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

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

41
const char flashrom_version[] = FLASHROM_VERSION;
Ronald G. Minnich's avatar
Ronald G. Minnich committed
42
char *chip_to_probe = NULL;
Peter Stuge's avatar
Peter Stuge committed
43
int verbose = 0;
44

45
#if CONFIG_INTERNAL == 1
46
enum programmer programmer = PROGRAMMER_INTERNAL;
47
#elif CONFIG_DUMMY == 1
48 49
enum programmer programmer = PROGRAMMER_DUMMY;
#else
50 51 52 53 54
/* 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.
 */
55
#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+CONFIG_RAYER_SPI+CONFIG_NICINTEL+CONFIG_NICINTEL_SPI+CONFIG_OGP_SPI+CONFIG_SATAMV > 1
56
#error Please enable either CONFIG_DUMMY or CONFIG_INTERNAL or disable support for all programmers except one.
57 58
#endif
enum programmer programmer =
59
#if CONFIG_NIC3COM == 1
60 61
	PROGRAMMER_NIC3COM
#endif
62
#if CONFIG_NICREALTEK == 1
63 64
	PROGRAMMER_NICREALTEK
#endif
65 66 67
#if CONFIG_NICNATSEMI == 1
	PROGRAMMER_NICNATSEMI
#endif
68
#if CONFIG_GFXNVIDIA == 1
69 70
	PROGRAMMER_GFXNVIDIA
#endif
71
#if CONFIG_DRKAISER == 1
72 73
	PROGRAMMER_DRKAISER
#endif
74
#if CONFIG_SATASII == 1
75 76
	PROGRAMMER_SATASII
#endif
77
#if CONFIG_ATAHPT == 1
78 79
	PROGRAMMER_ATAHPT
#endif
80 81
#if CONFIG_FT2232_SPI == 1
	PROGRAMMER_FT2232_SPI
82
#endif
83
#if CONFIG_SERPROG == 1
84 85
	PROGRAMMER_SERPROG
#endif
86 87
#if CONFIG_BUSPIRATE_SPI == 1
	PROGRAMMER_BUSPIRATE_SPI
88
#endif
89
#if CONFIG_DEDIPROG == 1
90 91
	PROGRAMMER_DEDIPROG
#endif
92 93 94
#if CONFIG_RAYER_SPI == 1
	PROGRAMMER_RAYER_SPI
#endif
95 96 97
#if CONFIG_NICINTEL == 1
	PROGRAMMER_NICINTEL
#endif
98 99 100
#if CONFIG_NICINTEL_SPI == 1
	PROGRAMMER_NICINTEL_SPI
#endif
101 102 103
#if CONFIG_OGP_SPI == 1
	PROGRAMMER_OGP_SPI
#endif
104 105 106
#if CONFIG_SATAMV == 1
	PROGRAMMER_SATAMV
#endif
107 108 109
#if CONFIG_LINUX_SPI == 1
	PROGRAMMER_LINUX_SPI
#endif
110
;
111 112
#endif

113
static char *programmer_param = NULL;
114

115 116
/* Supported buses for the current programmer. */
enum chipbustype buses_supported;
117

118
/*
119 120 121
 * Programmers supporting multiple buses can have differing size limits on
 * each bus. Store the limits for each bus in a common struct.
 */
122 123 124 125
struct decode_sizes max_rom_decode;

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

127 128 129
/* Is writing allowed with this programmer? */
int programmer_may_write;

130
const struct programmer_entry programmer_table[] = {
131
#if CONFIG_INTERNAL == 1
132
	{
133
		.name			= "internal",
134
		.init			= internal_init,
135 136
		.map_flash_region	= physmap,
		.unmap_flash_region	= physunmap,
137 138 139
		.chip_readb		= internal_chip_readb,
		.chip_readw		= internal_chip_readw,
		.chip_readl		= internal_chip_readl,
140
		.chip_readn		= internal_chip_readn,
141 142 143
		.chip_writeb		= internal_chip_writeb,
		.chip_writew		= internal_chip_writew,
		.chip_writel		= internal_chip_writel,
144
		.chip_writen		= fallback_chip_writen,
145
		.delay			= internal_delay,
146
	},
147
#endif
148

149
#if CONFIG_DUMMY == 1
150
	{
151
		.name			= "dummy",
152
		.init			= dummy_init,
153 154
		.map_flash_region	= dummy_map,
		.unmap_flash_region	= dummy_unmap,
155 156 157
		.chip_readb		= dummy_chip_readb,
		.chip_readw		= dummy_chip_readw,
		.chip_readl		= dummy_chip_readl,
158
		.chip_readn		= dummy_chip_readn,
159 160 161
		.chip_writeb		= dummy_chip_writeb,
		.chip_writew		= dummy_chip_writew,
		.chip_writel		= dummy_chip_writel,
162
		.chip_writen		= dummy_chip_writen,
163
		.delay			= internal_delay,
164
	},
165
#endif
166

167
#if CONFIG_NIC3COM == 1
168
	{
169
		.name			= "nic3com",
170
		.init			= nic3com_init,
171 172
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
173
		.chip_readb		= nic3com_chip_readb,
174 175
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
176
		.chip_readn		= fallback_chip_readn,
177
		.chip_writeb		= nic3com_chip_writeb,
178 179
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
180
		.chip_writen		= fallback_chip_writen,
181
		.delay			= internal_delay,
182
	},
183
#endif
184

185
#if CONFIG_NICREALTEK == 1
186
	{
187
		/* This programmer works for Realtek RTL8139 and SMC 1211. */
188 189 190 191 192 193 194 195 196 197 198 199 200 201
		.name			= "nicrealtek",
		//.name			= "nicsmc1211",
		.init			= nicrealtek_init,
		.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,
202 203 204
	},
#endif

205 206
#if CONFIG_NICNATSEMI == 1
	{
207 208 209 210 211 212 213 214 215 216 217 218 219
		.name			= "nicnatsemi",
		.init			= nicnatsemi_init,
		.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,
220 221
	},
#endif
222

223
#if CONFIG_GFXNVIDIA == 1
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
	{
		.name			= "gfxnvidia",
		.init			= gfxnvidia_init,
		.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

241
#if CONFIG_DRKAISER == 1
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
	{
		.name			= "drkaiser",
		.init			= drkaiser_init,
		.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
		.init			= satasii_init,
263 264
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
265 266 267
		.chip_readb		= satasii_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
268
		.chip_readn		= fallback_chip_readn,
269 270 271
		.chip_writeb		= satasii_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
272
		.chip_writen		= fallback_chip_writen,
273
		.delay			= internal_delay,
274
	},
275
#endif
276

277
#if CONFIG_ATAHPT == 1
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
	{
		.name			= "atahpt",
		.init			= atahpt_init,
		.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

295
#if CONFIG_FT2232_SPI == 1
296
	{
297
		.name			= "ft2232_spi",
298
		.init			= ft2232_spi_init,
299 300
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
301
		.chip_readb		= noop_chip_readb,
302 303 304
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
305
		.chip_writeb		= noop_chip_writeb,
306 307 308 309 310
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
311
#endif
312

313
#if CONFIG_SERPROG == 1
314
	{
315
		.name			= "serprog",
316 317 318 319 320 321 322 323 324 325 326 327 328
		.init			= serprog_init,
		.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,
	},
329
#endif
330

331
#if CONFIG_BUSPIRATE_SPI == 1
332
	{
333
		.name			= "buspirate_spi",
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
		.init			= buspirate_spi_init,
		.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

349
#if CONFIG_DEDIPROG == 1
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
	{
		.name			= "dediprog",
		.init			= dediprog_init,
		.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

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
#if CONFIG_RAYER_SPI == 1
	{
		.name			= "rayer_spi",
		.init			= rayer_spi_init,
		.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

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
#if CONFIG_NICINTEL == 1
	{
		.name			= "nicintel",
		.init			= nicintel_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.chip_readb		= nicintel_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
		.chip_writeb		= nicintel_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
#endif

403 404
#if CONFIG_NICINTEL_SPI == 1
	{
405 406 407 408 409 410 411 412 413 414 415 416 417
		.name			= "nicintel_spi",
		.init			= nicintel_spi_init,
		.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,
418 419 420
	},
#endif

421 422
#if CONFIG_OGP_SPI == 1
	{
423 424 425 426 427 428 429 430 431 432 433 434 435
		.name			= "ogp_spi",
		.init			= ogp_spi_init,
		.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,
436 437 438
	},
#endif

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
#if CONFIG_SATAMV == 1
	{
		.name			= "satamv",
		.init			= satamv_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.chip_readb		= satamv_chip_readb,
		.chip_readw		= fallback_chip_readw,
		.chip_readl		= fallback_chip_readl,
		.chip_readn		= fallback_chip_readn,
		.chip_writeb		= satamv_chip_writeb,
		.chip_writew		= fallback_chip_writew,
		.chip_writel		= fallback_chip_writel,
		.chip_writen		= fallback_chip_writen,
		.delay			= internal_delay,
	},
#endif

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
#if CONFIG_LINUX_SPI == 1
	{
		.name			= "linux_spi",
		.init			= linux_spi_init,
		.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

475
	{}, /* This entry corresponds to PROGRAMMER_INVALID. */
476
};
477

478
#define SHUTDOWN_MAXFN 32
479 480
static int shutdown_fn_count = 0;
struct shutdown_func_data {
481
	int (*func) (void *data);
482
	void *data;
483 484 485 486 487
} 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;
488

489 490
static int check_block_eraser(const struct flashchip *flash, int k, int log);

491 492 493 494 495 496 497 498
/* 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.
 */
499
int register_shutdown(int (*function) (void *data), void *data)
500 501
{
	if (shutdown_fn_count >= SHUTDOWN_MAXFN) {
502
		msg_perr("Tried to register more than %i shutdown functions.\n",
503 504 505
			 SHUTDOWN_MAXFN);
		return 1;
	}
506 507 508 509 510
	if (!may_register_shutdown) {
		msg_perr("Tried to register a shutdown function before "
			 "programmer init.\n");
		return 1;
	}
511 512 513 514 515 516 517
	shutdown_fn[shutdown_fn_count].func = function;
	shutdown_fn[shutdown_fn_count].data = data;
	shutdown_fn_count++;

	return 0;
}

518
int programmer_init(char *param)
519
{
520
	int ret;
521 522 523 524 525 526
	/* Initialize all programmer specific data. */
	/* Default to unlimited decode sizes. */
	max_rom_decode = (const struct decode_sizes) {
		.parallel	= 0xffffffff,
		.lpc		= 0xffffffff,
		.fwh		= 0xffffffff,
527
		.spi		= 0xffffffff,
528
	};
529
	buses_supported = BUS_NONE;
530 531 532 533
	/* Default to top aligned flash at 4 GB. */
	flashbase = 0;
	/* Registering shutdown functions is now allowed. */
	may_register_shutdown = 1;
534 535
	/* Default to allowing writes. Broken programmers set this to 0. */
	programmer_may_write = 1;
536 537 538 539

	programmer_param = param;
	msg_pdbg("Initializing %s programmer\n",
		 programmer_table[programmer].name);
540 541 542 543 544 545 546
	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;
547 548 549 550
}

int programmer_shutdown(void)
{
551 552
	int ret = 0;

553 554 555 556
	/* Registering shutdown functions is no longer allowed. */
	may_register_shutdown = 0;
	while (shutdown_fn_count > 0) {
		int i = --shutdown_fn_count;
557
		ret |= shutdown_fn[i].func(shutdown_fn[i].data);
558
	}
559
	return ret;
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
}

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

589 590 591 592 593
void chip_writen(uint8_t *buf, chipaddr addr, size_t len)
{
	programmer_table[programmer].chip_writen(buf, addr, len);
}

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
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);
}

609 610 611 612 613
void chip_readn(uint8_t *buf, chipaddr addr, size_t len)
{
	programmer_table[programmer].chip_readn(buf, addr, len);
}

614 615 616 617 618
void programmer_delay(int usecs)
{
	programmer_table[programmer].delay(usecs);
}

619
void map_flash_registers(struct flashchip *flash)
620 621
{
	size_t size = flash->total_size * 1024;
622
	/* Flash registers live 4 MByte below the flash. */
623
	/* FIXME: This is incorrect for nonstandard flashbase. */
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
624
	flash->virtual_registers = (chipaddr)programmer_map_flash_region("flash chip registers", (0xFFFFFFFF - 0x400000 - size + 1), size);
625 626
}

627
int read_memmapped(struct flashchip *flash, uint8_t *buf, int start, int len)
628
{
629
	chip_readn(buf, flash->virtual_memory + start, len);
630

631 632 633
	return 0;
}

634 635 636 637 638
int min(int a, int b)
{
	return (a < b) ? a : b;
}

639 640 641 642 643
int max(int a, int b)
{
	return (a > b) ? a : b;
}

644 645 646 647 648 649 650 651 652
int bitcount(unsigned long a)
{
	int i = 0;
	for (; a != 0; a >>= 1)
		if (a & 1)
			i++;
	return i;
}

653 654 655 656 657 658
void tolower_string(char *str)
{
	for (; *str != '\0'; str++)
		*str = (char)tolower((unsigned char)*str);
}

659 660 661
char *strcat_realloc(char *dest, const char *src)
{
	dest = realloc(dest, strlen(dest) + strlen(src) + 1);
662 663
	if (!dest) {
		msg_gerr("Out of memory!\n");
664
		return NULL;
665
	}
666 667 668 669
	strcat(dest, src);
	return dest;
}

670
/* This is a somewhat hacked function similar in some ways to strtok().
671 672 673
 * 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.
674
 */
675
char *extract_param(char **haystack, const char *needle, const char *delim)
676
{
677 678 679
	char *param_pos, *opt_pos, *rest;
	char *opt = NULL;
	int optlen;
680
	int needlelen;
681

682 683 684 685 686 687 688 689 690
	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;
691 692 693 694
	param_pos = strstr(*haystack, needle);
	do {
		if (!param_pos)
			return NULL;
695 696 697 698 699 700 701 702 703 704
		/* 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;
		}
705 706 707 708
		/* Continue searching. */
		param_pos++;
		param_pos = strstr(param_pos, needle);
	} while (1);
709

710
	if (param_pos) {
711 712 713 714 715 716
		/* 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) {
717
			msg_gerr("Out of memory!\n");
718 719
			exit(1);
		}
720 721 722 723 724 725 726
		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. */
727 728
	}

729
	return opt;
730 731
}

732
char *extract_programmer_param(const char *param_name)
733 734 735 736
{
	return extract_param(&programmer_param, param_name, ",");
}

737 738
/* Returns the number of well-defined erasers for a chip. */
static unsigned int count_usable_erasers(const struct flashchip *flash)
739 740 741 742 743 744 745 746 747 748
{
	unsigned int usable_erasefunctions = 0;
	int k;
	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
		if (!check_block_eraser(flash, k, 0))
			usable_erasefunctions++;
	}
	return usable_erasefunctions;
}

749 750 751 752 753 754 755
/* 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) {
756
		msg_gerr("Could not allocate memory!\n");
757 758 759 760 761 762 763 764
		exit(1);
	}
	memset(cmpbuf, 0xff, len);
	ret = verify_range(flash, cmpbuf, start, len, "ERASE");
	free(cmpbuf);
	return ret;
}

765
/*
766
 * @cmpbuf	buffer to compare against, cmpbuf[0] is expected to match the
767
 *		flash content at location start
768 769 770 771 772
 * @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
 */
773 774
int verify_range(struct flashchip *flash, uint8_t *cmpbuf, int start, int len,
		 const char *message)
775
{
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
776
	int i;
777
	uint8_t *readbuf = malloc(len);
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
778
	int ret = 0, failcount = 0;
779 780 781 782

	if (!len)
		goto out_free;

783
	if (!flash->read) {
784
		msg_cerr("ERROR: flashrom has no read function for this flash chip.\n");
785 786
		return 1;
	}
787
	if (!readbuf) {
788
		msg_gerr("Could not allocate memory!\n");
789 790 791 792
		exit(1);
	}

	if (start + len > flash->total_size * 1024) {
793
		msg_gerr("Error: %s called with start 0x%x + len 0x%x >"
794 795 796 797 798 799 800
			" total_size 0x%x\n", __func__, start, len,
			flash->total_size * 1024);
		ret = -1;
		goto out_free;
	}
	if (!message)
		message = "VERIFY";
801

802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
	ret = flash->read(flash, readbuf, start, len);
	if (ret) {
		msg_gerr("Verification impossible because read failed "
			 "at 0x%x (len 0x%x)\n", start, len);
		return ret;
	}

	for (i = 0; i < len; i++) {
		if (cmpbuf[i] != readbuf[i]) {
			/* Only print the first failure. */
			if (!failcount++)
				msg_cerr("%s FAILED at 0x%08x! "
					 "Expected=0x%02x, Read=0x%02x,",
					 message, start + i, cmpbuf[i],
					 readbuf[i]);
817 818
		}
	}
819
	if (failcount) {
820
		msg_cerr(" failed byte count from 0x%08x-0x%08x: 0x%x\n",
821
			 start, start + len - 1, failcount);
822 823
		ret = -1;
	}
824 825 826 827 828 829

out_free:
	free(readbuf);
	return ret;
}

830
/*
831 832 833
 * 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.
834
 *
835 836 837 838 839 840 841 842 843 844
 * 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.
845 846
 * Warning: This function assumes that @have and @want point to naturally
 * aligned regions.
847 848 849
 *
 * @have        buffer with current content
 * @want        buffer with desired content
850
 * @len		length of the checked area
851 852 853 854 855
 * @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)
{
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
856 857
	int result = 0;
	int i, j, limit;
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876

	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);
877
			/* Are 'have' and 'want' identical? */
878 879 880 881
			if (!memcmp(have + j * 256, want + j * 256, limit))
				continue;
			/* have needs to be in erased state. */
			for (i = 0; i < limit; i++)
882
				if (have[j * 256 + i] != 0xff) {
883 884 885 886 887 888 889
					result = 1;
					break;
				}
			if (result)
				break;
		}
		break;
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
	default:
		msg_cerr("%s: Unsupported granularity! Please report a bug at "
			 "flashrom@flashrom.org\n", __func__);
	}
	return result;
}

/**
 * Check if the buffer @have needs to be programmed to get the content of @want.
 * If yes, return 1 and fill in first_start with the start address of the
 * write operation and first_len with the length of the first to-be-written
 * chunk. If not, return 0 and leave first_start and first_len undefined.
 *
 * Warning: This function assumes that @have and @want point to naturally
 * aligned regions.
 *
 * @have	buffer with current content
 * @want	buffer with desired content
 * @len		length of the checked area
 * @gran	write granularity (enum, not count)
910 911 912 913 914
 * @first_start	offset of the first byte which needs to be written (passed in
 *		value is increased by the offset of the first needed write
 *		relative to have/want or unchanged if no write is needed)
 * @return	length of the first contiguous area which needs to be written
 *		0 if no write is needed
915 916 917 918 919 920
 *
 * FIXME: This function needs a parameter which tells it about coalescing
 * in relation to the max write length of the programmer and the max write
 * length of the chip.
 */
static int get_next_write(uint8_t *have, uint8_t *want, int len,
921
			  int *first_start, enum write_granularity gran)
922
{
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
923 924
	int need_write = 0, rel_start = 0, first_len = 0;
	int i, limit, stride;
925 926 927 928

	switch (gran) {
	case write_gran_1bit:
	case write_gran_1byte:
929
		stride = 1;
930 931
		break;
	case write_gran_256bytes:
932
		stride = 256;
933 934 935 936
		break;
	default:
		msg_cerr("%s: Unsupported granularity! Please report a bug at "
			 "flashrom@flashrom.org\n", __func__);
937 938 939 940
		/* Claim that no write was needed. A write with unknown
		 * granularity is too dangerous to try.
		 */
		return 0;
941
	}
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
	for (i = 0; i < len / stride; i++) {
		limit = min(stride, len - i * stride);
		/* Are 'have' and 'want' identical? */
		if (memcmp(have + i * stride, want + i * stride, limit)) {
			if (!need_write) {
				/* First location where have and want differ. */
				need_write = 1;
				rel_start = i * stride;
			}
		} else {
			if (need_write) {
				/* First location where have and want
				 * do not differ anymore.
				 */
				break;
			}
		}
	}
960
	if (need_write)
961
		first_len = min(i * stride - rel_start, len);
962
	*first_start += rel_start;
963
	return first_len;
964 965
}

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
/* 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) {
1020
		msg_gerr("Invalid buffer!\n");
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
		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;
}

1102 1103 1104
int check_max_decode(enum chipbustype buses, uint32_t size)
{
	int limitexceeded = 0;
1105 1106

	if ((buses & BUS_PARALLEL) && (max_rom_decode.parallel < size)) {
1107
		limitexceeded++;
1108
		msg_pdbg("Chip size %u kB is bigger than supported "
1109 1110 1111 1112
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.parallel / 1024, "Parallel");
1113
	}
1114
	if ((buses & BUS_LPC) && (max_rom_decode.lpc < size)) {
1115
		limitexceeded++;
1116
		msg_pdbg("Chip size %u kB is bigger than supported "
1117 1118 1119 1120
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.lpc / 1024, "LPC");
1121
	}
1122
	if ((buses & BUS_FWH) && (max_rom_decode.fwh < size)) {
1123
		limitexceeded++;
1124
		msg_pdbg("Chip size %u kB is bigger than supported "
1125 1126 1127 1128
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.fwh / 1024, "FWH");
1129
	}
1130
	if ((buses & BUS_SPI) && (max_rom_decode.spi < size)) {
1131
		limitexceeded++;
1132
		msg_pdbg("Chip size %u kB is bigger than supported "
1133 1134 1135 1136
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.spi / 1024, "SPI");
1137 1138 1139 1140 1141 1142 1143
	}
	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)
1144
		/* FIXME: This message is designed towards CLI users. */
1145
		msg_pdbg("There is at least one common chip/programmer "
1146 1147
			 "interface which can support a chip of this size. "
			 "You can try --force at your own risk.\n");
1148 1149 1150
	return 1;
}

1151
int probe_flash(int startchip, struct flashchip *fill_flash, int force)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1152
{
1153
	const struct flashchip *flash;
1154
	unsigned long base = 0;
1155
	char location[64];
1156 1157
	uint32_t size;
	enum chipbustype buses_common;
1158
	char *tmp;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1159

1160
	for (flash = flashchips + startchip; flash && flash->name; flash++) {
1161
		if (chip_to_probe && strcmp(flash->name, chip_to_probe) != 0)
1162
			continue;
1163 1164
		buses_common = buses_supported & flash->bustype;
		if (!buses_common) {
1165 1166
			msg_gspew("Probing for %s %s, %d kB: skipped. ",
			         flash->vendor, flash->name, flash->total_size);
1167
			tmp = flashbuses_to_text(buses_supported);
1168
			msg_gspew("Host bus type %s ", tmp);
1169 1170
			free(tmp);
			tmp = flashbuses_to_text(flash->bustype);
1171 1172
			msg_gspew("and chip bus type %s are incompatible.",
				  tmp);
1173
			free(tmp);
1174 1175 1176 1177 1178 1179 1180 1181
			msg_gspew("\n");
			continue;
		}
		msg_gdbg("Probing for %s %s, %d kB: ",
			     flash->vendor, flash->name, flash->total_size);
		if (!flash->probe && !force) {
			msg_gdbg("failed! flashrom has no probe function for "
				 "this flash chip.\n");
1182 1183
			continue;
		}
Stefan Reinauer's avatar
Stefan Reinauer committed
1184

1185
		size = flash->total_size * 1024;
1186
		check_max_decode(buses_common, size);
Stefan Reinauer's avatar
Stefan Reinauer committed
1187

1188 1189 1190
		/* Start filling in the dynamic data. */
		*fill_flash = *flash;

1191
		base = flashbase ? flashbase : (0xffffffff - size + 1);
1192
		fill_flash->virtual_memory = (chipaddr)programmer_map_flash_region("flash chip", base, size);
1193

1194 1195 1196
		if (force)
			break;

1197
		if (fill_flash->probe(fill_flash) != 1)
1198 1199
			goto notfound;

1200 1201 1202 1203 1204 1205 1206 1207 1208
		/* If this is the first chip found, accept it.
		 * If this is not the first chip found, accept it only if it is
		 * a non-generic match.
		 * We could either make chipcount global or provide it as
		 * parameter, or we assume that startchip==0 means this call to
		 * probe_flash() is the first one and thus no chip has been
		 * found before.
		 */
		if (startchip == 0 || fill_flash->model_id != GENERIC_DEVICE_ID)
1209
			break;
Stefan Reinauer's avatar
Stefan Reinauer committed
1210

1211
notfound:
1212
		programmer_unmap_flash_region((void *)fill_flash->virtual_memory, size);
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1213
	}
Uwe Hermann's avatar
Uwe Hermann committed
1214

1215
	if (!flash || !flash->name)
1216
		return -1;
1217

1218 1219
#if CONFIG_INTERNAL == 1
	if (programmer_table[programmer].map_flash_region == physmap)
1220
		snprintf(location, sizeof(location), "at physical address 0x%lx", base);
1221 1222
	else
#endif
1223 1224
		snprintf(location, sizeof(location), "on %s", programmer_table[programmer].name);

1225
	tmp = flashbuses_to_text(flash->bustype);
1226
	msg_cinfo("%s %s flash chip \"%s\" (%d kB, %s) %s.\n",
1227 1228 1229
		  force ? "Assuming" : "Found", fill_flash->vendor,
		  fill_flash->name, fill_flash->total_size, tmp, location);
	free(tmp);
1230

1231 1232 1233 1234
	/* Flash registers will not be mapped if the chip was forced. Lock info
	 * may be stored in registers, so avoid lock info printing.
	 */
	if (!force)
1235 1236
		if (fill_flash->printlock)
			fill_flash->printlock(fill_flash);
1237

1238 1239
	/* Return position of matching chip. */
	return flash - flashchips;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1240 1241
}

Stefan Reinauer's avatar
Stefan Reinauer committed
1242
int verify_flash(struct flashchip *flash, uint8_t *buf)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1243
{
1244
	int ret;
1245
	int total_size = flash->total_size * 1024;
1246

1247
	msg_cinfo("Verifying flash... ");
1248

1249
	ret = verify_range(flash, buf, 0, total_size, NULL);
1250

1251
	if (!ret)
1252
		msg_cinfo("VERIFIED.          \n");
1253

1254
	return ret;
Ronald G. Minnich's avatar
Fixes  
Ronald G. Minnich committed
1255 1256
}

1257 1258
int read_buf_from_file(unsigned char *buf, unsigned long size,
		       const char *filename)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
{
	unsigned long numbytes;
	FILE *image;
	struct stat image_stat;

	if ((image = fopen(filename, "rb")) == NULL) {
		perror(filename);
		return 1;
	}
	if (fstat(fileno(image), &image_stat) != 0) {
		perror(filename);
		fclose(image);
		return 1;
	}
	if (image_stat.st_size != size) {
		msg_gerr("Error: Image size doesn't match\n");
		fclose(image);
		return 1;
	}
	numbytes = fread(buf, 1, size, image);
	if (fclose(image)) {
		perror(filename);
		return 1;
	}
	if (numbytes != size) {
		msg_gerr("Error: Failed to read complete file. Got %ld bytes, "
			 "wanted %ld!\n", numbytes, size);
		return 1;
	}
	return 0;
}

1291 1292
int write_buf_to_file(unsigned char *buf, unsigned long size,
		      const char *filename)
1293 1294 1295
{
	unsigned long numbytes;
	FILE *image;
1296 1297

	if (!filename) {
1298
		msg_gerr("No filename specified.\n");
1299 1300
		return 1;
	}
1301
	if ((image = fopen(filename, "wb")) == NULL) {
1302
		perror(filename);
1303
		return 1;
1304
	}
1305 1306 1307

	numbytes = fwrite(buf, 1, size, image);
	fclose(image);
1308 1309 1310
	if (numbytes != size) {
		msg_gerr("File %s could not be written completely.\n",
			 filename);
1311
		return 1;
1312
	}
1313 1314 1315
	return 0;
}

1316
int read_flash_to_file(struct flashchip *flash, const char *filename)
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
{
	unsigned long size = flash->total_size * 1024;
	unsigned char *buf = calloc(size, sizeof(char));
	int ret = 0;

	msg_cinfo("Reading flash... ");
	if (!buf) {
		msg_gerr("Memory allocation failed!\n");
		msg_cinfo("FAILED.\n");
		return 1;
	}
	if (!flash->read) {
		msg_cerr("No read function available for this flash chip.\n");
		ret = 1;
		goto out_free;
	}
	if (flash->read(flash, buf, 0, size)) {
		msg_cerr("Read operation failed!\n");
		ret = 1;
		goto out_free;
	}

Stefan Tauner's avatar
Stefan Tauner committed
1339
	ret = write_buf_to_file(buf, size, filename);
1340 1341 1342 1343 1344 1345
out_free:
	free(buf);
	msg_cinfo("%s.\n", ret ? "FAILED" : "done");
	return ret;
}

1346 1347
/* This function shares a lot of its structure with erase_and_write_flash() and
 * walk_eraseregions().
1348 1349
 * Even if an error is found, the function will keep going and check the rest.
 */
1350
static int selfcheck_eraseblocks(const struct flashchip *flash)
1351
{
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1352 1353
	int i, j, k;
	int ret = 0;
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366

	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);
1367
				ret = 1;
1368 1369 1370 1371 1372 1373 1374 1375
			}
			/* 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);
1376
				ret = 1;
1377 1378 1379 1380
			}
			done += eraser.eraseblocks[i].count *
				eraser.eraseblocks[i].size;
		}
1381 1382
		/* Empty eraseblock definition with erase function.  */
		if (!done && eraser.block_erase)
1383
			msg_gspew("Strange: Empty eraseblock definition with "
1384
				  "non-empty erase function. Not an error.\n");
1385 1386 1387 1388 1389 1390 1391 1392
		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);
1393
			ret = 1;
1394
		}
1395 1396 1397 1398 1399 1400
		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.
		 */
1401
		for (j = k + 1; j < NUM_ERASEFUNCTIONS; j++) {
1402 1403 1404 1405 1406 1407 1408 1409
			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;
			}
1410
		}
1411
	}
1412
	return ret;
1413 1414
}

1415 1416
static int erase_and_write_block_helper(struct flashchip *flash,
					unsigned int start, unsigned int len,
1417
					uint8_t *curcontents,
1418 1419 1420 1421 1422
					uint8_t *newcontents,
					int (*erasefn) (struct flashchip *flash,
							unsigned int addr,
							unsigned int len))
{
1423
	int starthere = 0, lenhere = 0, ret = 0, skip = 1, writecount = 0;
1424 1425
	enum write_granularity gran = write_gran_256bytes; /* FIXME */

1426
	/* curcontents and newcontents are opaque to walk_eraseregions, and
1427 1428
	 * need to be adjusted here to keep the impression of proper abstraction
	 */
1429
	curcontents += start;
1430 1431 1432
	newcontents += start;
	msg_cdbg(":");
	/* FIXME: Assume 256 byte granularity for now to play it safe. */
1433
	if (need_erase(curcontents, newcontents, len, gran)) {
1434 1435 1436 1437
		msg_cdbg("E");
		ret = erasefn(flash, start, len);
		if (ret)
			return ret;
1438 1439 1440 1441
		if (check_erased_range(flash, start, len)) {
			msg_cerr("ERASE FAILED!\n");
			return -1;
		}
1442 1443
		/* Erase was successful. Adjust curcontents. */
		memset(curcontents, 0xff, len);
1444 1445
		skip = 0;
	}
1446 1447 1448 1449
	/* get_next_write() sets starthere to a new value after the call. */
	while ((lenhere = get_next_write(curcontents + starthere,
					 newcontents + starthere,
					 len - starthere, &starthere, gran))) {
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
		if (!writecount++)
			msg_cdbg("W");
		/* Needs the partial write function signature. */
		ret = flash->write(flash, newcontents + starthere,
				   start + starthere, lenhere);
		if (ret)
			return ret;
		starthere += lenhere;
		skip = 0;
	}
	if (skip)
		msg_cdbg("S");
	return ret;
}

1465 1466 1467
static int walk_eraseregions(struct flashchip *flash, int erasefunction,
			     int (*do_something) (struct flashchip *flash,
						  unsigned int addr,
1468 1469 1470 1471 1472 1473 1474 1475
						  unsigned int len,
						  uint8_t *param1,
						  uint8_t *param2,
						  int (*erasefn) (
							struct flashchip *flash,
							unsigned int addr,
							unsigned int len)),
			     void *param1, void *param2)
1476 1477
{
	int i, j;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1478 1479
	unsigned int start = 0;
	unsigned int len;
1480
	struct block_eraser eraser = flash->block_erasers[erasefunction];
1481

1482 1483 1484 1485 1486 1487
	for (i = 0; i < NUM_ERASEREGIONS; i++) {
		/* count==0 for all automatically initialized array
		 * members so the loop below won't be executed for them.
		 */
		len = eraser.eraseblocks[i].size;
		for (j = 0; j < eraser.eraseblocks[i].count; j++) {
1488 1489 1490 1491
			/* Print this for every block except the first one. */
			if (i || j)
				msg_cdbg(", ");
			msg_cdbg("0x%06x-0x%06x", start,
1492
				     start + len - 1);
1493 1494
			if (do_something(flash, start, len, param1, param2,
					 eraser.block_erase)) {
1495
				return 1;
1496
			}
1497 1498 1499
			start += len;
		}
	}
1500
	msg_cdbg("\n");
1501 1502 1503
	return 0;
}

1504
static int check_block_eraser(const struct flashchip *flash, int k, int log)
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
{
	struct block_eraser eraser = flash->block_erasers[k];

	if (!eraser.block_erase && !eraser.eraseblocks[0].count) {
		if (log)
			msg_cdbg("not defined. ");
		return 1;
	}
	if (!eraser.block_erase && eraser.eraseblocks[0].count) {
		if (log)
			msg_cdbg("eraseblock layout is known, but matching "
Stefan Tauner's avatar
Stefan Tauner committed
1516
				 "block erase function is not implemented. ");
1517 1518 1519 1520 1521
		return 1;
	}
	if (eraser.block_erase && !eraser.eraseblocks[0].count) {
		if (log)
			msg_cdbg("block erase function found, but "
Stefan Tauner's avatar
Stefan Tauner committed
1522
				 "eraseblock layout is not defined. ");
1523 1524 1525 1526 1527
		return 1;
	}
	return 0;
}

1528 1529
int erase_and_write_flash(struct flashchip *flash, uint8_t *oldcontents,
			  uint8_t *newcontents)
1530
{
1531
	int k, ret = 1;
1532 1533
	uint8_t *curcontents;
	unsigned long size = flash->total_size * 1024;
1534
	unsigned int usable_erasefunctions = count_usable_erasers(flash);
1535 1536

	msg_cinfo("Erasing and writing flash chip... ");
1537 1538 1539 1540 1541
	curcontents = malloc(size);
	if (!curcontents) {
		msg_gerr("Out of memory!\n");
		exit(1);
	}
1542 1543
	/* Copy oldcontents to curcontents to avoid clobbering oldcontents. */
	memcpy(curcontents, oldcontents, size);
1544 1545

	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
1546 1547
		if (k != 0)
			msg_cdbg("Looking for another erase function.\n");
1548 1549 1550 1551
		if (!usable_erasefunctions) {
			msg_cdbg("No usable erase functions left.\n");
			break;
		}
1552 1553
		msg_cdbg("Trying erase function %i... ", k);
		if (check_block_eraser(flash, k, 1))
1554
			continue;
1555
		usable_erasefunctions--;
1556 1557
		ret = walk_eraseregions(flash, k, &erase_and_write_block_helper,
					curcontents, newcontents);
1558 1559 1560
		/* If everything is OK, don't try another erase function. */
		if (!ret)
			break;
1561
		/* Write/erase failed, so try to find out what the current chip
1562 1563
		 * contents are. If no usable erase functions remain, we can
		 * skip this: the next iteration will break immediately anyway.
1564
		 */
1565 1566
		if (!usable_erasefunctions)
			continue;
1567 1568 1569 1570
		/* Reading the whole chip may take a while, inform the user even
		 * in non-verbose mode.
		 */
		msg_cinfo("Reading current flash chip contents... ");
1571 1572
		if (flash->read(flash, curcontents, 0, size)) {
			/* Now we are truly screwed. Read failed as well. */
1573
			msg_cerr("Can't read anymore! Aborting.\n");
1574 1575 1576 1577 1578
			/* We have no idea about the flash chip contents, so
			 * retrying with another erase function is pointless.
			 */
			break;
		}
1579
		msg_cinfo("done. ");
1580
	}
1581 1582
	/* Free the scratchpad. */
	free(curcontents);
1583

1584
	if (ret) {
1585
		msg_cerr("FAILED!\n");
1586
	} else {
1587
		msg_cinfo("Erase/write done.\n");
1588 1589
	}
	return ret;
1590 1591
}

1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
void nonfatal_help_message(void)
{
	msg_gerr("Writing to the flash chip apparently didn't do anything.\n"
		"This means we have to add special support for your board, "
		  "programmer or flash chip.\n"
		"Please report this on IRC at irc.freenode.net (channel "
		  "#flashrom) or\n"
		"mail flashrom@flashrom.org!\n"
		"-------------------------------------------------------------"
		  "------------------\n"
		"You may now reboot or simply leave the machine running.\n");
}

1605
void emergency_help_message(void)
1606
{
1607
	msg_gerr("Your flash chip is in an unknown state.\n"
1608
		"Get help on IRC at irc.freenode.net (channel #flashrom) or\n"
1609 1610
		"mail flashrom@flashrom.org with FAILED: your board name in "
		  "the subject line!\n"
1611 1612
		"-------------------------------------------------------------"
		  "------------------\n"
1613 1614 1615
		"DO NOT REBOOT OR POWEROFF!\n");
}

1616
/* The way to go if you want a delimited list of programmers */
1617
void list_programmers(const char *delim)
1618 1619 1620
{
	enum programmer p;
	for (p = 0; p < PROGRAMMER_INVALID; p++) {
1621
		msg_ginfo("%s", programmer_table[p].name);
1622
		if (p < PROGRAMMER_INVALID - 1)
1623
			msg_ginfo("%s", delim);
1624
	}
1625
	msg_ginfo("\n");	
1626 1627
}

1628 1629 1630
void list_programmers_linebreak(int startcol, int cols, int paren)
{
	const char *pname;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1631 1632
	int pnamelen;
	int remaining = 0, firstline = 1;
1633
	enum programmer p;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1634
	int i;
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667

	for (p = 0; p < PROGRAMMER_INVALID; p++) {
		pname = programmer_table[p].name;
		pnamelen = strlen(pname);
		if (remaining - pnamelen - 2 < 0) {
			if (firstline)
				firstline = 0;
			else
				printf("\n");
			for (i = 0; i < startcol; i++)
				printf(" ");
			remaining = cols - startcol;
		} else {
			printf(" ");
			remaining--;
		}
		if (paren && (p == 0)) {
			printf("(");
			remaining--;
		}
		printf("%s", pname);
		remaining -= pnamelen;
		if (p < PROGRAMMER_INVALID - 1) {
			printf(",");
			remaining--;
		} else {
			if (paren)
				printf(")");
			printf("\n");
		}
	}
}

1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
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__
1688 1689 1690 1691 1692 1693
	msg_ginfo(" LLVM Clang");
#ifdef __clang_version__
	msg_ginfo(" %s,", __clang_version__);
#else
	msg_ginfo(" unknown version (before r102686),");
#endif
1694 1695 1696
#elif defined(__GNUC__)
	msg_ginfo(" GCC");
#ifdef __VERSION__
1697 1698 1699 1700
	msg_ginfo(" %s,", __VERSION__);
#else
	msg_ginfo(" unknown version,");
#endif
1701
#else
1702
	msg_ginfo(" unknown compiler,");
1703
#endif
1704 1705
#if defined (__FLASHROM_LITTLE_ENDIAN__)
	msg_ginfo(" little endian");
1706
#else
1707
	msg_ginfo(" big endian");
1708 1709 1710 1711
#endif
	msg_ginfo("\n");
}

1712 1713
void print_version(void)
{
1714
	msg_ginfo("flashrom v%s", flashrom_version);
1715
	print_sysinfo();
1716 1717
}

1718 1719 1720
void print_banner(void)
{
	msg_ginfo("flashrom is free software, get the source code at "
1721
		  "http://www.flashrom.org\n");
1722 1723 1724
	msg_ginfo("\n");
}

1725 1726
int selfcheck(void)
{
1727
	int ret = 0;
1728
	const struct flashchip *flash;
1729 1730 1731 1732

	/* Safety check. Instead of aborting after the first error, check
	 * if more errors exist.
	 */
1733
	if (ARRAY_SIZE(programmer_table) - 1 != PROGRAMMER_INVALID) {
1734
		msg_gerr("Programmer table miscompilation!\n");
1735
		ret = 1;
1736
	}
1737
	/* It would be favorable if we could also check for correct termination
1738
	 * of the following arrays, but we don't know their sizes in here...
1739 1740 1741 1742 1743 1744 1745
	 * For 'flashchips' we check the first element to be non-null. In the
	 * other cases there exist use cases where the first element can be
	 * null. */
	if (flashchips == NULL || flashchips[0].vendor == NULL) {
		msg_gerr("Flashchips table miscompilation!\n");
		ret = 1;
	}
1746 1747 1748
	for (flash = flashchips; flash && flash->name; flash++)
		if (selfcheck_eraseblocks(flash))
			ret = 1;
1749 1750 1751 1752 1753 1754

#if CONFIG_INTERNAL == 1
	if (chipset_enables == NULL) {
		msg_gerr("Chipset enables table does not exist!\n");
		ret = 1;
	}
1755
	if (board_matches == NULL) {
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
		msg_gerr("Board enables table does not exist!\n");
		ret = 1;
	}
	if (boards_known == NULL) {
		msg_gerr("Known boards table does not exist!\n");
		ret = 1;
	}
	if (laptops_known == NULL) {
		msg_gerr("Known laptops table does not exist!\n");
		ret = 1;
	}
1767
#endif
1768
	return ret;
1769 1770
}

1771
void check_chip_supported(const struct flashchip *flash)
1772 1773
{
	if (TEST_OK_MASK != (flash->tested & TEST_OK_MASK)) {
1774
		msg_cinfo("===\n");
1775
		if (flash->tested & TEST_BAD_MASK) {
1776
			msg_cinfo("This flash part has status NOT WORKING for operations:");
1777
			if (flash->tested & TEST_BAD_PROBE)
1778
				msg_cinfo(" PROBE");
1779
			if (flash->tested & TEST_BAD_READ)
1780
				msg_cinfo(" READ");
1781
			if (flash->tested & TEST_BAD_ERASE)
1782
				msg_cinfo(" ERASE");
1783
			if (flash->tested & TEST_BAD_WRITE)
1784 1785
				msg_cinfo(" WRITE");
			msg_cinfo("\n");
1786 1787 1788 1789 1790
		}
		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))) {
1791
			msg_cinfo("This flash part has status UNTESTED for operations:");
1792
			if (!(flash->tested & TEST_BAD_PROBE) && !(flash->tested & TEST_OK_PROBE))
1793
				msg_cinfo(" PROBE");
1794
			if (!(flash->tested & TEST_BAD_READ) && !(flash->tested & TEST_OK_READ))
1795
				msg_cinfo(" READ");
1796
			if (!(flash->tested & TEST_BAD_ERASE) && !(flash->tested & TEST_OK_ERASE))
1797
				msg_cinfo(" ERASE");
1798
			if (!(flash->tested & TEST_BAD_WRITE) && !(flash->tested & TEST_OK_WRITE))
1799 1800
				msg_cinfo(" WRITE");
			msg_cinfo("\n");
1801
		}
1802
		/* FIXME: This message is designed towards CLI users. */
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
		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"
1815 1816
			  "Please mention your board in the subject line. "
			    "Thanks for your help!\n");
1817 1818 1819
	}
}

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1820 1821
/* FIXME: This function signature needs to be improved once doit() has a better
 * function signature.
1822
 */
1823
int chip_safety_check(struct flashchip *flash, int force, int read_it, int write_it, int erase_it, int verify_it)
1824
{
1825 1826 1827 1828 1829 1830
	if (!programmer_may_write && (write_it || erase_it)) {
		msg_perr("Write/erase is not working yet on your programmer in "
			 "its current configuration.\n");
		/* --force is the wrong approach, but it's the best we can do
		 * until the generic programmer parameter parser is merged.
		 */
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1831
		if (!force)
1832
			return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1833
		msg_cerr("Continuing anyway.\n");
1834 1835
	}

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1836 1837 1838 1839 1840
	if (read_it || erase_it || write_it || verify_it) {
		/* Everything needs read. */
		if (flash->tested & TEST_BAD_READ) {
			msg_cerr("Read is not working on this chip. ");
			if (!force)
1841
				return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1842
			msg_cerr("Continuing anyway.\n");
1843
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1844 1845 1846
		if (!flash->read) {
			msg_cerr("flashrom has no read function for this "
				 "flash chip.\n");
1847
			return 1;
1848
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1849 1850 1851
	}
	if (erase_it || write_it) {
		/* Write needs erase. */
1852
		if (flash->tested & TEST_BAD_ERASE) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1853 1854
			msg_cerr("Erase is not working on this chip. ");
			if (!force)
1855
				return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1856
			msg_cerr("Continuing anyway.\n");
1857
		}
1858
		if(count_usable_erasers(flash) == 0) {
1859 1860 1861 1862
			msg_cerr("flashrom has no erase function for this "
				 "flash chip.\n");
			return 1;
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1863 1864
	}
	if (write_it) {
1865
		if (flash->tested & TEST_BAD_WRITE) {
1866
			msg_cerr("Write is not working on this chip. ");
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1867
			if (!force)
1868
				return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1869
			msg_cerr("Continuing anyway.\n");
1870
		}
1871
		if (!flash->write) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1872 1873
			msg_cerr("flashrom has no write function for this "
				 "flash chip.\n");
1874 1875
			return 1;
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1876 1877 1878 1879 1880 1881 1882 1883
	}
	return 0;
}

/* This function signature is horrible. We need to design a better interface,
 * but right now it allows us to split off the CLI code.
 * Besides that, the function itself is a textbook example of abysmal code flow.
 */
1884
int doit(struct flashchip *flash, int force, const char *filename, int read_it, int write_it, int erase_it, int verify_it)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1885
{
1886 1887
	uint8_t *oldcontents;
	uint8_t *newcontents;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1888
	int ret = 0;
1889
	unsigned long size = flash->total_size * 1024;
1890

1891
	if (chip_safety_check(flash, force, read_it, write_it, erase_it, verify_it)) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1892
		msg_cerr("Aborting.\n");
1893 1894
		ret = 1;
		goto out_nofree;
1895 1896
	}

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1897 1898 1899 1900 1901 1902 1903 1904
	/* Given the existence of read locks, we want to unlock for read,
	 * erase and write.
	 */
	if (flash->unlock)
		flash->unlock(flash);

	if (read_it) {
		ret = read_flash_to_file(flash, filename);
1905
		goto out_nofree;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1906
	}
1907

1908 1909 1910 1911 1912
	oldcontents = malloc(size);
	if (!oldcontents) {
		msg_gerr("Out of memory!\n");
		exit(1);
	}
1913 1914
	/* Assume worst case: All bits are 0. */
	memset(oldcontents, 0x00, size);
1915 1916 1917 1918 1919
	newcontents = malloc(size);
	if (!newcontents) {
		msg_gerr("Out of memory!\n");
		exit(1);
	}
1920 1921 1922 1923 1924 1925 1926 1927
	/* Assume best case: All bits should be 1. */
	memset(newcontents, 0xff, size);
	/* Side effect of the assumptions above: Default write action is erase
	 * because newcontents looks like a completely erased chip, and
	 * oldcontents being completely 0x00 means we have to erase everything
	 * before we can write.
	 */

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1928
	if (erase_it) {
1929 1930 1931 1932 1933 1934
		/* FIXME: Do we really want the scary warning if erase failed?
		 * After all, after erase the chip is either blank or partially
		 * blank or it has the old contents. A blank chip won't boot,
		 * so if the user wanted erase and reboots afterwards, the user
		 * knows very well that booting won't work.
		 */
1935
		if (erase_and_write_flash(flash, oldcontents, newcontents)) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1936
			emergency_help_message();
1937
			ret = 1;
1938
		}
1939
		goto out;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1940 1941 1942
	}

	if (write_it || verify_it) {
1943
		if (read_buf_from_file(newcontents, size, filename)) {
1944 1945
			ret = 1;
			goto out;
1946 1947
		}

1948
#if CONFIG_INTERNAL == 1
1949 1950
		if (programmer == PROGRAMMER_INTERNAL)
			show_id(newcontents, size, force);
1951
#endif
1952
	}
Ronald G. Minnich's avatar
Ronald G. Minnich committed
1953

1954 1955 1956 1957 1958 1959
	/* Read the whole chip to be able to check whether regions need to be
	 * erased and to give better diagnostics in case write fails.
	 * The alternative would be to read only the regions which are to be
	 * preserved, but in that case we might perform unneeded erase which
	 * takes time as well.
	 */
1960
	msg_cinfo("Reading old flash chip contents... ");
1961
	if (flash->read(flash, oldcontents, 0, size)) {
1962
		ret = 1;
1963
		msg_cinfo("FAILED.\n");
1964
		goto out;
1965
	}
1966
	msg_cinfo("done.\n");
1967

1968 1969
	// This should be moved into each flash part's code to do it 
	// cleanly. This does the job.
1970
	handle_romentries(flash, oldcontents, newcontents);
1971

1972
	// ////////////////////////////////////////////////////////////
1973

1974
	if (write_it) {
1975 1976 1977
		if (erase_and_write_flash(flash, oldcontents, newcontents)) {
			msg_cerr("Uh oh. Erase/write failed. Checking if "
				 "anything changed.\n");
1978 1979 1980 1981 1982
			if (!flash->read(flash, newcontents, 0, size)) {
				if (!memcmp(oldcontents, newcontents, size)) {
					msg_cinfo("Good. It seems nothing was "
						  "changed.\n");
					nonfatal_help_message();
1983 1984
					ret = 1;
					goto out;
1985 1986
				}
			}
1987
			emergency_help_message();
1988 1989
			ret = 1;
			goto out;
1990 1991
		}
	}
1992

1993 1994 1995 1996
	if (verify_it) {
		/* Work around chips which need some time to calm down. */
		if (write_it)
			programmer_delay(1000*1000);
1997
		ret = verify_flash(flash, newcontents);
1998
		/* If we tried to write, and verification now fails, we
1999 2000 2001 2002 2003
		 * might have an emergency situation.
		 */
		if (ret && write_it)
			emergency_help_message();
	}
2004

2005 2006 2007 2008
out:
	free(oldcontents);
	free(newcontents);
out_nofree:
2009
	programmer_shutdown();
Stefan Reinauer's avatar
Stefan Reinauer committed
2010
	return ret;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
2011
}