flashrom.c 43.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>
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
25
#include <fcntl.h>
26 27
#include <sys/types.h>
#include <sys/stat.h>
Ronald G. Minnich's avatar
Ronald G. Minnich committed
28
#include <string.h>
Ronald G. Minnich's avatar
Ronald G. Minnich committed
29
#include <stdlib.h>
30
#include <getopt.h>
31 32 33
#if HAVE_UTSNAME == 1
#include <sys/utsname.h>
#endif
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
34
#include "flash.h"
35
#include "flashchips.h"
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
36

37
const char * const flashrom_version = FLASHROM_VERSION;
Ronald G. Minnich's avatar
Ronald G. Minnich committed
38
char *chip_to_probe = NULL;
Peter Stuge's avatar
Peter Stuge committed
39
int verbose = 0;
40

41
#if CONFIG_INTERNAL == 1
42
enum programmer programmer = PROGRAMMER_INTERNAL;
43
#elif CONFIG_DUMMY == 1
44 45
enum programmer programmer = PROGRAMMER_DUMMY;
#else
46 47 48 49 50
/* 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.
 */
51
#if CONFIG_NIC3COM+CONFIG_NICREALTEK+CONFIG_NICNATSEMI+CONFIG_GFXNVIDIA+CONFIG_DRKAISER+CONFIG_SATASII+CONFIG_ATAHPT+CONFIG_FT2232_SPI+CONFIG_SERPROG+CONFIG_BUSPIRATE_SPI+CONFIG_DEDIPROG > 1
52
#error Please enable either CONFIG_DUMMY or CONFIG_INTERNAL or disable support for all programmers except one.
53 54
#endif
enum programmer programmer =
55
#if CONFIG_NIC3COM == 1
56 57
	PROGRAMMER_NIC3COM
#endif
58
#if CONFIG_NICREALTEK == 1
59 60 61
	PROGRAMMER_NICREALTEK
	PROGRAMMER_NICREALTEK2
#endif
62 63 64
#if CONFIG_NICNATSEMI == 1
	PROGRAMMER_NICNATSEMI
#endif
65
#if CONFIG_GFXNVIDIA == 1
66 67
	PROGRAMMER_GFXNVIDIA
#endif
68
#if CONFIG_DRKAISER == 1
69 70
	PROGRAMMER_DRKAISER
#endif
71
#if CONFIG_SATASII == 1
72 73
	PROGRAMMER_SATASII
#endif
74
#if CONFIG_ATAHPT == 1
75 76
	PROGRAMMER_ATAHPT
#endif
77 78
#if CONFIG_FT2232_SPI == 1
	PROGRAMMER_FT2232_SPI
79
#endif
80
#if CONFIG_SERPROG == 1
81 82
	PROGRAMMER_SERPROG
#endif
83 84
#if CONFIG_BUSPIRATE_SPI == 1
	PROGRAMMER_BUSPIRATE_SPI
85
#endif
86
#if CONFIG_DEDIPROG == 1
87 88
	PROGRAMMER_DEDIPROG
#endif
89
;
90 91
#endif

92
static char *programmer_param = NULL;
93

94 95
/* Supported buses for the current programmer. */
enum chipbustype buses_supported;
96 97 98 99 100

/**
 * Programmers supporting multiple buses can have differing size limits on
 * each bus. Store the limits for each bus in a common struct.
 */
101 102 103 104
struct decode_sizes max_rom_decode;

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

106 107 108
/* Is writing allowed with this programmer? */
int programmer_may_write;

109
const struct programmer_entry programmer_table[] = {
110
#if CONFIG_INTERNAL == 1
111
	{
112
		.name			= "internal",
113 114
		.init			= internal_init,
		.shutdown		= internal_shutdown,
115 116
		.map_flash_region	= physmap,
		.unmap_flash_region	= physunmap,
117 118 119
		.chip_readb		= internal_chip_readb,
		.chip_readw		= internal_chip_readw,
		.chip_readl		= internal_chip_readl,
120
		.chip_readn		= internal_chip_readn,
121 122 123
		.chip_writeb		= internal_chip_writeb,
		.chip_writew		= internal_chip_writew,
		.chip_writel		= internal_chip_writel,
124
		.chip_writen		= fallback_chip_writen,
125
		.delay			= internal_delay,
126
	},
127
#endif
128

129
#if CONFIG_DUMMY == 1
130
	{
131
		.name			= "dummy",
132 133
		.init			= dummy_init,
		.shutdown		= dummy_shutdown,
134 135
		.map_flash_region	= dummy_map,
		.unmap_flash_region	= dummy_unmap,
136 137 138
		.chip_readb		= dummy_chip_readb,
		.chip_readw		= dummy_chip_readw,
		.chip_readl		= dummy_chip_readl,
139
		.chip_readn		= dummy_chip_readn,
140 141 142
		.chip_writeb		= dummy_chip_writeb,
		.chip_writew		= dummy_chip_writew,
		.chip_writel		= dummy_chip_writel,
143
		.chip_writen		= dummy_chip_writen,
144
		.delay			= internal_delay,
145
	},
146
#endif
147

148
#if CONFIG_NIC3COM == 1
149
	{
150
		.name			= "nic3com",
151 152
		.init			= nic3com_init,
		.shutdown		= nic3com_shutdown,
153 154
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
155
		.chip_readb		= nic3com_chip_readb,
156 157
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
158
		.chip_readn		= fallback_chip_readn,
159
		.chip_writeb		= nic3com_chip_writeb,
160 161
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
162
		.chip_writen		= fallback_chip_writen,
163
		.delay			= internal_delay,
164
	},
165
#endif
166

167
#if CONFIG_NICREALTEK == 1
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
	{
		.name                   = "nicrealtek",
		.init                   = nicrealtek_init,
		.shutdown               = nicrealtek_shutdown,
		.map_flash_region       = fallback_map,
		.unmap_flash_region     = fallback_unmap,
		.chip_readb             = nicrealtek_chip_readb,
		.chip_readw             = fallback_chip_readw,
		.chip_readl             = fallback_chip_readl,
		.chip_readn             = fallback_chip_readn,
		.chip_writeb            = nicrealtek_chip_writeb,
		.chip_writew            = fallback_chip_writew,
		.chip_writel            = fallback_chip_writel,
		.chip_writen            = fallback_chip_writen,
		.delay                  = internal_delay,
	},
	{
		.name                   = "nicsmc1211",
		.init                   = nicsmc1211_init,
		.shutdown               = nicrealtek_shutdown,
		.map_flash_region       = fallback_map,
		.unmap_flash_region     = fallback_unmap,
		.chip_readb             = nicrealtek_chip_readb,
		.chip_readw             = fallback_chip_readw,
		.chip_readl             = fallback_chip_readl,
		.chip_readn             = fallback_chip_readn,
		.chip_writeb            = nicrealtek_chip_writeb,
		.chip_writew            = fallback_chip_writew,
		.chip_writel            = fallback_chip_writel,
		.chip_writen            = fallback_chip_writen,
		.delay                  = internal_delay,
	},
#endif

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
#if CONFIG_NICNATSEMI == 1
	{
		.name                   = "nicnatsemi",
		.init                   = nicnatsemi_init,
		.shutdown               = nicnatsemi_shutdown,
		.map_flash_region       = fallback_map,
		.unmap_flash_region     = fallback_unmap,
		.chip_readb             = nicnatsemi_chip_readb,
		.chip_readw             = fallback_chip_readw,
		.chip_readl             = fallback_chip_readl,
		.chip_readn             = fallback_chip_readn,
		.chip_writeb            = nicnatsemi_chip_writeb,
		.chip_writew            = fallback_chip_writew,
		.chip_writel            = fallback_chip_writel,
		.chip_writen            = fallback_chip_writen,
		.delay                  = internal_delay,
	},
#endif
220

221
#if CONFIG_GFXNVIDIA == 1
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
	{
		.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

240
#if CONFIG_DRKAISER == 1
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
	{
		.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,
	},
257
#endif
258

259
#if CONFIG_SATASII == 1
260
	{
261
		.name			= "satasii",
262 263
		.init			= satasii_init,
		.shutdown		= satasii_shutdown,
264 265
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
266 267 268
		.chip_readb		= satasii_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
269
		.chip_readn		= fallback_chip_readn,
270 271 272
		.chip_writeb		= satasii_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
273
		.chip_writen		= fallback_chip_writen,
274
		.delay			= internal_delay,
275
	},
276
#endif
277

278
#if CONFIG_ATAHPT == 1
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
	{
		.name			= "atahpt",
		.init			= atahpt_init,
		.shutdown		= atahpt_shutdown,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.chip_readb		= atahpt_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
		.chip_writeb		= atahpt_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
#endif

297
#if CONFIG_INTERNAL == 1
298
#if defined(__i386__) || defined(__x86_64__)
299
	{
300
		.name			= "it87spi",
301
		.init			= it87spi_init,
302
		.shutdown		= noop_shutdown,
303 304
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
305
		.chip_readb		= noop_chip_readb,
306 307 308
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
309
		.chip_writeb		= noop_chip_writeb,
310 311 312
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
313
		.delay			= internal_delay,
314
	},
315
#endif
316
#endif
317

318
#if CONFIG_FT2232_SPI == 1
319
	{
320
		.name			= "ft2232_spi",
321
		.init			= ft2232_spi_init,
322
		.shutdown		= noop_shutdown, /* Missing shutdown */
323 324
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
325
		.chip_readb		= noop_chip_readb,
326 327 328
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
329
		.chip_writeb		= noop_chip_writeb,
330 331 332 333 334
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
335
#endif
336

337
#if CONFIG_SERPROG == 1
338
	{
339
		.name			= "serprog",
340 341 342 343 344 345 346 347 348 349 350 351 352 353
		.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,
	},
354
#endif
355

356
#if CONFIG_BUSPIRATE_SPI == 1
357
	{
358
		.name			= "buspirate_spi",
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
		.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

375
#if CONFIG_DEDIPROG == 1
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
	{
		.name			= "dediprog",
		.init			= dediprog_init,
		.shutdown		= dediprog_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

394
	{}, /* This entry corresponds to PROGRAMMER_INVALID. */
395
};
396

397 398 399 400 401
#define SHUTDOWN_MAXFN 4
static int shutdown_fn_count = 0;
struct shutdown_func_data {
	void (*func) (void *data);
	void *data;
402 403 404 405 406
} 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;
407 408 409 410 411 412 413 414 415 416 417 418

/* 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.
 */
int register_shutdown(void (*function) (void *data), void *data)
{
	if (shutdown_fn_count >= SHUTDOWN_MAXFN) {
419
		msg_perr("Tried to register more than %i shutdown functions.\n",
420 421 422
			 SHUTDOWN_MAXFN);
		return 1;
	}
423 424 425 426 427
	if (!may_register_shutdown) {
		msg_perr("Tried to register a shutdown function before "
			 "programmer init.\n");
		return 1;
	}
428 429 430 431 432 433 434
	shutdown_fn[shutdown_fn_count].func = function;
	shutdown_fn[shutdown_fn_count].data = data;
	shutdown_fn_count++;

	return 0;
}

435
int programmer_init(char *param)
436
{
437
	int ret;
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
	/* Initialize all programmer specific data. */
	/* Default to unlimited decode sizes. */
	max_rom_decode = (const struct decode_sizes) {
		.parallel	= 0xffffffff,
		.lpc		= 0xffffffff,
		.fwh		= 0xffffffff,
		.spi		= 0xffffffff
	};
	/* Default to Parallel/LPC/FWH flash devices. If a known host controller
	 * is found, the init routine sets the buses_supported bitfield.
	 */
	buses_supported = CHIP_BUSTYPE_NONSPI;
	/* Default to top aligned flash at 4 GB. */
	flashbase = 0;
	/* Registering shutdown functions is now allowed. */
	may_register_shutdown = 1;
454 455
	/* Default to allowing writes. Broken programmers set this to 0. */
	programmer_may_write = 1;
456 457 458 459

	programmer_param = param;
	msg_pdbg("Initializing %s programmer\n",
		 programmer_table[programmer].name);
460 461 462 463 464 465 466
	ret = programmer_table[programmer].init();
	if (programmer_param && strlen(programmer_param)) {
		msg_perr("Unhandled programmer parameters: %s\n",
			 programmer_param);
		/* Do not error out here, the init itself was successful. */
	}
	return ret;
467 468 469 470
}

int programmer_shutdown(void)
{
471 472 473 474
	/* Registering shutdown functions is no longer allowed. */
	may_register_shutdown = 0;
	while (shutdown_fn_count > 0) {
		int i = --shutdown_fn_count;
475
		shutdown_fn[i].func(shutdown_fn[i].data);
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
	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);
}

507 508 509 510 511
void chip_writen(uint8_t *buf, chipaddr addr, size_t len)
{
	programmer_table[programmer].chip_writen(buf, addr, len);
}

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
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);
}

527 528 529 530 531
void chip_readn(uint8_t *buf, chipaddr addr, size_t len)
{
	programmer_table[programmer].chip_readn(buf, addr, len);
}

532 533 534 535 536
void programmer_delay(int usecs)
{
	programmer_table[programmer].delay(usecs);
}

537
void map_flash_registers(struct flashchip *flash)
538 539
{
	size_t size = flash->total_size * 1024;
540
	/* Flash registers live 4 MByte below the flash. */
541
	/* FIXME: This is incorrect for nonstandard flashbase. */
542
	flash->virtual_registers = (chipaddr)programmer_map_flash_region("flash chip registers", (0xFFFFFFFF - 0x400000 - size + 1), size);
543 544
}

545
int read_memmapped(struct flashchip *flash, uint8_t *buf, int start, int len)
546
{
547
	chip_readn(buf, flash->virtual_memory + start, len);
548 549 550 551
		
	return 0;
}

552 553 554 555 556
int min(int a, int b)
{
	return (a < b) ? a : b;
}

557 558 559 560 561
int max(int a, int b)
{
	return (a > b) ? a : b;
}

562 563 564 565 566 567 568 569 570
int bitcount(unsigned long a)
{
	int i = 0;
	for (; a != 0; a >>= 1)
		if (a & 1)
			i++;
	return i;
}

571 572 573
char *strcat_realloc(char *dest, const char *src)
{
	dest = realloc(dest, strlen(dest) + strlen(src) + 1);
574 575
	if (!dest) {
		msg_gerr("Out of memory!\n");
576
		return NULL;
577
	}
578 579 580 581
	strcat(dest, src);
	return dest;
}

582
/* This is a somewhat hacked function similar in some ways to strtok().
583 584 585
 * 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.
586 587 588
 */
char *extract_param(char **haystack, char *needle, char *delim)
{
589 590 591
	char *param_pos, *opt_pos, *rest;
	char *opt = NULL;
	int optlen;
592
	int needlelen;
593

594 595 596 597 598 599 600 601 602
	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;
603 604 605 606
	param_pos = strstr(*haystack, needle);
	do {
		if (!param_pos)
			return NULL;
607 608 609 610 611 612 613 614 615 616
		/* 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;
		}
617 618 619 620
		/* Continue searching. */
		param_pos++;
		param_pos = strstr(param_pos, needle);
	} while (1);
621
	
622
	if (param_pos) {
623 624 625 626 627 628
		/* 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) {
629
			msg_gerr("Out of memory!\n");
630 631
			exit(1);
		}
632 633 634 635 636 637 638
		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. */
639 640
	}

641
	return opt;
642 643
}

644 645 646 647 648
char *extract_programmer_param(char *param_name)
{
	return extract_param(&programmer_param, param_name, ",");
}

649 650 651 652 653 654 655
/* 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) {
656
		msg_gerr("Could not allocate memory!\n");
657 658 659 660 661 662 663 664 665
		exit(1);
	}
	memset(cmpbuf, 0xff, len);
	ret = verify_range(flash, cmpbuf, start, len, "ERASE");
	free(cmpbuf);
	return ret;
}

/**
666 667
 * @cmpbuf	buffer to compare against, cmpbuf[0] is expected to match the
		flash content at location start
668 669 670 671 672 673 674 675 676 677
 * @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);
678
	int failcount = 0;
679 680 681 682

	if (!len)
		goto out_free;

683
	if (!flash->read) {
684
		msg_cerr("ERROR: flashrom has no read function for this flash chip.\n");
685 686
		return 1;
	}
687
	if (!readbuf) {
688
		msg_gerr("Could not allocate memory!\n");
689 690 691 692
		exit(1);
	}

	if (start + len > flash->total_size * 1024) {
693
		msg_gerr("Error: %s called with start 0x%x + len 0x%x >"
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
			" 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;
716
		flash->read(flash, readbuf, starthere, lenhere);
717 718
		for (j = 0; j < lenhere; j++) {
			if (cmpbuf[starthere - start + j] != readbuf[j]) {
719 720
				/* Only print the first failure. */
				if (!failcount++)
721
					msg_cerr("%s FAILED at 0x%08x! "
722 723 724 725
						"Expected=0x%02x, Read=0x%02x,",
						message, starthere + j,
						cmpbuf[starthere - start + j],
						readbuf[j]);
726 727 728
			}
		}
	}
729
	if (failcount) {
730
		msg_cerr(" failed byte count from 0x%08x-0x%08x: 0x%x\n",
731 732 733
			start, start + len - 1, failcount);
		ret = -1;
	}
734 735 736 737 738 739

out_free:
	free(readbuf);
	return ret;
}

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 770 771 772 773 774 775 776 777 778 779 780 781 782 783
/**
 * 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.
 * The following write granularities (enum @gran) are known:
 * - 1 bit. Each bit can be cleared individually.
 * - 1 byte. A byte can be written once. Further writes to an already written
 *   byte cause the contents to be either undefined or to stay unchanged.
 * - 128 bytes. If less than 128 bytes are written, the rest will be
 *   erased. Each write to a 128-byte region will trigger an automatic erase
 *   before anything is written. Very uncommon behaviour and unsupported by
 *   this function.
 * - 256 bytes. If less than 256 bytes are written, the contents of the
 *   unwritten bytes are undefined.
 *
 * @have        buffer with current content
 * @want        buffer with desired content
 * @len         length of the verified area
 * @gran	write granularity (enum, not count)
 * @return      0 if no erase is needed, 1 otherwise
 */
int need_erase(uint8_t *have, uint8_t *want, int len, enum write_granularity gran)
{
	int result = 0;
	int i, j, limit;

	switch (gran) {
	case write_gran_1bit:
		for (i = 0; i < len; i++)
			if ((have[i] & want[i]) != want[i]) {
				result = 1;
				break;
			}
		break;
	case write_gran_1byte:
		for (i = 0; i < len; i++)
			if ((have[i] != want[i]) && (have[i] != 0xff)) {
				result = 1;
				break;
			}
		break;
	case write_gran_256bytes:
		for (j = 0; j < len / 256; j++) {
			limit = min (256, len - j * 256);
784
			/* Are 'have' and 'want' identical? */
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
			if (!memcmp(have + j * 256, want + j * 256, limit))
				continue;
			/* have needs to be in erased state. */
			for (i = 0; i < limit; i++)
				if (have[i] != 0xff) {
					result = 1;
					break;
				}
			if (result)
				break;
		}
		break;
	}
	return result;
}

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
/* 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) {
855
		msg_gerr("Invalid buffer!\n");
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 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
		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;
}

937 938 939 940 941 942
int check_max_decode(enum chipbustype buses, uint32_t size)
{
	int limitexceeded = 0;
	if ((buses & CHIP_BUSTYPE_PARALLEL) &&
	    (max_rom_decode.parallel < size)) {
		limitexceeded++;
943
		msg_pdbg("Chip size %u kB is bigger than supported "
944 945 946 947 948 949 950
			     "size %u kB of chipset/board/programmer "
			     "for %s interface, "
			     "probe/read/erase/write may fail. ", size / 1024,
			     max_rom_decode.parallel / 1024, "Parallel");
	}
	if ((buses & CHIP_BUSTYPE_LPC) && (max_rom_decode.lpc < size)) {
		limitexceeded++;
951
		msg_pdbg("Chip size %u kB is bigger than supported "
952 953 954 955 956 957 958
			     "size %u kB of chipset/board/programmer "
			     "for %s interface, "
			     "probe/read/erase/write may fail. ", size / 1024,
			     max_rom_decode.lpc / 1024, "LPC");
	}
	if ((buses & CHIP_BUSTYPE_FWH) && (max_rom_decode.fwh < size)) {
		limitexceeded++;
959
		msg_pdbg("Chip size %u kB is bigger than supported "
960 961 962 963 964 965 966
			     "size %u kB of chipset/board/programmer "
			     "for %s interface, "
			     "probe/read/erase/write may fail. ", size / 1024,
			     max_rom_decode.fwh / 1024, "FWH");
	}
	if ((buses & CHIP_BUSTYPE_SPI) && (max_rom_decode.spi < size)) {
		limitexceeded++;
967
		msg_pdbg("Chip size %u kB is bigger than supported "
968 969 970 971 972 973 974 975 976 977 978
			     "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)
979
		/* FIXME: This message is designed towards CLI users. */
980
		msg_pdbg("There is at least one common chip/programmer "
981 982 983 984 985
			     "interface which can support a chip of this size. "
			     "You can try --force at your own risk.\n");
	return 1;
}

986
struct flashchip *probe_flash(struct flashchip *first_flash, int force)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
987
{
988
	struct flashchip *flash;
989 990 991
	unsigned long base = 0;
	uint32_t size;
	enum chipbustype buses_common;
992
	char *tmp;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
993

994
	for (flash = first_flash; flash && flash->name; flash++) {
995
		if (chip_to_probe && strcmp(flash->name, chip_to_probe) != 0)
996
			continue;
997
		msg_gdbg("Probing for %s %s, %d KB: ",
998
			     flash->vendor, flash->name, flash->total_size);
Peter Stuge's avatar
Peter Stuge committed
999
		if (!flash->probe && !force) {
1000 1001
			msg_gdbg("failed! flashrom has no probe function for "
				 "this flash chip.\n");
1002 1003
			continue;
		}
1004 1005
		buses_common = buses_supported & flash->bustype;
		if (!buses_common) {
1006
			tmp = flashbuses_to_text(buses_supported);
1007 1008
			msg_gdbg("skipped.");
			msg_gspew(" Host bus type %s ", tmp);
1009 1010
			free(tmp);
			tmp = flashbuses_to_text(flash->bustype);
1011 1012
			msg_gspew("and chip bus type %s are incompatible.",
				  tmp);
1013
			free(tmp);
1014
			msg_gdbg("\n");
1015 1016
			continue;
		}
Stefan Reinauer's avatar
Stefan Reinauer committed
1017

1018
		size = flash->total_size * 1024;
1019
		check_max_decode(buses_common, size);
Stefan Reinauer's avatar
Stefan Reinauer committed
1020

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

1024 1025 1026
		if (force)
			break;

1027 1028 1029
		if (flash->probe(flash) != 1)
			goto notfound;

1030 1031
		if (first_flash == flashchips
		    || flash->model_id != GENERIC_DEVICE_ID)
1032
			break;
Stefan Reinauer's avatar
Stefan Reinauer committed
1033

1034
notfound:
1035
		programmer_unmap_flash_region((void *)flash->virtual_memory, size);
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1036
	}
Uwe Hermann's avatar
Uwe Hermann committed
1037

1038 1039 1040
	if (!flash || !flash->name)
		return NULL;

1041
	msg_cinfo("%s chip \"%s %s\" (%d KB, %s) at physical address 0x%lx.\n",
1042
	       force ? "Assuming" : "Found",
1043 1044 1045
	       flash->vendor, flash->name, flash->total_size,
	       flashbuses_to_text(flash->bustype), base);

1046 1047 1048
	if (flash->printlock)
		flash->printlock(flash);

1049
	return flash;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1050 1051
}

Stefan Reinauer's avatar
Stefan Reinauer committed
1052
int verify_flash(struct flashchip *flash, uint8_t *buf)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1053
{
1054
	int ret;
1055
	int total_size = flash->total_size * 1024;
1056

1057
	msg_cinfo("Verifying flash... ");
1058

1059
	ret = verify_range(flash, buf, 0, total_size, NULL);
1060

1061
	if (!ret)
1062
		msg_cinfo("VERIFIED.          \n");
1063

1064
	return ret;
Ronald G. Minnich's avatar
Fixes  
Ronald G. Minnich committed
1065 1066
}

1067
int read_flash(struct flashchip *flash, char *filename)
1068 1069 1070 1071 1072
{
	unsigned long numbytes;
	FILE *image;
	unsigned long size = flash->total_size * 1024;
	unsigned char *buf = calloc(size, sizeof(char));
1073 1074

	if (!filename) {
1075
		msg_gerr("Error: No filename specified.\n");
1076 1077
		return 1;
	}
1078
	if ((image = fopen(filename, "wb")) == NULL) {
1079 1080 1081
		perror(filename);
		exit(1);
	}
1082
	msg_cinfo("Reading flash... ");
1083
	if (!flash->read) {
1084 1085
		msg_cinfo("FAILED!\n");
		msg_cerr("ERROR: flashrom has no read function for this flash chip.\n");
1086 1087
		return 1;
	} else
1088
		flash->read(flash, buf, 0, size);
1089 1090 1091

	numbytes = fwrite(buf, 1, size, image);
	fclose(image);
1092
	free(buf);
1093
	msg_cinfo("%s.\n", numbytes == size ? "done" : "FAILED");
1094 1095 1096 1097 1098
	if (numbytes != size)
		return 1;
	return 0;
}

1099 1100 1101
/* This function shares a lot of its structure with erase_flash().
 * Even if an error is found, the function will keep going and check the rest.
 */
1102
static int selfcheck_eraseblocks(struct flashchip *flash)
1103
{
1104 1105
	int i, j, k;
	int ret = 0;
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

	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);
1119
				ret = 1;
1120 1121 1122 1123 1124 1125 1126 1127
			}
			/* 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);
1128
				ret = 1;
1129 1130 1131 1132
			}
			done += eraser.eraseblocks[i].count *
				eraser.eraseblocks[i].size;
		}
1133 1134
		/* Empty eraseblock definition with erase function.  */
		if (!done && eraser.block_erase)
1135
			msg_gspew("Strange: Empty eraseblock definition with "
1136
				"non-empty erase function. Not an error.\n");
1137 1138 1139 1140 1141 1142 1143 1144
		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);
1145
			ret = 1;
1146
		}
1147 1148 1149 1150 1151 1152
		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.
		 */
1153
		for (j = k + 1; j < NUM_ERASEFUNCTIONS; j++) {
1154 1155 1156 1157 1158 1159 1160 1161
			if (eraser.block_erase ==
			    flash->block_erasers[j].block_erase) {
				msg_gerr("ERROR: Flash chip %s erase function "
					"%i and %i are identical. Please report"
					" a bug at flashrom@flashrom.org\n",
					flash->name, k, j);
				ret = 1;
			}
1162
		}
1163
	}
1164
	return ret;
1165 1166
}

1167 1168
int erase_flash(struct flashchip *flash)
{
1169
	int i, j, k, ret = 0, found = 0;
1170
	unsigned int start, len;
1171

1172
	msg_cinfo("Erasing flash chip... ");
1173
	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
1174
		unsigned int done = 0;
1175 1176
		struct block_eraser eraser = flash->block_erasers[k];

1177
		msg_cdbg("Looking at blockwise erase function %i... ", k);
1178
		if (!eraser.block_erase && !eraser.eraseblocks[0].count) {
1179
			msg_cdbg("not defined. "
1180 1181 1182 1183
				"Looking for another erase function.\n");
			continue;
		}
		if (!eraser.block_erase && eraser.eraseblocks[0].count) {
1184
			msg_cdbg("eraseblock layout is known, but no "
1185 1186 1187 1188 1189
				"matching block erase function found. "
				"Looking for another erase function.\n");
			continue;
		}
		if (eraser.block_erase && !eraser.eraseblocks[0].count) {
1190
			msg_cdbg("block erase function found, but "
1191 1192 1193 1194 1195
				"eraseblock layout is unknown. "
				"Looking for another erase function.\n");
			continue;
		}
		found = 1;
1196
		msg_cdbg("trying... ");
1197 1198 1199 1200 1201
		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++) {
1202 1203
				start = done + eraser.eraseblocks[i].size * j;
				len = eraser.eraseblocks[i].size;
1204
				msg_cdbg("0x%06x-0x%06x, ", start,
1205 1206
					     start + len - 1);
				ret = eraser.block_erase(flash, start, len);
1207 1208 1209 1210 1211
				if (ret)
					break;
			}
			if (ret)
				break;
1212 1213
			done += eraser.eraseblocks[i].count *
				eraser.eraseblocks[i].size;
1214
		}
1215
		msg_cdbg("\n");
1216 1217 1218 1219 1220
		/* If everything is OK, don't try another erase function. */
		if (!ret)
			break;
	}
	if (!found) {
1221
		msg_cerr("ERROR: flashrom has no erase function for this flash chip.\n");
1222 1223
		return 1;
	}
1224

1225
	if (ret) {
1226
		msg_cerr("FAILED!\n");
1227
	} else {
1228
		msg_cinfo("SUCCESS.\n");
1229 1230
	}
	return ret;
1231 1232
}

1233
void emergency_help_message(void)
1234
{
1235
	msg_gerr("Your flash chip is in an unknown state.\n"
1236
		"Get help on IRC at irc.freenode.net (channel #flashrom) or\n"
1237 1238 1239
		"mail flashrom@flashrom.org!\n"
		"-------------------------------------------------------------"
		  "------------------\n"
1240 1241 1242
		"DO NOT REBOOT OR POWEROFF!\n");
}

1243 1244 1245 1246 1247
/* 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++) {
1248
		msg_ginfo("%s", programmer_table[p].name);
1249
		if (p < PROGRAMMER_INVALID - 1)
1250
			msg_ginfo("%s", delim);
1251
	}
1252
	msg_ginfo("\n");	
1253 1254
}

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
void print_sysinfo(void)
{
#if HAVE_UTSNAME == 1
	struct utsname osinfo;
	uname(&osinfo);

	msg_ginfo(" on %s %s (%s)", osinfo.sysname, osinfo.release,
		  osinfo.machine);
#else
	msg_ginfo(" on unknown machine");
#endif
	msg_ginfo(", built with");
#if NEED_PCI == 1
#ifdef PCILIB_VERSION
	msg_ginfo(" libpci %s,", PCILIB_VERSION);
#else
	msg_ginfo(" unknown PCI library,");
#endif
#endif
#ifdef __clang__
1275
	msg_ginfo(" LLVM %i/clang %i, ", __llvm__, __clang__);
1276 1277 1278
#elif defined(__GNUC__)
	msg_ginfo(" GCC");
#ifdef __VERSION__
1279 1280 1281 1282
	msg_ginfo(" %s,", __VERSION__);
#else
	msg_ginfo(" unknown version,");
#endif
1283
#else
1284
	msg_ginfo(" unknown compiler,");
1285
#endif
1286 1287
#if defined (__FLASHROM_LITTLE_ENDIAN__)
	msg_ginfo(" little endian");
1288
#else
1289
	msg_ginfo(" big endian");
1290 1291 1292 1293
#endif
	msg_ginfo("\n");
}

1294 1295
void print_version(void)
{
1296
	msg_ginfo("flashrom v%s", flashrom_version);
1297
	print_sysinfo();
1298 1299
}

1300 1301 1302 1303 1304 1305 1306
void print_banner(void)
{
	msg_ginfo("flashrom is free software, get the source code at "
		    "http://www.flashrom.org\n");
	msg_ginfo("\n");
}

1307 1308
int selfcheck(void)
{
1309 1310 1311 1312 1313 1314
	int ret = 0;
	struct flashchip *flash;

	/* Safety check. Instead of aborting after the first error, check
	 * if more errors exist.
	 */
1315
	if (ARRAY_SIZE(programmer_table) - 1 != PROGRAMMER_INVALID) {
1316
		msg_gerr("Programmer table miscompilation!\n");
1317
		ret = 1;
1318 1319
	}
	if (spi_programmer_count - 1 != SPI_CONTROLLER_INVALID) {
1320
		msg_gerr("SPI programmer table miscompilation!\n");
1321
		ret = 1;
1322
	}
1323
#if CONFIG_BITBANG_SPI == 1
1324
	if (bitbang_spi_master_count - 1 != BITBANG_SPI_INVALID) {
1325
		msg_gerr("Bitbanging SPI master table miscompilation!\n");
1326
		ret = 1;
1327 1328
	}
#endif
1329 1330 1331 1332
	for (flash = flashchips; flash && flash->name; flash++)
		if (selfcheck_eraseblocks(flash))
			ret = 1;
	return ret;
1333 1334 1335 1336 1337
}

void check_chip_supported(struct flashchip *flash)
{
	if (TEST_OK_MASK != (flash->tested & TEST_OK_MASK)) {
1338
		msg_cinfo("===\n");
1339
		if (flash->tested & TEST_BAD_MASK) {
1340
			msg_cinfo("This flash part has status NOT WORKING for operations:");
1341
			if (flash->tested & TEST_BAD_PROBE)
1342
				msg_cinfo(" PROBE");
1343
			if (flash->tested & TEST_BAD_READ)
1344
				msg_cinfo(" READ");
1345
			if (flash->tested & TEST_BAD_ERASE)
1346
				msg_cinfo(" ERASE");
1347
			if (flash->tested & TEST_BAD_WRITE)
1348 1349
				msg_cinfo(" WRITE");
			msg_cinfo("\n");
1350 1351 1352 1353 1354
		}
		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))) {
1355
			msg_cinfo("This flash part has status UNTESTED for operations:");
1356
			if (!(flash->tested & TEST_BAD_PROBE) && !(flash->tested & TEST_OK_PROBE))
1357
				msg_cinfo(" PROBE");
1358
			if (!(flash->tested & TEST_BAD_READ) && !(flash->tested & TEST_OK_READ))
1359
				msg_cinfo(" READ");
1360
			if (!(flash->tested & TEST_BAD_ERASE) && !(flash->tested & TEST_OK_ERASE))
1361
				msg_cinfo(" ERASE");
1362
			if (!(flash->tested & TEST_BAD_WRITE) && !(flash->tested & TEST_OK_WRITE))
1363 1364
				msg_cinfo(" WRITE");
			msg_cinfo("\n");
1365
		}
1366
		/* FIXME: This message is designed towards CLI users. */
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
		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"
			  "-Vw, -VE), and mention which mainboard or "
			    "programmer you tested.\n"
			  "Thanks for your help!\n"
			  "===\n");
1381 1382 1383
	}
}

1384
int main(int argc, char *argv[])
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1385
{
1386
	return cli_classic(argc, argv);
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
}

/* 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;
1401
	buf = (uint8_t *) calloc(size, sizeof(char));
1402

1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
	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.
		 */
		if (!force) {
			msg_perr("Aborting.\n");
			programmer_shutdown();
			return 1;
		} else {
			msg_cerr("Continuing anyway.\n");
		}
	}

1418
	if (erase_it) {
1419
		if (flash->tested & TEST_BAD_ERASE) {
1420
			msg_cerr("Erase is not working on this chip. ");
1421
			if (!force) {
1422
				msg_cerr("Aborting.\n");
1423
				programmer_shutdown();
1424 1425
				return 1;
			} else {
1426
				msg_cerr("Continuing anyway.\n");
1427 1428
			}
		}
1429 1430 1431
		if (flash->unlock)
			flash->unlock(flash);

1432 1433
		if (erase_flash(flash)) {
			emergency_help_message();
1434
			programmer_shutdown();
1435
			return 1;
1436
		}
1437
	} else if (read_it) {
1438 1439 1440
		if (flash->unlock)
			flash->unlock(flash);

1441 1442
		if (read_flash(flash, filename)) {
			programmer_shutdown();
1443
			return 1;
1444
		}
1445
	} else {
1446 1447
		struct stat image_stat;

1448 1449 1450
		if (flash->unlock)
			flash->unlock(flash);

1451
		if (flash->tested & TEST_BAD_ERASE) {
1452
			msg_cerr("Erase is not working on this chip "
1453 1454
				"and erase is needed for write. ");
			if (!force) {
1455
				msg_cerr("Aborting.\n");
1456
				programmer_shutdown();
1457 1458
				return 1;
			} else {
1459
				msg_cerr("Continuing anyway.\n");
1460 1461 1462
			}
		}
		if (flash->tested & TEST_BAD_WRITE) {
1463
			msg_cerr("Write is not working on this chip. ");
1464
			if (!force) {
1465
				msg_cerr("Aborting.\n");
1466
				programmer_shutdown();
1467 1468
				return 1;
			} else {
1469
				msg_cerr("Continuing anyway.\n");
1470 1471
			}
		}
1472
		if ((image = fopen(filename, "rb")) == NULL) {
1473
			perror(filename);
1474
			programmer_shutdown();
1475 1476
			exit(1);
		}
1477 1478
		if (fstat(fileno(image), &image_stat) != 0) {
			perror(filename);
1479
			programmer_shutdown();
1480 1481
			exit(1);
		}
1482
		if (image_stat.st_size != flash->total_size * 1024) {
1483
			msg_gerr("Error: Image size doesn't match\n");
1484
			programmer_shutdown();
1485 1486 1487
			exit(1);
		}

1488
		numbytes = fread(buf, 1, size, image);
1489
#if CONFIG_INTERNAL == 1
Peter Stuge's avatar
Peter Stuge committed
1490
		show_id(buf, size, force);
1491
#endif
1492
		fclose(image);
1493
		if (numbytes != size) {
1494
			msg_gerr("Error: Failed to read file. Got %ld bytes, wanted %ld!\n", numbytes, size);
1495
			programmer_shutdown();
1496 1497
			return 1;
		}
1498
	}
Ronald G. Minnich's avatar
Ronald G. Minnich committed
1499

1500 1501
	// This should be moved into each flash part's code to do it 
	// cleanly. This does the job.
1502
	handle_romentries(buf, flash);
1503

1504
	// ////////////////////////////////////////////////////////////
1505

1506
	if (write_it) {
1507
		msg_cinfo("Writing flash chip... ");
1508
		if (!flash->write) {
1509
			msg_cerr("Error: flashrom has no write function for this flash chip.\n");
1510
			programmer_shutdown();
1511 1512
			return 1;
		}
1513 1514
		ret = flash->write(flash, buf);
		if (ret) {
1515
			msg_cerr("FAILED!\n");
1516
			emergency_help_message();
1517
			programmer_shutdown();
1518 1519
			return 1;
		} else {
1520
			msg_cinfo("COMPLETE.\n");
1521
		}
1522
	}
1523

1524 1525 1526 1527
	if (verify_it) {
		/* Work around chips which need some time to calm down. */
		if (write_it)
			programmer_delay(1000*1000);
1528
		ret = verify_flash(flash, buf);
1529
		/* If we tried to write, and verification now fails, we
1530 1531 1532 1533 1534
		 * might have an emergency situation.
		 */
		if (ret && write_it)
			emergency_help_message();
	}
1535

1536 1537
	programmer_shutdown();

Stefan Reinauer's avatar
Stefan Reinauer committed
1538
	return ret;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1539
}