buspirate_spi.c 15.3 KB
Newer Older
1 2 3
/*
 * This file is part of the flashrom project.
 *
4
 * Copyright (C) 2009, 2010, 2011, 2012 Carl-Daniel Hailfinger
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * 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; version 2 of the License.
 *
 * 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.
 *
 * 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
 */

#include <stdio.h>
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
21
#include <strings.h>
22 23 24
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
25
#include <unistd.h>
26
#include "flash.h"
27
#include "programmer.h"
28 29 30 31 32
#include "spi.h"

/* Change this to #define if you want to test without a serial implementation */
#undef FAKE_COMMUNICATION

33 34 35 36 37
struct buspirate_spispeeds {
	const char *name;
	const int speed;
};

38
#ifndef FAKE_COMMUNICATION
39
static int buspirate_serialport_setup(char *dev)
40 41 42
{
	/* 115200bps, 8 databits, no parity, 1 stopbit */
	sp_fd = sp_openserport(dev, 115200);
43
 	if (sp_fd == SER_INV_FD)
Niklas Söderlund's avatar
Niklas Söderlund committed
44
		return 1;
45 46 47 48
	return 0;
}
#else
#define buspirate_serialport_setup(...) 0
49
#define serialport_shutdown(...) 0
50 51
#define serialport_write(...) 0
#define serialport_read(...) 0
Patrick Georgi's avatar
Patrick Georgi committed
52
#define sp_flush_incoming(...) 0
53 54
#endif

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
static unsigned char *bp_commbuf = NULL;
static int bp_commbufsize = 0;

static int buspirate_commbuf_grow(int bufsize)
{
	unsigned char *tmpbuf;

	/* Never shrink. realloc() calls are expensive. */
	if (bufsize <= bp_commbufsize)
		return 0;

	tmpbuf = realloc(bp_commbuf, bufsize);
	if (!tmpbuf) {
		/* Keep the existing buffer because memory is already tight. */
		msg_perr("Out of memory!\n");
		return ERROR_OOM;
	}

	bp_commbuf = tmpbuf;
	bp_commbufsize = bufsize;
	return 0;
}

78 79
static int buspirate_sendrecv(unsigned char *buf, unsigned int writecnt,
			      unsigned int readcnt)
80 81 82
{
	int i, ret = 0;

83
	msg_pspew("%s: write %i, read %i ", __func__, writecnt, readcnt);
84
	if (!writecnt && !readcnt) {
85
		msg_perr("Zero length command!\n");
86 87
		return 1;
	}
88 89
	if (writecnt)
		msg_pspew("Sending");
90
	for (i = 0; i < writecnt; i++)
91
		msg_pspew(" 0x%02x", buf[i]);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
#ifdef FAKE_COMMUNICATION
	/* Placate the caller for now. */
	if (readcnt) {
		buf[0] = 0x01;
		memset(buf + 1, 0xff, readcnt - 1);
	}
	ret = 0;
#else
	if (writecnt)
		ret = serialport_write(buf, writecnt);
	if (ret)
		return ret;
	if (readcnt)
		ret = serialport_read(buf, readcnt);
	if (ret)
		return ret;
#endif
109 110
	if (readcnt)
		msg_pspew(", receiving");
111
	for (i = 0; i < readcnt; i++)
112 113
		msg_pspew(" 0x%02x", buf[i]);
	msg_pspew("\n");
114 115 116
	return 0;
}

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
static int buspirate_wait_for_string(unsigned char *buf, char *key)
{
	unsigned int keylen = strlen(key);
	int ret;

	ret = buspirate_sendrecv(buf, 0, keylen);
	while (!ret) {
		if (!memcmp(buf, key, keylen))
			return 0;
		memmove(buf, buf + 1, keylen - 1);
		ret = buspirate_sendrecv(buf + keylen - 1, 0, 1);
	}
	return ret;
}

132 133 134 135
static int buspirate_spi_send_command_v1(struct flashctx *flash, unsigned int writecnt, unsigned int readcnt,
					 const unsigned char *writearr, unsigned char *readarr);
static int buspirate_spi_send_command_v2(struct flashctx *flash, unsigned int writecnt, unsigned int readcnt,
					 const unsigned char *writearr, unsigned char *readarr);
136

137
static struct spi_master spi_master_buspirate = {
138
	.type		= SPI_CONTROLLER_BUSPIRATE,
139 140 141
	.max_data_read	= MAX_DATA_UNSPECIFIED,
	.max_data_write	= MAX_DATA_UNSPECIFIED,
	.command	= NULL,
142 143 144
	.multicommand	= default_spi_send_multicommand,
	.read		= default_spi_read,
	.write_256	= default_spi_write_256,
145
	.write_aai	= default_spi_write_aai,
146 147
};

148 149 150 151 152 153 154 155 156
static const struct buspirate_spispeeds spispeeds[] = {
	{"30k",		0x0},
	{"125k",	0x1},
	{"250k",	0x2},
	{"1M",		0x3},
	{"2M",		0x4},
	{"2.6M",	0x5},
	{"4M",		0x6},
	{"8M",		0x7},
157
	{NULL,		0x0},
158 159
};

160 161
static int buspirate_spi_shutdown(void *data)
{
162 163
	int ret = 0, ret2 = 0;
	/* No need to allocate a buffer here, we know that bp_commbuf is at least DEFAULT_BUFSIZE big. */
164 165

	/* Exit raw SPI mode (enter raw bitbang mode) */
166
	bp_commbuf[0] = 0x00;
167
	if ((ret = buspirate_sendrecv(bp_commbuf, 1, 0)))
168
		goto out_shutdown;
169
	if ((ret = buspirate_wait_for_string(bp_commbuf, "BBIO")))
170
		goto out_shutdown;
171 172 173 174 175
	if ((ret = buspirate_sendrecv(bp_commbuf, 0, 1)))
		goto out_shutdown;
	msg_pdbg("Raw bitbang mode version %c\n", bp_commbuf[0]);
	if (bp_commbuf[0] != '1') {
		msg_perr("Can't handle raw bitbang mode version %c!\n", bp_commbuf[0]);
176 177
		ret = 1;
		goto out_shutdown;
178 179
	}
	/* Reset Bus Pirate (return to user terminal) */
180 181
	bp_commbuf[0] = 0x0f;
	ret = buspirate_sendrecv(bp_commbuf, 1, 0);
182

183
out_shutdown:
184
	/* Shut down serial port communication */
185 186 187 188 189 190 191
	ret2 = serialport_shutdown(NULL);
	/* Keep the oldest error, it is probably the best indicator. */
	if (ret2 && !ret)
		ret = ret2;
	bp_commbufsize = 0;
	free(bp_commbuf);
	bp_commbuf = NULL;
192
	if (ret)
193 194 195
		msg_pdbg("Bus Pirate shutdown failed.\n");
	else
		msg_pdbg("Bus Pirate shutdown completed.\n");
196

197
	return ret;
198 199
}

200 201
#define BP_FWVERSION(a,b)	((a) << 8 | (b))

202 203
int buspirate_spi_init(void)
{
204
	char *tmp;
205 206
	char *dev;
	int i;
207 208
	unsigned int fw_version_major = 0;
	unsigned int fw_version_minor = 0;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
209 210
	int spispeed = 0x7;
	int ret = 0;
211
	int pullup = 0;
212

213
	dev = extract_programmer_param("dev");
214 215 216 217 218 219
	if (dev && !strlen(dev)) {
		free(dev);
		dev = NULL;
	}
	if (!dev) {
		msg_perr("No serial device given. Use flashrom -p buspirate_spi:dev=/dev/ttyUSB0\n");
220 221
		return 1;
	}
222

223 224 225 226
	tmp = extract_programmer_param("spispeed");
	if (tmp) {
		for (i = 0; spispeeds[i].name; i++) {
			if (!strncasecmp(spispeeds[i].name, tmp, strlen(spispeeds[i].name))) {
227 228 229
				spispeed = spispeeds[i].speed;
				break;
			}
230
		}
231
		if (!spispeeds[i].name)
232
			msg_perr("Invalid SPI speed, using default.\n");
233
	}
234 235 236 237 238 239 240 241 242 243 244 245
	free(tmp);

	tmp = extract_programmer_param("pullups");
	if (tmp) {
		if (strcasecmp("on", tmp) == 0)
			pullup = 1;
		else if (strcasecmp("off", tmp) == 0)
			; // ignore
		else
			msg_perr("Invalid pullups state, not using them.\n");
	}
	free(tmp);
246

247 248 249 250 251 252
	/* Default buffer size is 19: 16 bytes data, 3 bytes control. */
#define DEFAULT_BUFSIZE (16 + 3)
	bp_commbuf = malloc(DEFAULT_BUFSIZE);
	if (!bp_commbuf) {
		bp_commbufsize = 0;
		msg_perr("Out of memory!\n");
253
		free(dev);
254 255 256 257
		return ERROR_OOM;
	}
	bp_commbufsize = DEFAULT_BUFSIZE;

258
	ret = buspirate_serialport_setup(dev);
259
	free(dev);
260 261 262 263 264 265
	if (ret) {
		bp_commbufsize = 0;
		free(bp_commbuf);
		bp_commbuf = NULL;
		return ret;
	}
266

267 268 269 270
	if (register_shutdown(buspirate_spi_shutdown, NULL) != 0) {
		bp_commbufsize = 0;
		free(bp_commbuf);
		bp_commbuf = NULL;
271
		return 1;
272
	}
273

274 275 276 277 278
	/* This is the brute force version, but it should work.
	 * It is likely to fail if a previous flashrom run was aborted during a write with the new SPI commands
	 * in firmware v5.5 because that firmware may wait for up to 4096 bytes of input before responding to
	 * 0x00 again. The obvious workaround (sending 4096 bytes of \0) may cause significant startup delays.
	 */
279
	for (i = 0; i < 20; i++) {
280
		/* Enter raw bitbang mode */
281
		bp_commbuf[0] = 0x00;
282
		/* Send the command, don't read the response. */
283
		ret = buspirate_sendrecv(bp_commbuf, 1, 0);
284 285
		if (ret)
			return ret;
286 287 288 289 290 291 292 293
		/* The old way to handle responses from a Bus Pirate already in BBIO mode was to flush any
		 * response which came in over serial. Unfortunately that does not work reliably on Linux
		 * with FTDI USB-serial.
		 */
		//sp_flush_incoming();
		/* The Bus Pirate can't handle UART input buffer overflow in BBIO mode, and sending a sequence
		 * of 0x00 too fast apparently triggers such an UART input buffer overflow.
		 */
294
		internal_sleep(10000);
295
	}
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
	/* We know that 20 commands of \0 should elicit at least one BBIO1 response. */
	if ((ret = buspirate_wait_for_string(bp_commbuf, "BBIO")))
		return ret;

	/* Reset the Bus Pirate. */
	bp_commbuf[0] = 0x0f;
	/* Send the command, don't read the response. */
	if ((ret = buspirate_sendrecv(bp_commbuf, 1, 0)))
		return ret;
	if ((ret = buspirate_wait_for_string(bp_commbuf, "irate ")))
		return ret;
	/* Read the hardware version string. Last byte of the buffer is reserved for \0. */
	for (i = 0; i < DEFAULT_BUFSIZE - 1; i++) {
		if ((ret = buspirate_sendrecv(bp_commbuf + i, 0, 1)))
			return ret;
		if (strchr("\r\n\t ", bp_commbuf[i]))
			break;
313
	}
314 315 316 317
	bp_commbuf[i] = '\0';
	msg_pdbg("Detected Bus Pirate hardware %s\n", bp_commbuf);

	if ((ret = buspirate_wait_for_string(bp_commbuf, "irmware ")))
318
		return ret;
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
	/* Read the firmware version string. Last byte of the buffer is reserved for \0. */
	for (i = 0; i < DEFAULT_BUFSIZE - 1; i++) {
		if ((ret = buspirate_sendrecv(bp_commbuf + i, 0, 1)))
			return ret;
		if (strchr("\r\n\t ", bp_commbuf[i]))
			break;
	}
	bp_commbuf[i] = '\0';
	msg_pdbg("Detected Bus Pirate firmware ");
	if (bp_commbuf[0] != 'v')
		msg_pdbg("(unknown version number format)");
	else if (!strchr("0123456789", bp_commbuf[1]))
		msg_pdbg("(unknown version number format)");
	else {
		fw_version_major = strtoul((char *)bp_commbuf + 1, &tmp, 10);
		while ((*tmp != '\0') && !strchr("0123456789", *tmp))
			tmp++;
		fw_version_minor = strtoul(tmp, NULL, 10);
		msg_pdbg("%u.%u", fw_version_major, fw_version_minor);
	}
	msg_pdbg2(" (\"%s\")", bp_commbuf);
	msg_pdbg("\n");

	if ((ret = buspirate_wait_for_string(bp_commbuf, "HiZ>")))
		return ret;
	
	/* Tell the user about missing SPI binary mode in firmware 2.3 and older. */
	if (BP_FWVERSION(fw_version_major, fw_version_minor) < BP_FWVERSION(2, 4)) {
		msg_pinfo("Bus Pirate firmware 2.3 and older does not support binary SPI access.\n");
		msg_pinfo("Please upgrade to the latest firmware (at least 2.4).\n");
		return SPI_PROGRAMMER_ERROR;
	}

352 353 354 355 356 357
	/* Use fast SPI mode in firmware 5.5 and newer. */
	if (BP_FWVERSION(fw_version_major, fw_version_minor) >= BP_FWVERSION(5, 5)) {
		msg_pdbg("Using SPI command set v2.\n"); 
		/* Sensible default buffer size. */
		if (buspirate_commbuf_grow(260 + 5))
			return ERROR_OOM;
358 359 360
		spi_master_buspirate.max_data_read = 2048;
		spi_master_buspirate.max_data_write = 256;
		spi_master_buspirate.command = buspirate_spi_send_command_v2;
361 362 363 364 365 366 367
	} else {
		msg_pinfo("Bus Pirate firmware 5.4 and older does not support fast SPI access.\n");
		msg_pinfo("Reading/writing a flash chip may take hours.\n");
		msg_pinfo("It is recommended to upgrade to firmware 5.5 or newer.\n");
		/* Sensible default buffer size. */
		if (buspirate_commbuf_grow(16 + 3))
			return ERROR_OOM;
368 369 370
		spi_master_buspirate.max_data_read = 12;
		spi_master_buspirate.max_data_write = 12;
		spi_master_buspirate.command = buspirate_spi_send_command_v1;
371 372
	}

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
	/* Workaround for broken speed settings in firmware 6.1 and older. */
	if (BP_FWVERSION(fw_version_major, fw_version_minor) < BP_FWVERSION(6, 2))
		if (spispeed > 0x4) {
			msg_perr("Bus Pirate firmware 6.1 and older does not support SPI speeds above 2 MHz. "
				 "Limiting speed to 2 MHz.\n");
			msg_pinfo("It is recommended to upgrade to firmware 6.2 or newer.\n");
			spispeed = 0x4;
		}
		
	/* This works because speeds numbering starts at 0 and is contiguous. */
	msg_pdbg("SPI speed is %sHz\n", spispeeds[spispeed].name);

	/* Enter raw bitbang mode */
	for (i = 0; i < 20; i++) {
		bp_commbuf[0] = 0x00;
		if ((ret = buspirate_sendrecv(bp_commbuf, 1, 0)))
			return ret;
390
	}
391 392 393 394 395 396 397
	if ((ret = buspirate_wait_for_string(bp_commbuf, "BBIO")))
		return ret;
	if ((ret = buspirate_sendrecv(bp_commbuf, 0, 1)))
		return ret;
	msg_pdbg("Raw bitbang mode version %c\n", bp_commbuf[0]);
	if (bp_commbuf[0] != '1') {
		msg_perr("Can't handle raw bitbang mode version %c!\n", bp_commbuf[0]);
398 399 400
		return 1;
	}
	/* Enter raw SPI mode */
401
	bp_commbuf[0] = 0x01;
402 403
	ret = buspirate_sendrecv(bp_commbuf, 1, 0);
	if ((ret = buspirate_wait_for_string(bp_commbuf, "SPI")))
404
		return ret;
405 406 407 408 409
	if ((ret = buspirate_sendrecv(bp_commbuf, 0, 1)))
		return ret;
	msg_pdbg("Raw SPI mode version %c\n", bp_commbuf[0]);
	if (bp_commbuf[0] != '1') {
		msg_perr("Can't handle raw SPI mode version %c!\n", bp_commbuf[0]);
410 411 412 413
		return 1;
	}

	/* Initial setup (SPI peripherals config): Enable power, CS high, AUX */
414 415 416 417 418
	bp_commbuf[0] = 0x40 | 0x0b;
	if (pullup == 1) {
		bp_commbuf[0] |= (1 << 2);
		msg_pdbg("Enabling pull-up resistors.\n");
	}
419
	ret = buspirate_sendrecv(bp_commbuf, 1, 1);
420 421
	if (ret)
		return 1;
422
	if (bp_commbuf[0] != 0x01) {
423
		msg_perr("Protocol error while setting power/CS/AUX(/Pull-up resistors)!\n");
424 425 426
		return 1;
	}

427
	/* Set SPI speed */
428 429
	bp_commbuf[0] = 0x60 | spispeed;
	ret = buspirate_sendrecv(bp_commbuf, 1, 1);
430 431
	if (ret)
		return 1;
432
	if (bp_commbuf[0] != 0x01) {
433
		msg_perr("Protocol error while setting SPI speed!\n");
434 435 436 437
		return 1;
	}
	
	/* Set SPI config: output type, idle, clock edge, sample */
438 439
	bp_commbuf[0] = 0x80 | 0xa;
	ret = buspirate_sendrecv(bp_commbuf, 1, 1);
440 441
	if (ret)
		return 1;
442
	if (bp_commbuf[0] != 0x01) {
443
		msg_perr("Protocol error while setting SPI config!\n");
444 445 446 447
		return 1;
	}

	/* De-assert CS# */
448 449
	bp_commbuf[0] = 0x03;
	ret = buspirate_sendrecv(bp_commbuf, 1, 1);
450 451
	if (ret)
		return 1;
452
	if (bp_commbuf[0] != 0x01) {
453
		msg_perr("Protocol error while raising CS#!\n");
454 455 456
		return 1;
	}

457
	register_spi_master(&spi_master_buspirate);
458 459 460 461

	return 0;
}

462 463
static int buspirate_spi_send_command_v1(struct flashctx *flash, unsigned int writecnt, unsigned int readcnt,
					 const unsigned char *writearr, unsigned char *readarr)
464
{
465 466
	unsigned int i = 0;
	int ret = 0;
467 468 469 470

	if (writecnt > 16 || readcnt > 16 || (readcnt + writecnt) > 16)
		return SPI_INVALID_LENGTH;

471
	/* 3 bytes extra for CS#, len, CS#. */
472 473
	if (buspirate_commbuf_grow(writecnt + readcnt + 3))
		return ERROR_OOM;
474 475

	/* Assert CS# */
476
	bp_commbuf[i++] = 0x02;
477

478 479
	bp_commbuf[i++] = 0x10 | (writecnt + readcnt - 1);
	memcpy(bp_commbuf + i, writearr, writecnt);
480
	i += writecnt;
481
	memset(bp_commbuf + i, 0, readcnt);
482 483 484

	i += readcnt;
	/* De-assert CS# */
485
	bp_commbuf[i++] = 0x03;
486

487
	ret = buspirate_sendrecv(bp_commbuf, i, i);
488 489 490

	if (ret) {
		msg_perr("Bus Pirate communication error!\n");
491
		return SPI_GENERIC_ERROR;
492 493
	}

494
	if (bp_commbuf[0] != 0x01) {
495
		msg_perr("Protocol error while lowering CS#!\n");
496 497 498
		return SPI_GENERIC_ERROR;
	}

499
	if (bp_commbuf[1] != 0x01) {
500
		msg_perr("Protocol error while reading/writing SPI!\n");
501
		return SPI_GENERIC_ERROR;
502 503
	}

504
	if (bp_commbuf[i - 1] != 0x01) {
505
		msg_perr("Protocol error while raising CS#!\n");
506 507 508
		return SPI_GENERIC_ERROR;
	}

509
	/* Skip CS#, length, writearr. */
510
	memcpy(readarr, bp_commbuf + 2 + writecnt, readcnt);
511

512 513
	return ret;
}
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553

static int buspirate_spi_send_command_v2(struct flashctx *flash, unsigned int writecnt, unsigned int readcnt,
					 const unsigned char *writearr, unsigned char *readarr)
{
	int i = 0, ret = 0;

	if (writecnt > 4096 || readcnt > 4096 || (readcnt + writecnt) > 4096)
		return SPI_INVALID_LENGTH;

	/* 5 bytes extra for command, writelen, readlen.
	 * 1 byte extra for Ack/Nack.
	 */
	if (buspirate_commbuf_grow(max(writecnt + 5, readcnt + 1)))
		return ERROR_OOM;

	/* Combined SPI write/read. */
	bp_commbuf[i++] = 0x04;
	bp_commbuf[i++] = (writecnt >> 8) & 0xff;
	bp_commbuf[i++] = writecnt & 0xff;
	bp_commbuf[i++] = (readcnt >> 8) & 0xff;
	bp_commbuf[i++] = readcnt & 0xff;
	memcpy(bp_commbuf + i, writearr, writecnt);
	
	ret = buspirate_sendrecv(bp_commbuf, i + writecnt, 1 + readcnt);

	if (ret) {
		msg_perr("Bus Pirate communication error!\n");
		return SPI_GENERIC_ERROR;
	}

	if (bp_commbuf[0] != 0x01) {
		msg_perr("Protocol error while sending SPI write/read!\n");
		return SPI_GENERIC_ERROR;
	}

	/* Skip Ack. */
	memcpy(readarr, bp_commbuf + 1, readcnt);

	return ret;
}