flashrom.c 32.8 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 <fcntl.h>
25 26
#include <sys/types.h>
#include <sys/stat.h>
Ronald G. Minnich's avatar
Ronald G. Minnich committed
27
#include <string.h>
Ronald G. Minnich's avatar
Ronald G. Minnich committed
28
#include <stdlib.h>
29
#include <getopt.h>
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
30
#include "flash.h"
31
#include "flashchips.h"
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
32

33
const char *flashrom_version = FLASHROM_VERSION;
Ronald G. Minnich's avatar
Ronald G. Minnich committed
34
char *chip_to_probe = NULL;
Peter Stuge's avatar
Peter Stuge committed
35
int verbose = 0;
36 37

#if INTERNAL_SUPPORT == 1
38
enum programmer programmer = PROGRAMMER_INTERNAL;
39 40 41
#elif DUMMY_SUPPORT == 1
enum programmer programmer = PROGRAMMER_DUMMY;
#else
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
/* If neither internal nor dummy are selected, we must pick a sensible default.
 * Since there is no reason to prefer a particular external programmer, we fail
 * if more than one of them is selected. If only one is selected, it is clear
 * that the user wants that one to become the default.
 */
#if NIC3COM_SUPPORT+GFXNVIDIA_SUPPORT+DRKAISER_SUPPORT+SATASII_SUPPORT+FT2232_SPI_SUPPORT+SERPROG_SUPPORT+BUSPIRATE_SPI_SUPPORT > 1
#error Please enable either CONFIG_DUMMY or CONFIG_INTERNAL or disable support for all external programmers except one.
#endif
enum programmer programmer =
#if NIC3COM_SUPPORT == 1
	PROGRAMMER_NIC3COM
#endif
#if GFXNVIDIA_SUPPORT == 1
	PROGRAMMER_GFXNVIDIA
#endif
#if DRKAISER_SUPPORT == 1
	PROGRAMMER_DRKAISER
#endif
#if SATASII_SUPPORT == 1
	PROGRAMMER_SATASII
#endif
#if FT2232_SPI_SUPPORT == 1
	PROGRAMMER_FT2232SPI
#endif
#if SERPROG_SUPPORT == 1
	PROGRAMMER_SERPROG
#endif
#if BUSPIRATE_SPI_SUPPORT == 1
	PROGRAMMER_BUSPIRATESPI
#endif
;
73 74
#endif

75
char *programmer_param = NULL;
76

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
/**
 * flashrom defaults to Parallel/LPC/FWH flash devices. If a known host
 * controller is found, the init routine sets the buses_supported bitfield to
 * contain the supported buses for that controller.
 */
enum chipbustype buses_supported = CHIP_BUSTYPE_NONSPI;

/**
 * Programmers supporting multiple buses can have differing size limits on
 * each bus. Store the limits for each bus in a common struct.
 */
struct decode_sizes max_rom_decode = {
	.parallel	= 0xffffffff,
	.lpc		= 0xffffffff,
	.fwh		= 0xffffffff,
	.spi		= 0xffffffff
};

95
const struct programmer_entry programmer_table[] = {
96
#if INTERNAL_SUPPORT == 1
97
	{
98
		.name			= "internal",
99 100
		.init			= internal_init,
		.shutdown		= internal_shutdown,
101 102
		.map_flash_region	= physmap,
		.unmap_flash_region	= physunmap,
103 104 105
		.chip_readb		= internal_chip_readb,
		.chip_readw		= internal_chip_readw,
		.chip_readl		= internal_chip_readl,
106
		.chip_readn		= internal_chip_readn,
107 108 109
		.chip_writeb		= internal_chip_writeb,
		.chip_writew		= internal_chip_writew,
		.chip_writel		= internal_chip_writel,
110
		.chip_writen		= fallback_chip_writen,
111
		.delay			= internal_delay,
112
	},
113
#endif
114

115
#if DUMMY_SUPPORT == 1
116
	{
117
		.name			= "dummy",
118 119
		.init			= dummy_init,
		.shutdown		= dummy_shutdown,
120 121
		.map_flash_region	= dummy_map,
		.unmap_flash_region	= dummy_unmap,
122 123 124
		.chip_readb		= dummy_chip_readb,
		.chip_readw		= dummy_chip_readw,
		.chip_readl		= dummy_chip_readl,
125
		.chip_readn		= dummy_chip_readn,
126 127 128
		.chip_writeb		= dummy_chip_writeb,
		.chip_writew		= dummy_chip_writew,
		.chip_writel		= dummy_chip_writel,
129
		.chip_writen		= dummy_chip_writen,
130
		.delay			= internal_delay,
131
	},
132
#endif
133

134
#if NIC3COM_SUPPORT == 1
135
	{
136
		.name			= "nic3com",
137 138
		.init			= nic3com_init,
		.shutdown		= nic3com_shutdown,
139 140
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
141
		.chip_readb		= nic3com_chip_readb,
142 143
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
144
		.chip_readn		= fallback_chip_readn,
145
		.chip_writeb		= nic3com_chip_writeb,
146 147
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
148
		.chip_writen		= fallback_chip_writen,
149
		.delay			= internal_delay,
150
	},
151
#endif
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
#if GFXNVIDIA_SUPPORT == 1
	{
		.name			= "gfxnvidia",
		.init			= gfxnvidia_init,
		.shutdown		= gfxnvidia_shutdown,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.chip_readb		= gfxnvidia_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
		.chip_writeb		= gfxnvidia_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
#endif

172
#if DRKAISER_SUPPORT == 1
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	{
		.name			= "drkaiser",
		.init			= drkaiser_init,
		.shutdown		= drkaiser_shutdown,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.chip_readb		= drkaiser_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
		.chip_writeb		= drkaiser_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
189
#endif
190

191
#if SATASII_SUPPORT == 1
192
	{
193
		.name			= "satasii",
194 195
		.init			= satasii_init,
		.shutdown		= satasii_shutdown,
196 197
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
198 199 200
		.chip_readb		= satasii_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
201
		.chip_readn		= fallback_chip_readn,
202 203 204
		.chip_writeb		= satasii_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
205
		.chip_writen		= fallback_chip_writen,
206
		.delay			= internal_delay,
207
	},
208
#endif
209

210
#if INTERNAL_SUPPORT == 1
211
	{
212
		.name			= "it87spi",
213
		.init			= it87spi_init,
214
		.shutdown		= noop_shutdown,
215 216
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
217
		.chip_readb		= noop_chip_readb,
218 219 220
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
221
		.chip_writeb		= noop_chip_writeb,
222 223 224
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
225
		.delay			= internal_delay,
226
	},
227
#endif
228

229
#if FT2232_SPI_SUPPORT == 1
230
	{
231
		.name			= "ft2232spi",
232
		.init			= ft2232_spi_init,
233
		.shutdown		= noop_shutdown, /* Missing shutdown */
234 235
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
236
		.chip_readb		= noop_chip_readb,
237 238 239
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
240
		.chip_writeb		= noop_chip_writeb,
241 242 243 244 245
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
246
#endif
247

248
#if SERPROG_SUPPORT == 1
249
	{
250
		.name			= "serprog",
251 252 253 254 255 256 257 258 259 260 261 262 263 264
		.init			= serprog_init,
		.shutdown		= serprog_shutdown,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.chip_readb		= serprog_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= serprog_chip_readn,
		.chip_writeb		= serprog_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= serprog_delay,
	},
265
#endif
266

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
#if BUSPIRATE_SPI_SUPPORT == 1
	{
		.name			= "buspiratespi",
		.init			= buspirate_spi_init,
		.shutdown		= buspirate_spi_shutdown,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.chip_readb		= noop_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
		.chip_writeb		= noop_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
#endif

286
	{}, /* This entry corresponds to PROGRAMMER_INVALID. */
287
};
288

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
int programmer_init(void)
{
	return programmer_table[programmer].init();
}

int programmer_shutdown(void)
{
	return programmer_table[programmer].shutdown();
}

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);
}

void chip_writeb(uint8_t val, chipaddr addr)
{
	programmer_table[programmer].chip_writeb(val, addr);
}

void chip_writew(uint16_t val, chipaddr addr)
{
	programmer_table[programmer].chip_writew(val, addr);
}

void chip_writel(uint32_t val, chipaddr addr)
{
	programmer_table[programmer].chip_writel(val, addr);
}

326 327 328 329 330
void chip_writen(uint8_t *buf, chipaddr addr, size_t len)
{
	programmer_table[programmer].chip_writen(buf, addr, len);
}

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
uint8_t chip_readb(const chipaddr addr)
{
	return programmer_table[programmer].chip_readb(addr);
}

uint16_t chip_readw(const chipaddr addr)
{
	return programmer_table[programmer].chip_readw(addr);
}

uint32_t chip_readl(const chipaddr addr)
{
	return programmer_table[programmer].chip_readl(addr);
}

346 347 348 349 350
void chip_readn(uint8_t *buf, chipaddr addr, size_t len)
{
	programmer_table[programmer].chip_readn(buf, addr, len);
}

351 352 353 354 355
void programmer_delay(int usecs)
{
	programmer_table[programmer].delay(usecs);
}

356
void map_flash_registers(struct flashchip *flash)
357 358
{
	size_t size = flash->total_size * 1024;
359
	/* Flash registers live 4 MByte below the flash. */
360
	/* FIXME: This is incorrect for nonstandard flashbase. */
361
	flash->virtual_registers = (chipaddr)programmer_map_flash_region("flash chip registers", (0xFFFFFFFF - 0x400000 - size + 1), size);
362 363
}

364
int read_memmapped(struct flashchip *flash, uint8_t *buf, int start, int len)
365
{
366
	chip_readn(buf, flash->virtual_memory + start, len);
367 368 369 370
		
	return 0;
}

371 372
unsigned long flashbase = 0;

373 374 375 376 377
int min(int a, int b)
{
	return (a < b) ? a : b;
}

378 379 380 381 382
int max(int a, int b)
{
	return (a > b) ? a : b;
}

383 384 385 386 387 388 389 390 391
int bitcount(unsigned long a)
{
	int i = 0;
	for (; a != 0; a >>= 1)
		if (a & 1)
			i++;
	return i;
}

392 393 394 395 396 397 398 399 400
char *strcat_realloc(char *dest, const char *src)
{
	dest = realloc(dest, strlen(dest) + strlen(src) + 1);
	if (!dest)
		return NULL;
	strcat(dest, src);
	return dest;
}

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
/* This is a somewhat hacked function similar in some ways to strtok().
 * It will look for needle in haystack, return a copy of needle and remove
 * everything from the first occurrence of needle to the next delimiter
 * from haystack.
 */
char *extract_param(char **haystack, char *needle, char *delim)
{
	char *param_pos, *rest, *tmp;
	char *dev = NULL;
	int devlen;

	param_pos = strstr(*haystack, needle);
	do {
		if (!param_pos)
			return NULL;
		/* Beginning of the string? */
		if (param_pos == *haystack)
			break;
		/* After a delimiter? */
		if (strchr(delim, *(param_pos - 1)))
			break;
		/* Continue searching. */
		param_pos++;
		param_pos = strstr(param_pos, needle);
	} while (1);
		
	if (param_pos) {
		param_pos += strlen(needle);
		devlen = strcspn(param_pos, delim);
		if (devlen) {
			dev = malloc(devlen + 1);
			if (!dev) {
				fprintf(stderr, "Out of memory!\n");
				exit(1);
			}
			strncpy(dev, param_pos, devlen);
			dev[devlen] = '\0';
		}
		rest = param_pos + devlen;
		rest += strspn(rest, delim);
		param_pos -= strlen(needle);
		memmove(param_pos, rest, strlen(rest) + 1);
		tmp = realloc(*haystack, strlen(*haystack) + 1);
		if (!tmp) {
			fprintf(stderr, "Out of memory!\n");
			exit(1);
		}
		*haystack = tmp;
	}
	

	return dev;
}

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
/* start is an offset to the base address of the flash chip */
int check_erased_range(struct flashchip *flash, int start, int len)
{
	int ret;
	uint8_t *cmpbuf = malloc(len);

	if (!cmpbuf) {
		fprintf(stderr, "Could not allocate memory!\n");
		exit(1);
	}
	memset(cmpbuf, 0xff, len);
	ret = verify_range(flash, cmpbuf, start, len, "ERASE");
	free(cmpbuf);
	return ret;
}

/**
472 473
 * @cmpbuf	buffer to compare against, cmpbuf[0] is expected to match the
		flash content at location start
474 475 476 477 478 479 480 481 482 483
 * @start	offset to the base address of the flash chip
 * @len		length of the verified area
 * @message	string to print in the "FAILED" message
 * @return	0 for success, -1 for failure
 */
int verify_range(struct flashchip *flash, uint8_t *cmpbuf, int start, int len, char *message)
{
	int i, j, starthere, lenhere, ret = 0;
	int page_size = flash->page_size;
	uint8_t *readbuf = malloc(page_size);
484
	int failcount = 0;
485 486 487 488

	if (!len)
		goto out_free;

489 490 491 492
	if (!flash->read) {
		fprintf(stderr, "ERROR: flashrom has no read function for this flash chip.\n");
		return 1;
	}
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
	if (!readbuf) {
		fprintf(stderr, "Could not allocate memory!\n");
		exit(1);
	}

	if (start + len > flash->total_size * 1024) {
		fprintf(stderr, "Error: %s called with start 0x%x + len 0x%x >"
			" total_size 0x%x\n", __func__, start, len,
			flash->total_size * 1024);
		ret = -1;
		goto out_free;
	}
	if (!message)
		message = "VERIFY";
	
	/* Warning: This loop has a very unusual condition and body.
	 * The loop needs to go through each page with at least one affected
	 * byte. The lowest page number is (start / page_size) since that
	 * division rounds down. The highest page number we want is the page
	 * where the last byte of the range lives. That last byte has the
	 * address (start + len - 1), thus the highest page number is
	 * (start + len - 1) / page_size. Since we want to include that last
	 * page as well, the loop condition uses <=.
	 */
	for (i = start / page_size; i <= (start + len - 1) / page_size; i++) {
		/* Byte position of the first byte in the range in this page. */
		starthere = max(start, i * page_size);
		/* Length of bytes in the range in this page. */
		lenhere = min(start + len, (i + 1) * page_size) - starthere;
522
		flash->read(flash, readbuf, starthere, lenhere);
523 524
		for (j = 0; j < lenhere; j++) {
			if (cmpbuf[starthere - start + j] != readbuf[j]) {
525 526 527 528 529 530 531
				/* Only print the first failure. */
				if (!failcount++)
					fprintf(stderr, "%s FAILED at 0x%08x! "
						"Expected=0x%02x, Read=0x%02x,",
						message, starthere + j,
						cmpbuf[starthere - start + j],
						readbuf[j]);
532 533 534
			}
		}
	}
535 536 537 538 539
	if (failcount) {
		fprintf(stderr, " failed byte count from 0x%08x-0x%08x: 0x%x\n",
			start, start + len - 1, failcount);
		ret = -1;
	}
540 541 542 543 544 545

out_free:
	free(readbuf);
	return ret;
}

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
/* 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) {
		fprintf(stderr, "Invalid buffer!\n");
		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;
}

682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
int check_max_decode(enum chipbustype buses, uint32_t size)
{
	int limitexceeded = 0;
	if ((buses & CHIP_BUSTYPE_PARALLEL) &&
	    (max_rom_decode.parallel < size)) {
		limitexceeded++;
		printf_debug("Chip size %u kB is bigger than supported "
			     "size %u kB of chipset/board/programmer "
			     "for %s interface, "
			     "probe/read/erase/write may fail. ", size / 1024,
			     max_rom_decode.parallel / 1024, "Parallel");
	}
	if ((buses & CHIP_BUSTYPE_LPC) && (max_rom_decode.lpc < size)) {
		limitexceeded++;
		printf_debug("Chip size %u kB is bigger than supported "
			     "size %u kB of chipset/board/programmer "
			     "for %s interface, "
			     "probe/read/erase/write may fail. ", size / 1024,
			     max_rom_decode.lpc / 1024, "LPC");
	}
	if ((buses & CHIP_BUSTYPE_FWH) && (max_rom_decode.fwh < size)) {
		limitexceeded++;
		printf_debug("Chip size %u kB is bigger than supported "
			     "size %u kB of chipset/board/programmer "
			     "for %s interface, "
			     "probe/read/erase/write may fail. ", size / 1024,
			     max_rom_decode.fwh / 1024, "FWH");
	}
	if ((buses & CHIP_BUSTYPE_SPI) && (max_rom_decode.spi < size)) {
		limitexceeded++;
		printf_debug("Chip size %u kB is bigger than supported "
			     "size %u kB of chipset/board/programmer "
			     "for %s interface, "
			     "probe/read/erase/write may fail. ", size / 1024,
			     max_rom_decode.spi / 1024, "SPI");
	}
	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)
724
		/* FIXME: This message is designed towards CLI users. */
725 726 727 728 729 730
		printf_debug("There is at least one common chip/programmer "
			     "interface which can support a chip of this size. "
			     "You can try --force at your own risk.\n");
	return 1;
}

731
struct flashchip *probe_flash(struct flashchip *first_flash, int force)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
732
{
733
	struct flashchip *flash;
734 735 736
	unsigned long base = 0;
	uint32_t size;
	enum chipbustype buses_common;
737
	char *tmp;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
738

739
	for (flash = first_flash; flash && flash->name; flash++) {
740
		if (chip_to_probe && strcmp(flash->name, chip_to_probe) != 0)
741
			continue;
742 743
		printf_debug("Probing for %s %s, %d KB: ",
			     flash->vendor, flash->name, flash->total_size);
Peter Stuge's avatar
Peter Stuge committed
744
		if (!flash->probe && !force) {
745 746 747
			printf_debug("failed! flashrom has no probe function for this flash chip.\n");
			continue;
		}
748 749
		buses_common = buses_supported & flash->bustype;
		if (!buses_common) {
750 751 752 753 754 755 756 757
			tmp = flashbuses_to_text(buses_supported);
			printf_debug("skipped. Host bus type %s ", tmp);
			free(tmp);
			tmp = flashbuses_to_text(flash->bustype);
			printf_debug("and chip bus type %s are incompatible.\n", tmp);
			free(tmp);
			continue;
		}
Stefan Reinauer's avatar
Stefan Reinauer committed
758

759
		size = flash->total_size * 1024;
760
		check_max_decode(buses_common, size);
Stefan Reinauer's avatar
Stefan Reinauer committed
761

762
		base = flashbase ? flashbase : (0xffffffff - size + 1);
763
		flash->virtual_memory = (chipaddr)programmer_map_flash_region("flash chip", base, size);
764

765 766 767
		if (force)
			break;

768 769 770
		if (flash->probe(flash) != 1)
			goto notfound;

771 772
		if (first_flash == flashchips
		    || flash->model_id != GENERIC_DEVICE_ID)
773
			break;
Stefan Reinauer's avatar
Stefan Reinauer committed
774

775
notfound:
776
		programmer_unmap_flash_region((void *)flash->virtual_memory, size);
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
777
	}
Uwe Hermann's avatar
Uwe Hermann committed
778

779 780 781
	if (!flash || !flash->name)
		return NULL;

782 783 784 785
	printf("Found chip \"%s %s\" (%d KB, %s) at physical address 0x%lx.\n",
	       flash->vendor, flash->name, flash->total_size,
	       flashbuses_to_text(flash->bustype), base);

786
	return flash;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
787 788
}

Stefan Reinauer's avatar
Stefan Reinauer committed
789
int verify_flash(struct flashchip *flash, uint8_t *buf)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
790
{
791
	int ret;
792
	int total_size = flash->total_size * 1024;
793

794
	printf("Verifying flash... ");
795

796
	ret = verify_range(flash, buf, 0, total_size, NULL);
797

798 799
	if (!ret)
		printf("VERIFIED.          \n");
800

801
	return ret;
Ronald G. Minnich's avatar
Fixes  
Ronald G. Minnich committed
802 803
}

804
int read_flash(struct flashchip *flash, char *filename)
805 806 807 808 809
{
	unsigned long numbytes;
	FILE *image;
	unsigned long size = flash->total_size * 1024;
	unsigned char *buf = calloc(size, sizeof(char));
810 811 812 813 814

	if (!filename) {
		printf("Error: No filename specified.\n");
		return 1;
	}
815 816 817 818 819
	if ((image = fopen(filename, "w")) == NULL) {
		perror(filename);
		exit(1);
	}
	printf("Reading flash... ");
820 821 822 823 824
	if (!flash->read) {
		printf("FAILED!\n");
		fprintf(stderr, "ERROR: flashrom has no read function for this flash chip.\n");
		return 1;
	} else
825
		flash->read(flash, buf, 0, size);
826 827 828

	numbytes = fwrite(buf, 1, size, image);
	fclose(image);
829
	free(buf);
830 831 832 833 834 835
	printf("%s.\n", numbytes == size ? "done" : "FAILED");
	if (numbytes != size)
		return 1;
	return 0;
}

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 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
/* This function shares a lot of its structure with erase_flash(). */
int selfcheck_eraseblocks(struct flashchip *flash)
{
	int i, k;

	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
		unsigned int done = 0;
		struct block_eraser eraser = flash->block_erasers[k];

		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",
					flash->name, k, i);
				return 1;
				break;
			}
			/* 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",
					flash->name, k, i);
				return 1;
				break;
			}
			done += eraser.eraseblocks[i].count *
				eraser.eraseblocks[i].size;
		}
		/* This erase function is completely empty. */
		if (!done)
			continue;
		if (done != flash->total_size * 1024) {
			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"
				" flashrom@flashrom.org\n", flash->name, k,
				done, flash->total_size * 1024);
			return 1;
		}
	}
	return 0;
}

884 885
int erase_flash(struct flashchip *flash)
{
886
	int i, j, k, ret = 0, found = 0;
887
	unsigned int start, len;
888

889
	printf("Erasing flash chip... ");
890
	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
891
		unsigned int done = 0;
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
		struct block_eraser eraser = flash->block_erasers[k];

		printf_debug("Looking at blockwise erase function %i... ", k);
		if (!eraser.block_erase && !eraser.eraseblocks[0].count) {
			printf_debug("not defined. "
				"Looking for another erase function.\n");
			continue;
		}
		if (!eraser.block_erase && eraser.eraseblocks[0].count) {
			printf_debug("eraseblock layout is known, but no "
				"matching block erase function found. "
				"Looking for another erase function.\n");
			continue;
		}
		if (eraser.block_erase && !eraser.eraseblocks[0].count) {
			printf_debug("block erase function found, but "
				"eraseblock layout is unknown. "
				"Looking for another erase function.\n");
			continue;
		}
		found = 1;
		printf_debug("trying... ");
		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.
			 */
			for (j = 0; j < eraser.eraseblocks[i].count; j++) {
919 920 921 922 923
				start = done + eraser.eraseblocks[i].size * j;
				len = eraser.eraseblocks[i].size;
				printf_debug("0x%06x-0x%06x, ", start,
					     start + len - 1);
				ret = eraser.block_erase(flash, start, len);
924 925 926 927 928
				if (ret)
					break;
			}
			if (ret)
				break;
929 930
			done += eraser.eraseblocks[i].count *
				eraser.eraseblocks[i].size;
931
		}
932
		printf_debug("\n");
933 934 935 936 937 938 939 940 941 942 943
		/* If everything is OK, don't try another erase function. */
		if (!ret)
			break;
	}
	/* If no block erase function was found or block erase failed, retry. */
	if ((!found || ret) && (flash->erase)) {
		found = 1;
		printf_debug("Trying whole-chip erase function... ");
		ret = flash->erase(flash);
	}
	if (!found) {
944 945 946
		fprintf(stderr, "ERROR: flashrom has no erase function for this flash chip.\n");
		return 1;
	}
947

948 949 950 951 952 953
	if (ret) {
		fprintf(stderr, "FAILED!\n");
	} else {
		printf("SUCCESS.\n");
	}
	return ret;
954 955
}

956
void emergency_help_message(void)
957 958
{
	fprintf(stderr, "Your flash chip is in an unknown state.\n"
959 960 961
		"Get help on IRC at irc.freenode.net (channel #flashrom) or\n"
		"mail flashrom@flashrom.org!\n--------------------"
		"-----------------------------------------------------------\n"
962 963 964
		"DO NOT REBOOT OR POWEROFF!\n");
}

965 966 967 968 969 970 971 972 973 974 975 976
/* The way to go if you want a delimited list of programmers*/
void list_programmers(char *delim)
{
	enum programmer p;
	for (p = 0; p < PROGRAMMER_INVALID; p++) {
		printf("%s", programmer_table[p].name);
		if (p < PROGRAMMER_INVALID - 1)
			printf("%s", delim);
	}
	printf("\n");	
}

977 978
void print_version(void)
{
979
	printf("flashrom v%s\n", flashrom_version);
980 981
}

982 983
int selfcheck(void)
{
984 985 986 987 988 989
	int ret = 0;
	struct flashchip *flash;

	/* Safety check. Instead of aborting after the first error, check
	 * if more errors exist.
	 */
990 991
	if (ARRAY_SIZE(programmer_table) - 1 != PROGRAMMER_INVALID) {
		fprintf(stderr, "Programmer table miscompilation!\n");
992
		ret = 1;
993 994 995
	}
	if (spi_programmer_count - 1 != SPI_CONTROLLER_INVALID) {
		fprintf(stderr, "SPI programmer table miscompilation!\n");
996
		ret = 1;
997 998 999 1000
	}
#if BITBANG_SPI_SUPPORT == 1
	if (bitbang_spi_master_count - 1 != BITBANG_SPI_INVALID) {
		fprintf(stderr, "Bitbanging SPI master table miscompilation!\n");
1001
		ret = 1;
1002 1003
	}
#endif
1004 1005 1006 1007
	for (flash = flashchips; flash && flash->name; flash++)
		if (selfcheck_eraseblocks(flash))
			ret = 1;
	return ret;
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
}

void check_chip_supported(struct flashchip *flash)
{
	if (TEST_OK_MASK != (flash->tested & TEST_OK_MASK)) {
		printf("===\n");
		if (flash->tested & TEST_BAD_MASK) {
			printf("This flash part has status NOT WORKING for operations:");
			if (flash->tested & TEST_BAD_PROBE)
				printf(" PROBE");
			if (flash->tested & TEST_BAD_READ)
				printf(" READ");
			if (flash->tested & TEST_BAD_ERASE)
				printf(" ERASE");
			if (flash->tested & TEST_BAD_WRITE)
				printf(" WRITE");
			printf("\n");
		}
		if ((!(flash->tested & TEST_BAD_PROBE) && !(flash->tested & TEST_OK_PROBE)) ||
		    (!(flash->tested & TEST_BAD_READ) && !(flash->tested & TEST_OK_READ)) ||
		    (!(flash->tested & TEST_BAD_ERASE) && !(flash->tested & TEST_OK_ERASE)) ||
		    (!(flash->tested & TEST_BAD_WRITE) && !(flash->tested & TEST_OK_WRITE))) {
			printf("This flash part has status UNTESTED for operations:");
			if (!(flash->tested & TEST_BAD_PROBE) && !(flash->tested & TEST_OK_PROBE))
				printf(" PROBE");
			if (!(flash->tested & TEST_BAD_READ) && !(flash->tested & TEST_OK_READ))
				printf(" READ");
			if (!(flash->tested & TEST_BAD_ERASE) && !(flash->tested & TEST_OK_ERASE))
				printf(" ERASE");
			if (!(flash->tested & TEST_BAD_WRITE) && !(flash->tested & TEST_OK_WRITE))
				printf(" WRITE");
			printf("\n");
		}
1041
		/* FIXME: This message is designed towards CLI users. */
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
		printf("Please email a report to flashrom@flashrom.org if any "
		       "of the above operations\nwork correctly for you with "
		       "this flash part. Please include the flashrom\noutput "
		       "with the additional -V option for all operations you "
		       "tested (-V, -rV,\n-wV, -EV), and mention which "
		       "mainboard or programmer you tested. Thanks for your "
		       "help!\n===\n");
	}
}

1052
int main(int argc, char *argv[])
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1053
{
1054
	return cli_classic(argc, argv);
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
}

/* This function signature is horrible. We need to design a better interface,
 * but right now it allows us to split off the CLI code.
 */
int doit(struct flashchip *flash, int force, char *filename, int read_it, int write_it, int erase_it, int verify_it)
{
	uint8_t *buf;
	unsigned long numbytes;
	FILE *image;
	int ret = 0;
	unsigned long size;

	size = flash->total_size * 1024;
1069
	buf = (uint8_t *) calloc(size, sizeof(char));
1070

1071
	if (erase_it) {
1072 1073 1074 1075
		if (flash->tested & TEST_BAD_ERASE) {
			fprintf(stderr, "Erase is not working on this chip. ");
			if (!force) {
				fprintf(stderr, "Aborting.\n");
1076
				programmer_shutdown();
1077 1078 1079 1080 1081 1082 1083
				return 1;
			} else {
				fprintf(stderr, "Continuing anyway.\n");
			}
		}
		if (erase_flash(flash)) {
			emergency_help_message();
1084
			programmer_shutdown();
1085
			return 1;
1086
		}
1087
	} else if (read_it) {
1088 1089
		if (read_flash(flash, filename)) {
			programmer_shutdown();
1090
			return 1;
1091
		}
1092
	} else {
1093 1094
		struct stat image_stat;

1095 1096 1097 1098 1099
		if (flash->tested & TEST_BAD_ERASE) {
			fprintf(stderr, "Erase is not working on this chip "
				"and erase is needed for write. ");
			if (!force) {
				fprintf(stderr, "Aborting.\n");
1100
				programmer_shutdown();
1101 1102 1103 1104 1105 1106 1107 1108 1109
				return 1;
			} else {
				fprintf(stderr, "Continuing anyway.\n");
			}
		}
		if (flash->tested & TEST_BAD_WRITE) {
			fprintf(stderr, "Write is not working on this chip. ");
			if (!force) {
				fprintf(stderr, "Aborting.\n");
1110
				programmer_shutdown();
1111 1112 1113 1114 1115
				return 1;
			} else {
				fprintf(stderr, "Continuing anyway.\n");
			}
		}
1116
		if ((image = fopen(filename, "r")) == NULL) {
1117
			perror(filename);
1118
			programmer_shutdown();
1119 1120
			exit(1);
		}
1121 1122
		if (fstat(fileno(image), &image_stat) != 0) {
			perror(filename);
1123
			programmer_shutdown();
1124 1125
			exit(1);
		}
1126
		if (image_stat.st_size != flash->total_size * 1024) {
Uwe Hermann's avatar
Uwe Hermann committed
1127
			fprintf(stderr, "Error: Image size doesn't match\n");
1128
			programmer_shutdown();
1129 1130 1131
			exit(1);
		}

1132
		numbytes = fread(buf, 1, size, image);
1133
#if INTERNAL_SUPPORT == 1
Peter Stuge's avatar
Peter Stuge committed
1134
		show_id(buf, size, force);
1135
#endif
1136
		fclose(image);
1137 1138
		if (numbytes != size) {
			fprintf(stderr, "Error: Failed to read file. Got %ld bytes, wanted %ld!\n", numbytes, size);
1139
			programmer_shutdown();
1140 1141
			return 1;
		}
1142
	}
Ronald G. Minnich's avatar
Ronald G. Minnich committed
1143

1144 1145
	// This should be moved into each flash part's code to do it 
	// cleanly. This does the job.
1146
	handle_romentries(buf, flash);
1147

1148
	// ////////////////////////////////////////////////////////////
1149

1150
	if (write_it) {
1151
		printf("Writing flash chip... ");
1152 1153
		if (!flash->write) {
			fprintf(stderr, "Error: flashrom has no write function for this flash chip.\n");
1154
			programmer_shutdown();
1155 1156
			return 1;
		}
1157 1158 1159
		ret = flash->write(flash, buf);
		if (ret) {
			fprintf(stderr, "FAILED!\n");
1160
			emergency_help_message();
1161
			programmer_shutdown();
1162 1163 1164 1165
			return 1;
		} else {
			printf("COMPLETE.\n");
		}
1166
	}
1167

1168 1169 1170 1171
	if (verify_it) {
		/* Work around chips which need some time to calm down. */
		if (write_it)
			programmer_delay(1000*1000);
1172
		ret = verify_flash(flash, buf);
1173
		/* If we tried to write, and verification now fails, we
1174 1175 1176 1177 1178
		 * might have an emergency situation.
		 */
		if (ret && write_it)
			emergency_help_message();
	}
1179

1180 1181
	programmer_shutdown();

Stefan Reinauer's avatar
Stefan Reinauer committed
1182
	return ret;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1183
}