flashrom.c 56.2 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>
Stefan Tauner's avatar
Stefan Tauner committed
32
#include <errno.h>
33
#include <ctype.h>
34
#include <getopt.h>
35 36 37
#if HAVE_UTSNAME == 1
#include <sys/utsname.h>
#endif
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
38
#include "flash.h"
39
#include "flashchips.h"
40
#include "programmer.h"
41
#include "hwaccess.h"
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
42

43
const char flashrom_version[] = FLASHROM_VERSION;
Nico Huber's avatar
Nico Huber committed
44
const char *chip_to_probe = NULL;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
45 46
int verbose_screen = MSG_INFO;
int verbose_logfile = MSG_DEBUG2;
47

48
static enum programmer programmer = PROGRAMMER_INVALID;
49

Nico Huber's avatar
Nico Huber committed
50
static const char *programmer_param = NULL;
51

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

312 313 314 315 316 317 318 319 320 321 322 323
#if CONFIG_USBBLASTER_SPI == 1
	{
		.name			= "usbblaster_spi",
		.type			= USB,
		.devs.dev		= devs_usbblasterspi,
		.init			= usbblaster_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
324
	{0}, /* This entry corresponds to PROGRAMMER_INVALID. */
325
};
326

327
#define SHUTDOWN_MAXFN 32
328 329
static int shutdown_fn_count = 0;
struct shutdown_func_data {
330
	int (*func) (void *data);
331
	void *data;
332 333 334 335 336
} 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;
337

Stefan Tauner's avatar
Stefan Tauner committed
338 339 340
/* Did we change something or was every erase/write skipped (if any)? */
static bool all_skipped = true;

341
static int check_block_eraser(const struct flashctx *flash, int k, int log);
342

343 344 345 346 347 348 349 350
/* 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.
 */
351
int register_shutdown(int (*function) (void *data), void *data)
352 353
{
	if (shutdown_fn_count >= SHUTDOWN_MAXFN) {
354
		msg_perr("Tried to register more than %i shutdown functions.\n",
355 356 357
			 SHUTDOWN_MAXFN);
		return 1;
	}
358 359 360 361 362
	if (!may_register_shutdown) {
		msg_perr("Tried to register a shutdown function before "
			 "programmer init.\n");
		return 1;
	}
363 364 365 366 367 368 369
	shutdown_fn[shutdown_fn_count].func = function;
	shutdown_fn[shutdown_fn_count].data = data;
	shutdown_fn_count++;

	return 0;
}

Nico Huber's avatar
Nico Huber committed
370
int programmer_init(enum programmer prog, const char *param)
371
{
372
	int ret;
373 374 375 376 377 378

	if (prog >= PROGRAMMER_INVALID) {
		msg_perr("Invalid programmer specified!\n");
		return -1;
	}
	programmer = prog;
379 380 381 382 383 384
	/* Initialize all programmer specific data. */
	/* Default to unlimited decode sizes. */
	max_rom_decode = (const struct decode_sizes) {
		.parallel	= 0xffffffff,
		.lpc		= 0xffffffff,
		.fwh		= 0xffffffff,
385
		.spi		= 0xffffffff,
386 387 388 389 390
	};
	/* Default to top aligned flash at 4 GB. */
	flashbase = 0;
	/* Registering shutdown functions is now allowed. */
	may_register_shutdown = 1;
391 392
	/* Default to allowing writes. Broken programmers set this to 0. */
	programmer_may_write = 1;
393 394

	programmer_param = param;
395
	msg_pdbg("Initializing %s programmer\n", programmer_table[programmer].name);
396 397
	ret = programmer_table[programmer].init();
	if (programmer_param && strlen(programmer_param)) {
398 399 400 401 402 403 404 405 406 407 408 409 410 411
		if (ret != 0) {
			/* It is quite possible that any unhandled programmer parameter would have been valid,
			 * but an error in actual programmer init happened before the parameter was evaluated.
			 */
			msg_pwarn("Unhandled programmer parameters (possibly due to another failure): %s\n",
				  programmer_param);
		} else {
			/* Actual programmer init was successful, but the user specified an invalid or unusable
			 * (for the current programmer configuration) parameter.
			 */
			msg_perr("Unhandled programmer parameters: %s\n", programmer_param);
			msg_perr("Aborting.\n");
			ret = ERROR_FATAL;
		}
412 413
	}
	return ret;
414 415 416 417
}

int programmer_shutdown(void)
{
418 419
	int ret = 0;

420 421 422 423
	/* Registering shutdown functions is no longer allowed. */
	may_register_shutdown = 0;
	while (shutdown_fn_count > 0) {
		int i = --shutdown_fn_count;
424
		ret |= shutdown_fn[i].func(shutdown_fn[i].data);
425
	}
426

Stefan Tauner's avatar
Stefan Tauner committed
427
	programmer_param = NULL;
428 429
	registered_programmer_count = 0;

430
	return ret;
431 432
}

433
void *programmer_map_flash_region(const char *descr, uintptr_t phys_addr, size_t len)
434 435 436 437 438 439 440 441 442 443
{
	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);
}

444
void chip_writeb(const struct flashctx *flash, uint8_t val, chipaddr addr)
445
{
446
	flash->pgm->par.chip_writeb(flash, val, addr);
447 448
}

449
void chip_writew(const struct flashctx *flash, uint16_t val, chipaddr addr)
450
{
451
	flash->pgm->par.chip_writew(flash, val, addr);
452 453
}

454
void chip_writel(const struct flashctx *flash, uint32_t val, chipaddr addr)
455
{
456
	flash->pgm->par.chip_writel(flash, val, addr);
457 458
}

459 460
void chip_writen(const struct flashctx *flash, uint8_t *buf, chipaddr addr,
		 size_t len)
461
{
462
	flash->pgm->par.chip_writen(flash, buf, addr, len);
463 464
}

465
uint8_t chip_readb(const struct flashctx *flash, const chipaddr addr)
466
{
467
	return flash->pgm->par.chip_readb(flash, addr);
468 469
}

470
uint16_t chip_readw(const struct flashctx *flash, const chipaddr addr)
471
{
472
	return flash->pgm->par.chip_readw(flash, addr);
473 474
}

475
uint32_t chip_readl(const struct flashctx *flash, const chipaddr addr)
476
{
477
	return flash->pgm->par.chip_readl(flash, addr);
478 479
}

480 481
void chip_readn(const struct flashctx *flash, uint8_t *buf, chipaddr addr,
		size_t len)
482
{
483
	flash->pgm->par.chip_readn(flash, buf, addr, len);
484 485
}

486 487 488 489 490
void programmer_delay(int usecs)
{
	programmer_table[programmer].delay(usecs);
}

491
void map_flash_registers(struct flashctx *flash)
492
{
493
	size_t size = flash->chip->total_size * 1024;
494
	/* Flash registers live 4 MByte below the flash. */
495
	/* FIXME: This is incorrect for nonstandard flashbase. */
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
496
	flash->virtual_registers = (chipaddr)programmer_map_flash_region("flash chip registers", (0xFFFFFFFF - 0x400000 - size + 1), size);
497 498
}

499 500
int read_memmapped(struct flashctx *flash, uint8_t *buf, unsigned int start,
		   int unsigned len)
501
{
502
	chip_readn(flash, buf, flash->virtual_memory + start, len);
503

504 505 506
	return 0;
}

507 508 509 510 511
int min(int a, int b)
{
	return (a < b) ? a : b;
}

512 513 514 515 516
int max(int a, int b)
{
	return (a > b) ? a : b;
}

517 518 519 520 521 522 523 524 525
int bitcount(unsigned long a)
{
	int i = 0;
	for (; a != 0; a >>= 1)
		if (a & 1)
			i++;
	return i;
}

526 527 528 529 530 531
void tolower_string(char *str)
{
	for (; *str != '\0'; str++)
		*str = (char)tolower((unsigned char)*str);
}

532 533 534
char *strcat_realloc(char *dest, const char *src)
{
	dest = realloc(dest, strlen(dest) + strlen(src) + 1);
535 536
	if (!dest) {
		msg_gerr("Out of memory!\n");
537
		return NULL;
538
	}
539 540 541 542
	strcat(dest, src);
	return dest;
}

543
/* This is a somewhat hacked function similar in some ways to strtok().
544 545 546
 * 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.
547
 */
Nico Huber's avatar
Nico Huber committed
548
char *extract_param(const char *const *haystack, const char *needle, const char *delim)
549
{
550 551 552
	char *param_pos, *opt_pos, *rest;
	char *opt = NULL;
	int optlen;
553
	int needlelen;
554

555 556 557 558 559 560 561 562 563
	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;
564 565 566 567
	param_pos = strstr(*haystack, needle);
	do {
		if (!param_pos)
			return NULL;
568 569 570 571 572 573 574 575 576 577
		/* 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;
		}
578 579 580 581
		/* Continue searching. */
		param_pos++;
		param_pos = strstr(param_pos, needle);
	} while (1);
582

583
	if (param_pos) {
584 585 586 587 588 589
		/* 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) {
590
			msg_gerr("Out of memory!\n");
591 592
			exit(1);
		}
593 594 595 596 597 598 599
		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. */
600 601
	}

602
	return opt;
603 604
}

605
char *extract_programmer_param(const char *param_name)
606 607 608 609
{
	return extract_param(&programmer_param, param_name, ",");
}

610
/* Returns the number of well-defined erasers for a chip. */
611
static unsigned int count_usable_erasers(const struct flashctx *flash)
612 613 614 615 616 617 618 619 620 621
{
	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;
}

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
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;
}

642
/* start is an offset to the base address of the flash chip */
643 644
int check_erased_range(struct flashctx *flash, unsigned int start,
		       unsigned int len)
645 646 647 648 649
{
	int ret;
	uint8_t *cmpbuf = malloc(len);

	if (!cmpbuf) {
650
		msg_gerr("Could not allocate memory!\n");
651 652 653
		exit(1);
	}
	memset(cmpbuf, 0xff, len);
654
	ret = verify_range(flash, cmpbuf, start, len);
655 656 657 658
	free(cmpbuf);
	return ret;
}

659
/*
660
 * @cmpbuf	buffer to compare against, cmpbuf[0] is expected to match the
661
 *		flash content at location start
662 663 664 665
 * @start	offset to the base address of the flash chip
 * @len		length of the verified area
 * @return	0 for success, -1 for failure
 */
666
int verify_range(struct flashctx *flash, uint8_t *cmpbuf, unsigned int start, unsigned int len)
667
{
668
	uint8_t *readbuf = malloc(len);
669
	int ret = 0;
670 671 672 673

	if (!len)
		goto out_free;

674
	if (!flash->chip->read) {
675
		msg_cerr("ERROR: flashrom has no read function for this flash chip.\n");
676 677
		return 1;
	}
678
	if (!readbuf) {
679
		msg_gerr("Could not allocate memory!\n");
680 681 682
		exit(1);
	}

683
	if (start + len > flash->chip->total_size * 1024) {
684
		msg_gerr("Error: %s called with start 0x%x + len 0x%x >"
685
			" total_size 0x%x\n", __func__, start, len,
686
			flash->chip->total_size * 1024);
687 688 689
		ret = -1;
		goto out_free;
	}
690

691
	ret = flash->chip->read(flash, readbuf, start, len);
692 693 694 695 696 697
	if (ret) {
		msg_gerr("Verification impossible because read failed "
			 "at 0x%x (len 0x%x)\n", start, len);
		return ret;
	}

698
	ret = compare_range(cmpbuf, readbuf, start, len);
699 700 701 702 703
out_free:
	free(readbuf);
	return ret;
}

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
/* Helper function for need_erase() that focuses on granularities of gran bytes. */
static int need_erase_gran_bytes(uint8_t *have, uint8_t *want, unsigned int len, unsigned int gran)
{
	unsigned int i, j, limit;
	for (j = 0; j < len / gran; j++) {
		limit = min (gran, len - j * gran);
		/* Are 'have' and 'want' identical? */
		if (!memcmp(have + j * gran, want + j * gran, limit))
			continue;
		/* have needs to be in erased state. */
		for (i = 0; i < limit; i++)
			if (have[j * gran + i] != 0xff)
				return 1;
	}
	return 0;
}

721
/*
722 723 724
 * 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.
725 726 727
 *
 * Warning: This function assumes that @have and @want point to naturally
 * aligned regions.
728 729 730
 *
 * @have        buffer with current content
 * @want        buffer with desired content
731
 * @len		length of the checked area
732 733 734
 * @gran	write granularity (enum, not count)
 * @return      0 if no erase is needed, 1 otherwise
 */
735
int need_erase(uint8_t *have, uint8_t *want, unsigned int len, enum write_granularity gran)
736
{
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
737
	int result = 0;
738
	unsigned int i;
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755

	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:
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
		result = need_erase_gran_bytes(have, want, len, 256);
		break;
	case write_gran_264bytes:
		result = need_erase_gran_bytes(have, want, len, 264);
		break;
	case write_gran_512bytes:
		result = need_erase_gran_bytes(have, want, len, 512);
		break;
	case write_gran_528bytes:
		result = need_erase_gran_bytes(have, want, len, 528);
		break;
	case write_gran_1024bytes:
		result = need_erase_gran_bytes(have, want, len, 1024);
		break;
	case write_gran_1056bytes:
		result = need_erase_gran_bytes(have, want, len, 1056);
772
		break;
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
	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)
793 794 795 796 797
 * @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
798 799 800 801 802
 *
 * 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.
 */
803 804 805
static unsigned int get_next_write(uint8_t *have, uint8_t *want, unsigned int len,
			  unsigned int *first_start,
			  enum write_granularity gran)
806
{
807 808 809
	int need_write = 0;
	unsigned int rel_start = 0, first_len = 0;
	unsigned int i, limit, stride;
810 811 812 813

	switch (gran) {
	case write_gran_1bit:
	case write_gran_1byte:
814
		stride = 1;
815 816
		break;
	case write_gran_256bytes:
817
		stride = 256;
818
		break;
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
	case write_gran_264bytes:
		stride = 264;
		break;
	case write_gran_512bytes:
		stride = 512;
		break;
	case write_gran_528bytes:
		stride = 528;
		break;
	case write_gran_1024bytes:
		stride = 1024;
		break;
	case write_gran_1056bytes:
		stride = 1056;
		break;
834 835 836
	default:
		msg_cerr("%s: Unsupported granularity! Please report a bug at "
			 "flashrom@flashrom.org\n", __func__);
837 838 839 840
		/* Claim that no write was needed. A write with unknown
		 * granularity is too dangerous to try.
		 */
		return 0;
841
	}
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	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;
			}
		}
	}
860
	if (need_write)
861
		first_len = min(i * stride - rel_start, len);
862
	*first_start += rel_start;
863
	return first_len;
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
/* 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) {
920
		msg_gerr("Invalid buffer!\n");
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
		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;
}

1002 1003 1004
int check_max_decode(enum chipbustype buses, uint32_t size)
{
	int limitexceeded = 0;
1005 1006

	if ((buses & BUS_PARALLEL) && (max_rom_decode.parallel < size)) {
1007
		limitexceeded++;
1008
		msg_pdbg("Chip size %u kB is bigger than supported "
1009 1010 1011 1012
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.parallel / 1024, "Parallel");
1013
	}
1014
	if ((buses & BUS_LPC) && (max_rom_decode.lpc < size)) {
1015
		limitexceeded++;
1016
		msg_pdbg("Chip size %u kB is bigger than supported "
1017 1018 1019 1020
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.lpc / 1024, "LPC");
1021
	}
1022
	if ((buses & BUS_FWH) && (max_rom_decode.fwh < size)) {
1023
		limitexceeded++;
1024
		msg_pdbg("Chip size %u kB is bigger than supported "
1025 1026 1027 1028
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.fwh / 1024, "FWH");
1029
	}
1030
	if ((buses & BUS_SPI) && (max_rom_decode.spi < size)) {
1031
		limitexceeded++;
1032
		msg_pdbg("Chip size %u kB is bigger than supported "
1033 1034 1035 1036
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.spi / 1024, "SPI");
1037 1038 1039 1040 1041 1042 1043
	}
	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)
1044
		/* FIXME: This message is designed towards CLI users. */
1045
		msg_pdbg("There is at least one common chip/programmer "
1046 1047
			 "interface which can support a chip of this size. "
			 "You can try --force at your own risk.\n");
1048 1049 1050
	return 1;
}

1051
int probe_flash(struct registered_programmer *pgm, int startchip, struct flashctx *flash, int force)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1052
{
1053
	const struct flashchip *chip;
1054
	unsigned long base = 0;
1055
	char location[64];
1056 1057
	uint32_t size;
	enum chipbustype buses_common;
1058
	char *tmp;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1059

1060 1061
	for (chip = flashchips + startchip; chip && chip->name; chip++) {
		if (chip_to_probe && strcmp(chip->name, chip_to_probe) != 0)
1062
			continue;
1063
		buses_common = pgm->buses_supported & chip->bustype;
1064
		if (!buses_common)
1065
			continue;
1066 1067 1068
		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");
1069 1070
			continue;
		}
Stefan Reinauer's avatar
Stefan Reinauer committed
1071

1072
		size = chip->total_size * 1024;
1073
		check_max_decode(buses_common, size);
Stefan Reinauer's avatar
Stefan Reinauer committed
1074

1075
		/* Start filling in the dynamic data. */
1076 1077 1078 1079 1080 1081 1082
		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;
1083

1084
		base = flashbase ? flashbase : (0xffffffff - size + 1);
1085
		flash->virtual_memory = (chipaddr)programmer_map_flash_region("flash chip", base, size);
1086

1087 1088 1089
		/* 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.
		 */
1090 1091 1092
		if (force)
			break;

1093
		if (flash->chip->probe(flash) != 1)
1094 1095
			goto notfound;

1096 1097
		/* 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
1098 1099 1100 1101
		 * 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.
1102
		 */
1103
		if (startchip == 0 && flash->chip->model_id == SFDP_DEVICE_ID) {
Stefan Tauner's avatar
Stefan Tauner committed
1104 1105 1106
			msg_cinfo("===\n"
				  "SFDP has autodetected a flash chip which is "
				  "not natively supported by flashrom yet.\n");
1107
			if (count_usable_erasers(flash) == 0)
Stefan Tauner's avatar
Stefan Tauner committed
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
				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");

1118 1119 1120 1121 1122
			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
1123 1124 1125
				  "===\n");
		}

1126 1127
		/* First flash chip detected on this bus. */
		if (startchip == 0)
1128
			break;
1129 1130 1131 1132
		/* 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. */
1133
notfound:
1134 1135 1136 1137
		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
1138
	}
Uwe Hermann's avatar
Uwe Hermann committed
1139

1140
	if (!flash->chip)
1141
		return -1;
1142

1143 1144
#if CONFIG_INTERNAL == 1
	if (programmer_table[programmer].map_flash_region == physmap)
1145
		snprintf(location, sizeof(location), "at physical address 0x%lx", base);
1146 1147
	else
#endif
1148 1149
		snprintf(location, sizeof(location), "on %s", programmer_table[programmer].name);

1150 1151 1152
	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);
1153
	free(tmp);
1154

1155 1156 1157 1158
	/* 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)
1159 1160
		if (flash->chip->printlock)
			flash->chip->printlock(flash);
1161

1162
	/* Return position of matching chip. */
1163
	return chip - flashchips;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1164 1165
}

1166 1167
int read_buf_from_file(unsigned char *buf, unsigned long size,
		       const char *filename)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1168
{
Nico Huber's avatar
Nico Huber committed
1169 1170 1171 1172
#ifdef __LIBPAYLOAD__
	msg_gerr("Error: No file I/O support in libpayload\n");
	return 1;
#else
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1173 1174 1175 1176 1177
	unsigned long numbytes;
	FILE *image;
	struct stat image_stat;

	if ((image = fopen(filename, "rb")) == NULL) {
Stefan Tauner's avatar
Stefan Tauner committed
1178
		msg_gerr("Error: opening file \"%s\" failed: %s\n", filename, strerror(errno));
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1179 1180 1181
		return 1;
	}
	if (fstat(fileno(image), &image_stat) != 0) {
Stefan Tauner's avatar
Stefan Tauner committed
1182
		msg_gerr("Error: getting metadata of file \"%s\" failed: %s\n", filename, strerror(errno));
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1183 1184 1185 1186
		fclose(image);
		return 1;
	}
	if (image_stat.st_size != size) {
1187
		msg_gerr("Error: Image size (%jd B) doesn't match the flash chip's size (%lu B)!\n",
Stefan Tauner's avatar
Stefan Tauner committed
1188
			 (intmax_t)image_stat.st_size, size);
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1189 1190 1191 1192 1193
		fclose(image);
		return 1;
	}
	numbytes = fread(buf, 1, size, image);
	if (fclose(image)) {
Stefan Tauner's avatar
Stefan Tauner committed
1194
		msg_gerr("Error: closing file \"%s\" failed: %s\n", filename, strerror(errno));
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1195 1196 1197 1198 1199 1200 1201 1202
		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;
Nico Huber's avatar
Nico Huber committed
1203
#endif
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1204 1205
}

1206 1207
int write_buf_to_file(unsigned char *buf, unsigned long size,
		      const char *filename)
1208
{
Nico Huber's avatar
Nico Huber committed
1209 1210 1211 1212
#ifdef __LIBPAYLOAD__
	msg_gerr("Error: No file I/O support in libpayload\n");
	return 1;
#else
1213 1214
	unsigned long numbytes;
	FILE *image;
1215 1216

	if (!filename) {
1217
		msg_gerr("No filename specified.\n");
1218 1219
		return 1;
	}
1220
	if ((image = fopen(filename, "wb")) == NULL) {
Stefan Tauner's avatar
Stefan Tauner committed
1221
		msg_gerr("Error: opening file \"%s\" failed: %s\n", filename, strerror(errno));
1222
		return 1;
1223
	}
1224 1225 1226

	numbytes = fwrite(buf, 1, size, image);
	fclose(image);
1227 1228 1229
	if (numbytes != size) {
		msg_gerr("File %s could not be written completely.\n",
			 filename);
1230
		return 1;
1231
	}
1232
	return 0;
Nico Huber's avatar
Nico Huber committed
1233
#endif
1234 1235
}

1236
int read_flash_to_file(struct flashctx *flash, const char *filename)
1237
{
1238
	unsigned long size = flash->chip->total_size * 1024;
1239 1240 1241 1242 1243 1244 1245 1246 1247
	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;
	}
1248
	if (!flash->chip->read) {
1249 1250 1251 1252
		msg_cerr("No read function available for this flash chip.\n");
		ret = 1;
		goto out_free;
	}
1253
	if (flash->chip->read(flash, buf, 0, size)) {
1254 1255 1256 1257 1258
		msg_cerr("Read operation failed!\n");
		ret = 1;
		goto out_free;
	}

Stefan Tauner's avatar
Stefan Tauner committed
1259
	ret = write_buf_to_file(buf, size, filename);
1260 1261 1262 1263 1264 1265
out_free:
	free(buf);
	msg_cinfo("%s.\n", ret ? "FAILED" : "done");
	return ret;
}

1266 1267
/* This function shares a lot of its structure with erase_and_write_flash() and
 * walk_eraseregions().
1268 1269
 * Even if an error is found, the function will keep going and check the rest.
 */
1270
static int selfcheck_eraseblocks(const struct flashchip *chip)
1271
{
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1272 1273
	int i, j, k;
	int ret = 0;
1274 1275 1276

	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
		unsigned int done = 0;
1277
		struct block_eraser eraser = chip->block_erasers[k];
1278 1279 1280 1281 1282 1283 1284 1285

		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",
1286
					chip->name, k, i);
1287
				ret = 1;
1288 1289 1290 1291 1292 1293 1294
			}
			/* 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",
1295
					chip->name, k, i);
1296
				ret = 1;
1297 1298 1299 1300
			}
			done += eraser.eraseblocks[i].count *
				eraser.eraseblocks[i].size;
		}
1301 1302
		/* Empty eraseblock definition with erase function.  */
		if (!done && eraser.block_erase)
1303
			msg_gspew("Strange: Empty eraseblock definition with "
1304
				  "non-empty erase function. Not an error.\n");
1305 1306
		if (!done)
			continue;
1307
		if (done != chip->total_size * 1024) {
1308 1309 1310
			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"
1311 1312
				" flashrom@flashrom.org\n", chip->name, k,
				done, chip->total_size * 1024);
1313
			ret = 1;
1314
		}
1315 1316 1317 1318 1319 1320
		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.
		 */
1321
		for (j = k + 1; j < NUM_ERASEFUNCTIONS; j++) {
1322
			if (eraser.block_erase ==
1323
			    chip->block_erasers[j].block_erase) {
1324 1325 1326
				msg_gerr("ERROR: Flash chip %s erase function "
					"%i and %i are identical. Please report"
					" a bug at flashrom@flashrom.org\n",
1327
					chip->name, k, j);
1328 1329
				ret = 1;
			}
1330
		}
1331
	}
1332
	return ret;
1333 1334
}

1335
static int erase_and_write_block_helper(struct flashctx *flash,
1336
					unsigned int start, unsigned int len,
1337
					uint8_t *curcontents,
1338
					uint8_t *newcontents,
1339
					int (*erasefn) (struct flashctx *flash,
1340 1341 1342
							unsigned int addr,
							unsigned int len))
{
1343 1344
	unsigned int starthere = 0, lenhere = 0;
	int ret = 0, skip = 1, writecount = 0;
1345
	enum write_granularity gran = flash->chip->gran;
1346

1347
	/* curcontents and newcontents are opaque to walk_eraseregions, and
1348 1349
	 * need to be adjusted here to keep the impression of proper abstraction
	 */
1350
	curcontents += start;
1351 1352
	newcontents += start;
	msg_cdbg(":");
1353
	if (need_erase(curcontents, newcontents, len, gran)) {
1354 1355 1356 1357
		msg_cdbg("E");
		ret = erasefn(flash, start, len);
		if (ret)
			return ret;
1358 1359 1360 1361
		if (check_erased_range(flash, start, len)) {
			msg_cerr("ERASE FAILED!\n");
			return -1;
		}
1362 1363
		/* Erase was successful. Adjust curcontents. */
		memset(curcontents, 0xff, len);
1364 1365
		skip = 0;
	}
1366 1367 1368 1369
	/* 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))) {
1370 1371 1372
		if (!writecount++)
			msg_cdbg("W");
		/* Needs the partial write function signature. */
1373
		ret = flash->chip->write(flash, newcontents + starthere,
1374 1375 1376 1377 1378 1379 1380 1381
				   start + starthere, lenhere);
		if (ret)
			return ret;
		starthere += lenhere;
		skip = 0;
	}
	if (skip)
		msg_cdbg("S");
1382 1383
	else
		all_skipped = false;
1384 1385 1386
	return ret;
}

1387 1388
static int walk_eraseregions(struct flashctx *flash, int erasefunction,
			     int (*do_something) (struct flashctx *flash,
1389
						  unsigned int addr,
1390 1391 1392 1393
						  unsigned int len,
						  uint8_t *param1,
						  uint8_t *param2,
						  int (*erasefn) (
1394
							struct flashctx *flash,
1395 1396 1397
							unsigned int addr,
							unsigned int len)),
			     void *param1, void *param2)
1398 1399
{
	int i, j;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1400 1401
	unsigned int start = 0;
	unsigned int len;
1402
	struct block_eraser eraser = flash->chip->block_erasers[erasefunction];
1403

1404 1405 1406 1407 1408 1409
	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++) {
1410 1411 1412 1413
			/* Print this for every block except the first one. */
			if (i || j)
				msg_cdbg(", ");
			msg_cdbg("0x%06x-0x%06x", start,
1414
				     start + len - 1);
1415 1416
			if (do_something(flash, start, len, param1, param2,
					 eraser.block_erase)) {
1417
				return 1;
1418
			}
1419 1420 1421
			start += len;
		}
	}
1422
	msg_cdbg("\n");
1423 1424 1425
	return 0;
}

1426
static int check_block_eraser(const struct flashctx *flash, int k, int log)
1427
{
1428
	struct block_eraser eraser = flash->chip->block_erasers[k];
1429 1430 1431 1432 1433 1434 1435 1436 1437

	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
1438
				 "block erase function is not implemented. ");
1439 1440 1441 1442 1443
		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
1444
				 "eraseblock layout is not defined. ");
1445 1446
		return 1;
	}
1447
	// TODO: Once erase functions are annotated with allowed buses, check that as well.
1448 1449 1450
	return 0;
}

1451
int erase_and_write_flash(struct flashctx *flash, uint8_t *oldcontents,
1452
			  uint8_t *newcontents)
1453
{
1454
	int k, ret = 1;
1455
	uint8_t *curcontents;
1456
	unsigned long size = flash->chip->total_size * 1024;
1457
	unsigned int usable_erasefunctions = count_usable_erasers(flash);
1458 1459

	msg_cinfo("Erasing and writing flash chip... ");
1460 1461 1462 1463 1464
	curcontents = malloc(size);
	if (!curcontents) {
		msg_gerr("Out of memory!\n");
		exit(1);
	}
1465 1466
	/* Copy oldcontents to curcontents to avoid clobbering oldcontents. */
	memcpy(curcontents, oldcontents, size);
1467 1468

	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
1469 1470
		if (k != 0)
			msg_cdbg("Looking for another erase function.\n");
1471 1472 1473 1474
		if (!usable_erasefunctions) {
			msg_cdbg("No usable erase functions left.\n");
			break;
		}
1475 1476
		msg_cdbg("Trying erase function %i... ", k);
		if (check_block_eraser(flash, k, 1))
1477
			continue;
1478
		usable_erasefunctions--;
1479 1480
		ret = walk_eraseregions(flash, k, &erase_and_write_block_helper,
					curcontents, newcontents);
1481 1482 1483
		/* If everything is OK, don't try another erase function. */
		if (!ret)
			break;
1484
		/* Write/erase failed, so try to find out what the current chip
1485 1486
		 * contents are. If no usable erase functions remain, we can
		 * skip this: the next iteration will break immediately anyway.
1487
		 */
1488 1489
		if (!usable_erasefunctions)
			continue;
1490 1491 1492 1493
		/* Reading the whole chip may take a while, inform the user even
		 * in non-verbose mode.
		 */
		msg_cinfo("Reading current flash chip contents... ");
1494
		if (flash->chip->read(flash, curcontents, 0, size)) {
1495
			/* Now we are truly screwed. Read failed as well. */
1496
			msg_cerr("Can't read anymore! Aborting.\n");
1497 1498 1499 1500 1501
			/* We have no idea about the flash chip contents, so
			 * retrying with another erase function is pointless.
			 */
			break;
		}
1502
		msg_cinfo("done. ");
1503
	}
1504 1505
	/* Free the scratchpad. */
	free(curcontents);
1506

1507
	if (ret) {
1508
		msg_cerr("FAILED!\n");
1509
	} else {
1510 1511
		if (all_skipped)
			msg_cinfo("\nWarning: Chip content is identical to the requested image.\n");
1512
		msg_cinfo("Erase/write done.\n");
1513 1514
	}
	return ret;
1515 1516
}

1517
static void nonfatal_help_message(void)
1518
{
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
	msg_gerr("Writing to the flash chip apparently didn't do anything.\n");
#if CONFIG_INTERNAL == 1
	if (programmer == PROGRAMMER_INTERNAL)
		msg_gerr("This means we have to add special support for your board, programmer or flash\n"
			 "chip. Please report this on IRC at chat.freenode.net (channel #flashrom) or\n"
			 "mail flashrom@flashrom.org, thanks!\n"
			 "-------------------------------------------------------------------------------\n"
			 "You may now reboot or simply leave the machine running.\n");
	else
#endif
		msg_gerr("Please check the connections (especially those to write protection pins) between\n"
			 "the programmer and the flash chip. If you think the error is caused by flashrom\n"
			 "please report this on IRC at chat.freenode.net (channel #flashrom) or\n"
			 "mail flashrom@flashrom.org, thanks!\n");
1533 1534
}

1535
static void emergency_help_message(void)
1536
{
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
	msg_gerr("Your flash chip is in an unknown state.\n");
#if CONFIG_INTERNAL == 1
	if (programmer == PROGRAMMER_INTERNAL)
		msg_gerr("Get help on IRC at chat.freenode.net (channel #flashrom) or\n"
			"mail flashrom@flashrom.org with the subject \"FAILED: <your board name>\"!\n"
			"-------------------------------------------------------------------------------\n"
			"DO NOT REBOOT OR POWEROFF!\n");
	else
#endif
		msg_gerr("Please report this on IRC at chat.freenode.net (channel #flashrom) or\n"
			 "mail flashrom@flashrom.org, thanks!\n");
1548 1549
}

1550
/* The way to go if you want a delimited list of programmers */
1551
void list_programmers(const char *delim)
1552 1553 1554
{
	enum programmer p;
	for (p = 0; p < PROGRAMMER_INVALID; p++) {
1555
		msg_ginfo("%s", programmer_table[p].name);
1556
		if (p < PROGRAMMER_INVALID - 1)
1557
			msg_ginfo("%s", delim);
1558
	}
1559
	msg_ginfo("\n");	
1560 1561
}

1562 1563 1564
void list_programmers_linebreak(int startcol, int cols, int paren)
{
	const char *pname;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1565 1566
	int pnamelen;
	int remaining = 0, firstline = 1;
1567
	enum programmer p;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1568
	int i;
1569 1570 1571 1572 1573 1574 1575 1576

	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
1577
				msg_ginfo("\n");
1578
			for (i = 0; i < startcol; i++)
1579
				msg_ginfo(" ");
1580 1581
			remaining = cols - startcol;
		} else {
1582
			msg_ginfo(" ");
1583 1584 1585
			remaining--;
		}
		if (paren && (p == 0)) {
1586
			msg_ginfo("(");
1587 1588
			remaining--;
		}
1589
		msg_ginfo("%s", pname);
1590 1591
		remaining -= pnamelen;
		if (p < PROGRAMMER_INVALID - 1) {
1592
			msg_ginfo(",");
1593 1594 1595
			remaining--;
		} else {
			if (paren)
1596
				msg_ginfo(")");
1597 1598 1599 1600
		}
	}
}

1601 1602
void print_sysinfo(void)
{
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
#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
1629 1630
	struct utsname osinfo;

1631
	uname(&osinfo);
1632 1633 1634 1635 1636
	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
1637 1638 1639 1640 1641
}

void print_buildinfo(void)
{
	msg_gdbg("flashrom was built with");
1642 1643
#if NEED_PCI == 1
#ifdef PCILIB_VERSION
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1644
	msg_gdbg(" libpci %s,", PCILIB_VERSION);
1645
#else
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1646
	msg_gdbg(" unknown PCI library,");
1647 1648 1649
#endif
#endif
#ifdef __clang__
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1650
	msg_gdbg(" LLVM Clang");
1651
#ifdef __clang_version__
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1652
	msg_gdbg(" %s,", __clang_version__);
1653
#else
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1654
	msg_gdbg(" unknown version (before r102686),");
1655
#endif
1656
#elif defined(__GNUC__)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1657
	msg_gdbg(" GCC");
1658
#ifdef __VERSION__
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1659
	msg_gdbg(" %s,", __VERSION__);
1660
#else
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1661
	msg_gdbg(" unknown version,");
1662
#endif
1663
#else
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1664
	msg_gdbg(" unknown compiler,");
1665
#endif
1666
#if defined (__FLASHROM_LITTLE_ENDIAN__)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1667
	msg_gdbg(" little endian");
1668
#elif defined (__FLASHROM_BIG_ENDIAN__)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1669
	msg_gdbg(" big endian");
1670 1671
#else
#error Endianness could not be determined
1672
#endif
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1673
	msg_gdbg("\n");
1674 1675
}

1676 1677
void print_version(void)
{
1678
	msg_ginfo("flashrom v%s", flashrom_version);
1679
	print_sysinfo();
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1680
	msg_ginfo("\n");
1681 1682
}

1683 1684 1685
void print_banner(void)
{
	msg_ginfo("flashrom is free software, get the source code at "
1686
		  "http://www.flashrom.org\n");
1687 1688 1689
	msg_ginfo("\n");
}

1690 1691
int selfcheck(void)
{
1692
	const struct flashchip *chip;
1693 1694
	int i;
	int ret = 0;
1695 1696 1697 1698

	/* Safety check. Instead of aborting after the first error, check
	 * if more errors exist.
	 */
1699
	if (ARRAY_SIZE(programmer_table) - 1 != PROGRAMMER_INVALID) {
1700
		msg_gerr("Programmer table miscompilation!\n");
1701
		ret = 1;
1702
	}
1703 1704 1705 1706 1707 1708 1709 1710 1711
	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;
		}
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
		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;
		}
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
		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;
		}
	}
1746
	/* It would be favorable if we could also check for correct termination
1747
	 * of the following arrays, but we don't know their sizes in here...
1748 1749 1750 1751 1752 1753 1754
	 * 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;
	}
1755 1756
	for (chip = flashchips; chip && chip->name; chip++)
		if (selfcheck_eraseblocks(chip))
1757
			ret = 1;
1758 1759 1760 1761 1762 1763

#if CONFIG_INTERNAL == 1
	if (chipset_enables == NULL) {
		msg_gerr("Chipset enables table does not exist!\n");
		ret = 1;
	}
1764
	if (board_matches == NULL) {
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
		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;
	}
1776
#endif
1777
	return ret;
1778 1779
}

1780
void check_chip_supported(const struct flashchip *chip)
1781
{
1782
	if (chip->feature_bits & FEATURE_OTP) {
1783 1784 1785 1786 1787 1788
		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");
	}
1789
	if (TEST_OK_MASK != (chip->tested & TEST_OK_MASK)) {
1790
		msg_cinfo("===\n");
1791
		if (chip->tested & TEST_BAD_MASK) {
1792
			msg_cinfo("This flash part has status NOT WORKING for operations:");
1793
			if (chip->tested & TEST_BAD_PROBE)
1794
				msg_cinfo(" PROBE");
1795
			if (chip->tested & TEST_BAD_READ)
1796
				msg_cinfo(" READ");
1797
			if (chip->tested & TEST_BAD_ERASE)
1798
				msg_cinfo(" ERASE");
1799
			if (chip->tested & TEST_BAD_WRITE)
1800 1801
				msg_cinfo(" WRITE");
			msg_cinfo("\n");
1802
		}
1803 1804 1805 1806
		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))) {
1807
			msg_cinfo("This flash part has status UNTESTED for operations:");
1808
			if (!(chip->tested & TEST_BAD_PROBE) && !(chip->tested & TEST_OK_PROBE))
1809
				msg_cinfo(" PROBE");
1810
			if (!(chip->tested & TEST_BAD_READ) && !(chip->tested & TEST_OK_READ))
1811
				msg_cinfo(" READ");
1812
			if (!(chip->tested & TEST_BAD_ERASE) && !(chip->tested & TEST_OK_ERASE))
1813
				msg_cinfo(" ERASE");
1814
			if (!(chip->tested & TEST_BAD_WRITE) && !(chip->tested & TEST_OK_WRITE))
1815 1816
				msg_cinfo(" WRITE");
			msg_cinfo("\n");
1817
		}
1818
		/* FIXME: This message is designed towards CLI users. */
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
		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
1829
			  "-VE, -Vw), and mention which mainboard or "
1830
			    "programmer you tested.\n"
1831 1832
			  "Please mention your board in the subject line. "
			    "Thanks for your help!\n");
1833 1834 1835
	}
}

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1836 1837
/* FIXME: This function signature needs to be improved once doit() has a better
 * function signature.
1838
 */
1839 1840
int chip_safety_check(const struct flashctx *flash, int force, int read_it, int write_it, int erase_it,
		      int verify_it)
1841
{
1842 1843
	const struct flashchip *chip = flash->chip;

1844 1845 1846 1847 1848 1849
	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
1850
		if (!force)
1851
			return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1852
		msg_cerr("Continuing anyway.\n");
1853 1854
	}

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1855 1856
	if (read_it || erase_it || write_it || verify_it) {
		/* Everything needs read. */
1857
		if (chip->tested & TEST_BAD_READ) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1858 1859
			msg_cerr("Read is not working on this chip. ");
			if (!force)
1860
				return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1861
			msg_cerr("Continuing anyway.\n");
1862
		}
1863
		if (!chip->read) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1864 1865
			msg_cerr("flashrom has no read function for this "
				 "flash chip.\n");
1866
			return 1;
1867
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1868 1869 1870
	}
	if (erase_it || write_it) {
		/* Write needs erase. */
1871
		if (chip->tested & TEST_BAD_ERASE) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1872 1873
			msg_cerr("Erase is not working on this chip. ");
			if (!force)
1874
				return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1875
			msg_cerr("Continuing anyway.\n");
1876
		}
1877
		if(count_usable_erasers(flash) == 0) {
1878 1879 1880 1881
			msg_cerr("flashrom has no erase function for this "
				 "flash chip.\n");
			return 1;
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1882 1883
	}
	if (write_it) {
1884
		if (chip->tested & TEST_BAD_WRITE) {
1885
			msg_cerr("Write is not working on this chip. ");
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1886
			if (!force)
1887
				return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1888
			msg_cerr("Continuing anyway.\n");
1889
		}
1890
		if (!chip->write) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1891 1892
			msg_cerr("flashrom has no write function for this "
				 "flash chip.\n");
1893 1894
			return 1;
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1895 1896 1897 1898 1899 1900 1901 1902
	}
	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.
 */
1903 1904
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
1905
{
1906 1907
	uint8_t *oldcontents;
	uint8_t *newcontents;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1908
	int ret = 0;
1909
	unsigned long size = flash->chip->total_size * 1024;
1910

1911
	if (chip_safety_check(flash, force, read_it, write_it, erase_it, verify_it)) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1912
		msg_cerr("Aborting.\n");
1913 1914
		ret = 1;
		goto out_nofree;
1915 1916
	}

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1917 1918 1919
	/* Given the existence of read locks, we want to unlock for read,
	 * erase and write.
	 */
1920 1921
	if (flash->chip->unlock)
		flash->chip->unlock(flash);
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1922 1923 1924

	if (read_it) {
		ret = read_flash_to_file(flash, filename);
1925
		goto out_nofree;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1926
	}
1927

1928 1929 1930 1931 1932
	oldcontents = malloc(size);
	if (!oldcontents) {
		msg_gerr("Out of memory!\n");
		exit(1);
	}
1933 1934
	/* Assume worst case: All bits are 0. */
	memset(oldcontents, 0x00, size);
1935 1936 1937 1938 1939
	newcontents = malloc(size);
	if (!newcontents) {
		msg_gerr("Out of memory!\n");
		exit(1);
	}
1940 1941 1942 1943 1944 1945 1946 1947
	/* 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
1948
	if (erase_it) {
1949 1950 1951 1952 1953 1954
		/* 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.
		 */
1955
		if (erase_and_write_flash(flash, oldcontents, newcontents)) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1956
			emergency_help_message();
1957
			ret = 1;
1958
		}
1959
		goto out;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1960 1961 1962
	}

	if (write_it || verify_it) {
1963
		if (read_buf_from_file(newcontents, size, filename)) {
1964 1965
			ret = 1;
			goto out;
1966 1967
		}

1968
#if CONFIG_INTERNAL == 1
1969 1970 1971 1972 1973 1974
		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");
1975 1976 1977
				ret = 1;
				goto out;
			}
1978
		}
1979
#endif
1980
	}
Ronald G. Minnich's avatar
Ronald G. Minnich committed
1981

1982 1983 1984 1985 1986 1987
	/* 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.
	 */
1988
	msg_cinfo("Reading old flash chip contents... ");
1989
	if (flash->chip->read(flash, oldcontents, 0, size)) {
1990
		ret = 1;
1991
		msg_cinfo("FAILED.\n");
1992
		goto out;
1993
	}
1994
	msg_cinfo("done.\n");
1995

1996 1997
	// This should be moved into each flash part's code to do it 
	// cleanly. This does the job.
1998
	handle_romentries(flash, oldcontents, newcontents);
1999

2000
	// ////////////////////////////////////////////////////////////
2001

2002
	if (write_it) {
2003 2004 2005
		if (erase_and_write_flash(flash, oldcontents, newcontents)) {
			msg_cerr("Uh oh. Erase/write failed. Checking if "
				 "anything changed.\n");
2006
			if (!flash->chip->read(flash, newcontents, 0, size)) {
2007
				if (!memcmp(oldcontents, newcontents, size)) {
2008
					msg_cinfo("Good. It seems nothing was changed.\n");
2009
					nonfatal_help_message();
2010 2011
					ret = 1;
					goto out;
2012 2013
				}
			}
2014
			emergency_help_message();
2015 2016
			ret = 1;
			goto out;
2017 2018
		}
	}
2019

Stefan Tauner's avatar
Stefan Tauner committed
2020 2021
	/* Verify only if we either did not try to write (verify operation) or actually changed something. */
	if (verify_it && (!write_it || !all_skipped)) {
2022 2023 2024 2025
		msg_cinfo("Verifying flash... ");

		if (write_it) {
			/* Work around chips which need some time to calm down. */
2026
			programmer_delay(1000*1000);
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
			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");
2038
	}
2039

2040 2041 2042 2043
out:
	free(oldcontents);
	free(newcontents);
out_nofree:
2044
	programmer_shutdown();
Stefan Reinauer's avatar
Stefan Reinauer committed
2045
	return ret;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
2046
}