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

#include <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
enum programmer programmer = PROGRAMMER_INTERNAL;
37
char *programmer_param = NULL;
38 39 40

const struct programmer_entry programmer_table[] = {
	{
41
		.name			= "internal",
42 43
		.init			= internal_init,
		.shutdown		= internal_shutdown,
44 45
		.map_flash_region	= physmap,
		.unmap_flash_region	= physunmap,
46 47 48
		.chip_readb		= internal_chip_readb,
		.chip_readw		= internal_chip_readw,
		.chip_readl		= internal_chip_readl,
49
		.chip_readn		= internal_chip_readn,
50 51 52
		.chip_writeb		= internal_chip_writeb,
		.chip_writew		= internal_chip_writew,
		.chip_writel		= internal_chip_writel,
53
		.chip_writen		= fallback_chip_writen,
54
		.delay			= internal_delay,
55 56
	},

57
#if DUMMY_SUPPORT == 1
58
	{
59
		.name			= "dummy",
60 61
		.init			= dummy_init,
		.shutdown		= dummy_shutdown,
62 63
		.map_flash_region	= dummy_map,
		.unmap_flash_region	= dummy_unmap,
64 65 66
		.chip_readb		= dummy_chip_readb,
		.chip_readw		= dummy_chip_readw,
		.chip_readl		= dummy_chip_readl,
67
		.chip_readn		= dummy_chip_readn,
68 69 70
		.chip_writeb		= dummy_chip_writeb,
		.chip_writew		= dummy_chip_writew,
		.chip_writel		= dummy_chip_writel,
71
		.chip_writen		= dummy_chip_writen,
72
		.delay			= internal_delay,
73
	},
74
#endif
75

76
#if NIC3COM_SUPPORT == 1
77
	{
78
		.name			= "nic3com",
79 80
		.init			= nic3com_init,
		.shutdown		= nic3com_shutdown,
81 82
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
83
		.chip_readb		= nic3com_chip_readb,
84 85
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
86
		.chip_readn		= fallback_chip_readn,
87
		.chip_writeb		= nic3com_chip_writeb,
88 89
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
90
		.chip_writen		= fallback_chip_writen,
91
		.delay			= internal_delay,
92
	},
93
#endif
94

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
#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

114
#if DRKAISER_SUPPORT == 1
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
	{
		.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,
	},
131
#endif
132

133
#if SATASII_SUPPORT == 1
134
	{
135
		.name			= "satasii",
136 137
		.init			= satasii_init,
		.shutdown		= satasii_shutdown,
138 139
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
140 141 142
		.chip_readb		= satasii_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
143
		.chip_readn		= fallback_chip_readn,
144 145 146
		.chip_writeb		= satasii_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
147
		.chip_writen		= fallback_chip_writen,
148
		.delay			= internal_delay,
149
	},
150
#endif
151

152
	{
153
		.name			= "it87spi",
154
		.init			= it87spi_init,
155
		.shutdown		= noop_shutdown,
156 157
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
158
		.chip_readb		= noop_chip_readb,
159 160 161
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
162
		.chip_writeb		= noop_chip_writeb,
163 164 165
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
166
		.delay			= internal_delay,
167 168
	},

169
#if FT2232_SPI_SUPPORT == 1
170
	{
171
		.name			= "ft2232spi",
172
		.init			= ft2232_spi_init,
173
		.shutdown		= noop_shutdown, /* Missing shutdown */
174 175
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
176
		.chip_readb		= noop_chip_readb,
177 178 179
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
180
		.chip_writeb		= noop_chip_writeb,
181 182 183 184 185
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
186
#endif
187

188
#if SERPROG_SUPPORT == 1
189
	{
190
		.name			= "serprog",
191 192 193 194 195 196 197 198 199 200 201 202 203 204
		.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,
	},
205
#endif
206

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
#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

226
	{}, /* This entry corresponds to PROGRAMMER_INVALID. */
227
};
228

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
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);
}

266 267 268 269 270
void chip_writen(uint8_t *buf, chipaddr addr, size_t len)
{
	programmer_table[programmer].chip_writen(buf, addr, len);
}

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
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);
}

286 287 288 289 290
void chip_readn(uint8_t *buf, chipaddr addr, size_t len)
{
	programmer_table[programmer].chip_readn(buf, addr, len);
}

291 292 293 294 295
void programmer_delay(int usecs)
{
	programmer_table[programmer].delay(usecs);
}

296
void map_flash_registers(struct flashchip *flash)
297 298
{
	size_t size = flash->total_size * 1024;
299
	/* Flash registers live 4 MByte below the flash. */
300
	/* FIXME: This is incorrect for nonstandard flashbase. */
301
	flash->virtual_registers = (chipaddr)programmer_map_flash_region("flash chip registers", (0xFFFFFFFF - 0x400000 - size + 1), size);
302 303
}

304
int read_memmapped(struct flashchip *flash, uint8_t *buf, int start, int len)
305
{
306
	chip_readn(buf, flash->virtual_memory + start, len);
307 308 309 310
		
	return 0;
}

311 312 313 314 315
int min(int a, int b)
{
	return (a < b) ? a : b;
}

316 317 318 319 320
int max(int a, int b)
{
	return (a > b) ? a : b;
}

321 322 323 324 325 326 327 328 329
int bitcount(unsigned long a)
{
	int i = 0;
	for (; a != 0; a >>= 1)
		if (a & 1)
			i++;
	return i;
}

330 331 332 333 334 335 336 337 338
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;
}

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
/* 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;
}

/**
 * @cmpbuf	buffer to compare against
 * @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);
367
	int failcount = 0;
368 369 370 371

	if (!len)
		goto out_free;

372 373 374 375
	if (!flash->read) {
		fprintf(stderr, "ERROR: flashrom has no read function for this flash chip.\n");
		return 1;
	}
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
	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;
405
		flash->read(flash, readbuf, starthere, lenhere);
406 407
		for (j = 0; j < lenhere; j++) {
			if (cmpbuf[starthere - start + j] != readbuf[j]) {
408 409 410 411 412 413 414
				/* 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]);
415 416 417
			}
		}
	}
418 419 420 421 422
	if (failcount) {
		fprintf(stderr, " failed byte count from 0x%08x-0x%08x: 0x%x\n",
			start, start + len - 1, failcount);
		ret = -1;
	}
423 424 425 426 427 428

out_free:
	free(readbuf);
	return ret;
}

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 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 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 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
/* 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;
}

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

613
struct flashchip *probe_flash(struct flashchip *first_flash, int force)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
614
{
615
	struct flashchip *flash;
616 617 618
	unsigned long base = 0;
	uint32_t size;
	enum chipbustype buses_common;
619
	char *tmp;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
620

621
	for (flash = first_flash; flash && flash->name; flash++) {
622
		if (chip_to_probe && strcmp(flash->name, chip_to_probe) != 0)
623
			continue;
624 625
		printf_debug("Probing for %s %s, %d KB: ",
			     flash->vendor, flash->name, flash->total_size);
Peter Stuge's avatar
Peter Stuge committed
626
		if (!flash->probe && !force) {
627 628 629
			printf_debug("failed! flashrom has no probe function for this flash chip.\n");
			continue;
		}
630 631
		buses_common = buses_supported & flash->bustype;
		if (!buses_common) {
632 633 634 635 636 637 638 639
			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
640

641
		size = flash->total_size * 1024;
642
		check_max_decode(buses_common, size);
Stefan Reinauer's avatar
Stefan Reinauer committed
643

644
		base = flashbase ? flashbase : (0xffffffff - size + 1);
645
		flash->virtual_memory = (chipaddr)programmer_map_flash_region("flash chip", base, size);
646

647 648 649
		if (force)
			break;

650 651 652
		if (flash->probe(flash) != 1)
			goto notfound;

653 654
		if (first_flash == flashchips
		    || flash->model_id != GENERIC_DEVICE_ID)
655
			break;
Stefan Reinauer's avatar
Stefan Reinauer committed
656

657
notfound:
658
		programmer_unmap_flash_region((void *)flash->virtual_memory, size);
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
659
	}
Uwe Hermann's avatar
Uwe Hermann committed
660

661 662 663
	if (!flash || !flash->name)
		return NULL;

664 665 666 667
	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);

668
	return flash;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
669 670
}

Stefan Reinauer's avatar
Stefan Reinauer committed
671
int verify_flash(struct flashchip *flash, uint8_t *buf)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
672
{
673
	int ret;
674
	int total_size = flash->total_size * 1024;
675

676
	printf("Verifying flash... ");
677

678
	ret = verify_range(flash, buf, 0, total_size, NULL);
679

680 681
	if (!ret)
		printf("VERIFIED.          \n");
682

683
	return ret;
Ronald G. Minnich's avatar
Fixes  
Ronald G. Minnich committed
684 685
}

686
int read_flash(struct flashchip *flash, char *filename)
687 688 689 690 691
{
	unsigned long numbytes;
	FILE *image;
	unsigned long size = flash->total_size * 1024;
	unsigned char *buf = calloc(size, sizeof(char));
692 693 694 695 696

	if (!filename) {
		printf("Error: No filename specified.\n");
		return 1;
	}
697 698 699 700 701
	if ((image = fopen(filename, "w")) == NULL) {
		perror(filename);
		exit(1);
	}
	printf("Reading flash... ");
702 703 704 705 706
	if (!flash->read) {
		printf("FAILED!\n");
		fprintf(stderr, "ERROR: flashrom has no read function for this flash chip.\n");
		return 1;
	} else
707
		flash->read(flash, buf, 0, size);
708 709 710

	numbytes = fwrite(buf, 1, size, image);
	fclose(image);
711
	free(buf);
712 713 714 715 716 717 718 719
	printf("%s.\n", numbytes == size ? "done" : "FAILED");
	if (numbytes != size)
		return 1;
	return 0;
}

int erase_flash(struct flashchip *flash)
{
720 721
	int i, j, k, ret = 0, found = 0;

722
	printf("Erasing flash chip... ");
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
		unsigned long done = 0;
		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++) {
				ret = eraser.block_erase(flash, done + eraser.eraseblocks[i].size * j, eraser.eraseblocks[i].size);
				if (ret)
					break;
			}
			if (ret)
				break;
		}
		/* 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) {
770 771 772
		fprintf(stderr, "ERROR: flashrom has no erase function for this flash chip.\n");
		return 1;
	}
773

774 775 776 777 778 779
	if (ret) {
		fprintf(stderr, "FAILED!\n");
	} else {
		printf("SUCCESS.\n");
	}
	return ret;
780 781
}

782
void emergency_help_message(void)
783 784
{
	fprintf(stderr, "Your flash chip is in an unknown state.\n"
785 786 787
		"Get help on IRC at irc.freenode.net (channel #flashrom) or\n"
		"mail flashrom@flashrom.org!\n--------------------"
		"-----------------------------------------------------------\n"
788 789 790
		"DO NOT REBOOT OR POWEROFF!\n");
}

Ronald G. Minnich's avatar
Ronald G. Minnich committed
791 792
void usage(const char *name)
{
793 794 795 796 797
	const char *pname;
	int pnamelen;
	int remaining = 0;
	enum programmer p;

798
	printf("usage: %s [-VfLzhR] [-E|-r file|-w file|-v file] [-c chipname]\n"
799
              "       [-m [vendor:]part] [-l file] [-i image] [-p programmer]\n\n", name);
800

801 802 803 804
	printf("Please note that the command line interface for flashrom will "
		"change before\nflashrom 1.0. Do not use flashrom in scripts "
		"or other automated tools without\nchecking that your flashrom"
		" version won't interpret options in a different way.\n\n");
805

806
	printf
807 808 809
	    ("   -r | --read:                      read flash and save into file\n"
	     "   -w | --write:                     write file into flash\n"
	     "   -v | --verify:                    verify flash against file\n"
810
	     "   -n | --noverify:                  don't verify flash against file\n"
811 812 813 814 815
	     "   -E | --erase:                     erase flash device\n"
	     "   -V | --verbose:                   more verbose output\n"
	     "   -c | --chip <chipname>:           probe only for specified flash chip\n"
	     "   -m | --mainboard <[vendor:]part>: override mainboard settings\n"
	     "   -f | --force:                     force write without checking image\n"
816
	     "   -l | --layout <file.layout>:      read ROM layout from file\n"
817
	     "   -i | --image <name>:              only flash image name from flash layout\n"
818
	     "   -L | --list-supported:            print supported devices\n"
819
#if PRINT_WIKI_SUPPORT == 1
820
	     "   -z | --list-supported-wiki:       print supported devices in wiki syntax\n"
821
#endif
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
	     "   -p | --programmer <name>:         specify the programmer device");

	for (p = 0; p < PROGRAMMER_INVALID; p++) {
		pname = programmer_table[p].name;
		pnamelen = strlen(pname);
		if (remaining - pnamelen - 2 < 0) {
			printf("\n                                     ");
			remaining = 43;
		} else {
			printf(" ");
			remaining--;
		}
		if (p == 0) {
			printf("(");
			remaining--;
		}
		printf("%s", pname);
		remaining -= pnamelen;
		if (p < PROGRAMMER_INVALID - 1) {
			printf(",");
			remaining--;
		} else {
			printf(")\n");
		}
	}
		
	printf(
849
	     "   -h | --help:                      print this help text\n"
850
	     "   -R | --version:                   print the version (release)\n"
851 852
	     "\nYou can specify one of -E, -r, -w, -v or no operation. If no operation is\n"
	     "specified, then all that happens is that flash info is dumped.\n\n");
853
	exit(1);
Ronald G. Minnich's avatar
Ronald G. Minnich committed
854 855
}

856 857
void print_version(void)
{
858
	printf("flashrom v%s\n", flashrom_version);
859 860
}

861
int main(int argc, char *argv[])
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
862
{
863
	uint8_t *buf;
864
	unsigned long size, numbytes;
865
	FILE *image;
Claus Gindhart's avatar
Claus Gindhart committed
866 867
	/* Probe for up to three flash chips. */
	struct flashchip *flash, *flashes[3];
868 869
	const char *name;
	int namelen;
870
	int opt;
871
	int option_index = 0;
Peter Stuge's avatar
Peter Stuge committed
872
	int force = 0;
873
	int read_it = 0, write_it = 0, erase_it = 0, verify_it = 0;
874
	int dont_verify_it = 0, list_supported = 0;
875
#if PRINT_WIKI_SUPPORT == 1
876 877
	int list_supported_wiki = 0;
#endif
878
	int operation_specified = 0;
Claus Gindhart's avatar
Claus Gindhart committed
879
	int ret = 0, i;
880

881
#if PRINT_WIKI_SUPPORT == 1
882 883 884 885
	const char *optstring = "rRwvnVEfc:m:l:i:p:Lzh";
#else
	const char *optstring = "rRwvnVEfc:m:l:i:p:Lh";
#endif
886 887 888 889 890
	static struct option long_options[] = {
		{"read", 0, 0, 'r'},
		{"write", 0, 0, 'w'},
		{"erase", 0, 0, 'E'},
		{"verify", 0, 0, 'v'},
891
		{"noverify", 0, 0, 'n'},
892 893 894 895 896 897
		{"chip", 1, 0, 'c'},
		{"mainboard", 1, 0, 'm'},
		{"verbose", 0, 0, 'V'},
		{"force", 0, 0, 'f'},
		{"layout", 1, 0, 'l'},
		{"image", 1, 0, 'i'},
898
		{"list-supported", 0, 0, 'L'},
899
#if PRINT_WIKI_SUPPORT == 1
900
		{"list-supported-wiki", 0, 0, 'z'},
901
#endif
902
		{"programmer", 1, 0, 'p'},
903
		{"help", 0, 0, 'h'},
904
		{"version", 0, 0, 'R'},
905
		{0, 0, 0, 0}
906
	};
907

908
	char *filename = NULL;
909

910
	char *tempstr = NULL, *tempstr2 = NULL;
911

912 913
	print_version();

914 915 916
	if (argc > 1) {
		/* Yes, print them. */
		int i;
917
		printf_debug("The arguments are:\n");
918
		for (i = 1; i < argc; ++i)
919
			printf_debug("%s\n", argv[i]);
920 921
	}

922 923 924 925 926
	/* Safety check. */
	if (ARRAY_SIZE(programmer_table) - 1 != PROGRAMMER_INVALID) {
		fprintf(stderr, "Programmer table miscompilation!\n");
		exit(1);
	}
927 928 929 930
	if (spi_programmer_count - 1 != SPI_CONTROLLER_INVALID) {
		fprintf(stderr, "SPI programmer table miscompilation!\n");
		exit(1);
	}
931
#if BITBANG_SPI_SUPPORT == 1
932
	if (bitbang_spi_master_count - 1 != BITBANG_SPI_INVALID) {
933 934 935 936
		fprintf(stderr, "Bitbanging SPI master table miscompilation!\n");
		exit(1);
	}
#endif
937

938
	setbuf(stdout, NULL);
939
	while ((opt = getopt_long(argc, argv, optstring,
940
				  long_options, &option_index)) != EOF) {
941 942
		switch (opt) {
		case 'r':
943 944 945 946 947
			if (++operation_specified > 1) {
				fprintf(stderr, "More than one operation "
					"specified. Aborting.\n");
				exit(1);
			}
948 949 950
			read_it = 1;
			break;
		case 'w':
951 952 953 954 955
			if (++operation_specified > 1) {
				fprintf(stderr, "More than one operation "
					"specified. Aborting.\n");
				exit(1);
			}
956 957 958
			write_it = 1;
			break;
		case 'v':
959
			//FIXME: gracefully handle superfluous -v
960 961 962 963 964
			if (++operation_specified > 1) {
				fprintf(stderr, "More than one operation "
					"specified. Aborting.\n");
				exit(1);
			}
965 966 967 968 969
			if (dont_verify_it) {
				fprintf(stderr, "--verify and --noverify are"
					"mutually exclusive. Aborting.\n");
				exit(1);
			}
970 971
			verify_it = 1;
			break;
972
		case 'n':
973 974 975 976 977
			if (verify_it) {
				fprintf(stderr, "--verify and --noverify are"
					"mutually exclusive. Aborting.\n");
				exit(1);
			}
978 979
			dont_verify_it = 1;
			break;
980 981 982
		case 'c':
			chip_to_probe = strdup(optarg);
			break;
Ollie Lho's avatar
Ollie Lho committed
983 984 985
		case 'V':
			verbose = 1;
			break;
986
		case 'E':
987 988 989 990 991
			if (++operation_specified > 1) {
				fprintf(stderr, "More than one operation "
					"specified. Aborting.\n");
				exit(1);
			}
992 993
			erase_it = 1;
			break;
994 995 996
		case 'm':
			tempstr = strdup(optarg);
			strtok(tempstr, ":");
997
			tempstr2 = strtok(NULL, ":");
998
			if (tempstr2) {
999 1000
				lb_vendor = tempstr;
				lb_part = tempstr2;
1001
			} else {
1002 1003
				lb_vendor = NULL;
				lb_part = tempstr;
1004 1005 1006
			}
			break;
		case 'f':
1007
			force = 1;
1008 1009
			break;
		case 'l':
1010
			tempstr = strdup(optarg);
1011 1012
			if (read_romlayout(tempstr))
				exit(1);
1013 1014
			break;
		case 'i':
1015
			tempstr = strdup(optarg);
1016 1017
			find_romentry(tempstr);
			break;
1018
		case 'L':
Uwe Hermann's avatar
Uwe Hermann committed
1019
			list_supported = 1;
1020
			break;
1021
#if PRINT_WIKI_SUPPORT == 1
1022 1023 1024
		case 'z':
			list_supported_wiki = 1;
			break;
1025
#endif
1026
		case 'p':
1027 1028 1029 1030 1031
			for (programmer = 0; programmer < PROGRAMMER_INVALID; programmer++) {
				name = programmer_table[programmer].name;
				namelen = strlen(name);
				if (strncmp(optarg, name, namelen) == 0) {
					switch (optarg[namelen]) {
1032
					case ':':
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
						programmer_param = strdup(optarg + namelen + 1);
						break;
					case '\0':
						break;
					default:
						/* The continue refers to the
						 * for loop. It is here to be
						 * able to differentiate between
						 * foo and foobar.
						 */
						continue;
					}
					break;
				}
			}
			if (programmer == PROGRAMMER_INVALID) {
1049
				printf("Error: Unknown programmer %s.\n", optarg);
1050 1051 1052
				exit(1);
			}
			break;
1053
		case 'R':
1054
			/* print_version() is always called during startup. */
1055 1056
			exit(0);
			break;
1057
		case 'h':
1058 1059 1060 1061 1062
		default:
			usage(argv[0]);
			break;
		}
	}
1063

Uwe Hermann's avatar
Uwe Hermann committed
1064
	if (list_supported) {
1065
		print_supported();
Uwe Hermann's avatar
Uwe Hermann committed
1066 1067 1068
		exit(0);
	}

1069
#if PRINT_WIKI_SUPPORT == 1
1070
	if (list_supported_wiki) {
1071
		print_supported_wiki();
1072 1073
		exit(0);
	}
1074
#endif
1075

1076
	if (read_it && write_it) {
Uwe Hermann's avatar
Uwe Hermann committed
1077
		printf("Error: -r and -w are mutually exclusive.\n");
1078 1079
		usage(argv[0]);
	}
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1080

1081 1082
	if (optind < argc)
		filename = argv[optind++];
1083 1084 1085 1086 1087
	
	if (optind < argc) {
		printf("Error: Extra parameter found.\n");
		usage(argv[0]);
	}
Ronald G. Minnich's avatar
Ronald G. Minnich committed
1088

1089 1090 1091 1092
	if (programmer_init()) {
		fprintf(stderr, "Error: Programmer initialization failed.\n");
		exit(1);
	}
1093

1094
	myusec_calibrate_delay();
1095

Claus Gindhart's avatar
Claus Gindhart committed
1096
	for (i = 0; i < ARRAY_SIZE(flashes); i++) {
1097 1098
		flashes[i] =
		    probe_flash(i ? flashes[i - 1] + 1 : flashchips, 0);
Claus Gindhart's avatar
Claus Gindhart committed
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
		if (!flashes[i])
			for (i++; i < ARRAY_SIZE(flashes); i++)
				flashes[i] = NULL;
	}

	if (flashes[1]) {
		printf("Multiple flash chips were detected:");
		for (i = 0; i < ARRAY_SIZE(flashes) && flashes[i]; i++)
			printf(" %s", flashes[i]->name);
		printf("\nPlease specify which chip to use with the -c <chipname> option.\n");
1109
		programmer_shutdown();
Claus Gindhart's avatar
Claus Gindhart committed
1110 1111
		exit(1);
	} else if (!flashes[0]) {
1112
		printf("No EEPROM/flash device found.\n");
Peter Stuge's avatar
Peter Stuge committed
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
		if (!force || !chip_to_probe) {
			printf("If you know which flash chip you have, and if this version of flashrom\n");
			printf("supports a similar flash chip, you can try to force read your chip. Run:\n");
			printf("flashrom -f -r -c similar_supported_flash_chip filename\n");
			printf("\n");
			printf("Note: flashrom can never write when the flash chip isn't found automatically.\n");
		}
		if (force && read_it && chip_to_probe) {
			printf("Force read (-f -r -c) requested, forcing chip probe success:\n");
			flashes[0] = probe_flash(flashchips, 1);
			if (!flashes[0]) {
				printf("flashrom does not support a flash chip named '%s'.\n", chip_to_probe);
				printf("Run flashrom -L to view the hardware supported in this flashrom version.\n");
				exit(1);
			}
1128
			printf("Please note that forced reads most likely contain garbage.\n");
1129
			return read_flash(flashes[0], filename);
Peter Stuge's avatar
Peter Stuge committed
1130
		}
1131
		// FIXME: flash writes stay enabled!
1132
		programmer_shutdown();
1133 1134
		exit(1);
	}
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1135

Claus Gindhart's avatar
Claus Gindhart committed
1136 1137
	flash = flashes[0];

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
	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");
1151 1152 1153 1154 1155
		}
		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))) {
1156
			printf("This flash part has status UNTESTED for operations:");
1157
			if (!(flash->tested & TEST_BAD_PROBE) && !(flash->tested & TEST_OK_PROBE))
1158
				printf(" PROBE");
1159
			if (!(flash->tested & TEST_BAD_READ) && !(flash->tested & TEST_OK_READ))
1160
				printf(" READ");
1161
			if (!(flash->tested & TEST_BAD_ERASE) && !(flash->tested & TEST_OK_ERASE))
1162
				printf(" ERASE");
1163
			if (!(flash->tested & TEST_BAD_WRITE) && !(flash->tested & TEST_OK_WRITE))
1164 1165 1166
				printf(" WRITE");
			printf("\n");
		}
1167
		printf("Please email a report to flashrom@flashrom.org if any "
1168 1169 1170 1171 1172
		       "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 you tested. Thanks for your help!\n===\n");
1173
	}
1174

1175 1176 1177 1178 1179 1180 1181 1182 1183
	size = flash->total_size * 1024;
	if (check_max_decode((buses_supported & flash->bustype), size) &&
	    (!force)) {
		fprintf(stderr, "Chip is too big for this programmer "
			"(-V gives details). Use --force to override.\n");
		programmer_shutdown();
		return 1;
	}

1184 1185 1186
	if (!(read_it | write_it | verify_it | erase_it)) {
		printf("No operations were specified.\n");
		// FIXME: flash writes stay enabled!
1187
		programmer_shutdown();
1188 1189 1190
		exit(1);
	}

1191
	if (!filename && !erase_it) {
1192 1193
		printf("Error: No filename specified.\n");
		// FIXME: flash writes stay enabled!
1194
		programmer_shutdown();
1195
		exit(1);
1196 1197
	}

1198 1199 1200 1201
	/* Always verify write operations unless -n is used. */
	if (write_it && !dont_verify_it)
		verify_it = 1;

1202
	buf = (uint8_t *) calloc(size, sizeof(char));
1203

1204
	if (erase_it) {
1205 1206 1207 1208
		if (flash->tested & TEST_BAD_ERASE) {
			fprintf(stderr, "Erase is not working on this chip. ");
			if (!force) {
				fprintf(stderr, "Aborting.\n");
1209
				programmer_shutdown();
1210 1211 1212 1213 1214 1215 1216
				return 1;
			} else {
				fprintf(stderr, "Continuing anyway.\n");
			}
		}
		if (erase_flash(flash)) {
			emergency_help_message();
1217
			programmer_shutdown();
1218
			return 1;
1219
		}
1220
	} else if (read_it) {
1221 1222
		if (read_flash(flash, filename)) {
			programmer_shutdown();
1223
			return 1;
1224
		}
1225
	} else {
1226 1227
		struct stat image_stat;

1228 1229 1230 1231 1232
		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");
1233
				programmer_shutdown();
1234 1235 1236 1237 1238 1239 1240 1241 1242
				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");
1243
				programmer_shutdown();
1244 1245 1246 1247 1248
				return 1;
			} else {
				fprintf(stderr, "Continuing anyway.\n");
			}
		}
1249
		if ((image = fopen(filename, "r")) == NULL) {
1250
			perror(filename);
1251
			programmer_shutdown();
1252 1253
			exit(1);
		}
1254 1255
		if (fstat(fileno(image), &image_stat) != 0) {
			perror(filename);
1256
			programmer_shutdown();
1257 1258
			exit(1);
		}
1259
		if (image_stat.st_size != flash->total_size * 1024) {
Uwe Hermann's avatar
Uwe Hermann committed
1260
			fprintf(stderr, "Error: Image size doesn't match\n");
1261
			programmer_shutdown();
1262 1263 1264
			exit(1);
		}

1265
		numbytes = fread(buf, 1, size, image);
Peter Stuge's avatar
Peter Stuge committed
1266
		show_id(buf, size, force);
1267
		fclose(image);
1268 1269
		if (numbytes != size) {
			fprintf(stderr, "Error: Failed to read file. Got %ld bytes, wanted %ld!\n", numbytes, size);
1270
			programmer_shutdown();
1271 1272
			return 1;
		}
1273
	}
Ronald G. Minnich's avatar
Ronald G. Minnich committed
1274

1275 1276
	// This should be moved into each flash part's code to do it 
	// cleanly. This does the job.
1277
	handle_romentries(buf, flash);
1278

1279
	// ////////////////////////////////////////////////////////////
1280

1281
	if (write_it) {
1282
		printf("Writing flash chip... ");
1283 1284
		if (!flash->write) {
			fprintf(stderr, "Error: flashrom has no write function for this flash chip.\n");
1285
			programmer_shutdown();
1286 1287
			return 1;
		}
1288 1289 1290
		ret = flash->write(flash, buf);
		if (ret) {
			fprintf(stderr, "FAILED!\n");
1291
			emergency_help_message();
1292
			programmer_shutdown();
1293 1294 1295 1296
			return 1;
		} else {
			printf("COMPLETE.\n");
		}
1297
	}
1298

1299 1300 1301 1302
	if (verify_it) {
		/* Work around chips which need some time to calm down. */
		if (write_it)
			programmer_delay(1000*1000);
1303
		ret = verify_flash(flash, buf);
1304
		/* If we tried to write, and verification now fails, we
1305 1306 1307 1308 1309
		 * might have an emergency situation.
		 */
		if (ret && write_it)
			emergency_help_message();
	}
1310

1311 1312
	programmer_shutdown();

Stefan Reinauer's avatar
Stefan Reinauer committed
1313
	return ret;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1314
}