1 /*
2  * This file is part of the flashrom project.
3  *
4  * Copyright (C) 2010 Carl-Daniel Hailfinger
5  * Copyright (C) 2015 Simon Glass
6  * Copyright (C) 2015 Stefan Tauner
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  */
17 
18 #include "platform.h"
19 
20 #include <sys/types.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <limits.h>
25 #include <errno.h>
26 #include <libusb.h>
27 #include "flash.h"
28 #include "chipdrivers.h"
29 #include "programmer.h"
30 #include "spi.h"
31 
32 /* LIBUSB_CALL ensures the right calling conventions on libusb callbacks.
33  * However, the macro is not defined everywhere. m(
34  */
35 #ifndef LIBUSB_CALL
36 #define LIBUSB_CALL
37 #endif
38 
39 #define FIRMWARE_VERSION(x,y,z) ((x << 16) | (y << 8) | z)
40 #define DEFAULT_TIMEOUT 3000
41 #define DEDIPROG_ASYNC_TRANSFERS 8 /* at most 8 asynchronous transfers */
42 #define REQTYPE_OTHER_OUT (LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_OTHER)	/* 0x43 */
43 #define REQTYPE_OTHER_IN (LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_OTHER)	/* 0xC3 */
44 #define REQTYPE_EP_OUT (LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_ENDPOINT)	/* 0x42 */
45 #define REQTYPE_EP_IN (LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_ENDPOINT)	/* 0xC2 */
46 static struct libusb_context *usb_ctx;
47 static libusb_device_handle *dediprog_handle;
48 static int dediprog_in_endpoint;
49 static int dediprog_out_endpoint;
50 
51 enum dediprog_devtype {
52 	DEV_UNKNOWN		= 0,
53 	DEV_SF100		= 100,
54 	DEV_SF200		= 200,
55 	DEV_SF600		= 600,
56 };
57 
58 enum dediprog_leds {
59 	LED_INVALID		= -1,
60 	LED_NONE		= 0,
61 	LED_PASS		= 1 << 0,
62 	LED_BUSY		= 1 << 1,
63 	LED_ERROR		= 1 << 2,
64 	LED_ALL			= 7,
65 };
66 
67 /* IO bits for CMD_SET_IO_LED message */
68 enum dediprog_ios {
69 	IO1			= 1 << 0,
70 	IO2			= 1 << 1,
71 	IO3			= 1 << 2,
72 	IO4			= 1 << 3,
73 };
74 
75 enum dediprog_cmds {
76 	CMD_TRANSCEIVE		= 0x01,
77 	CMD_POLL_STATUS_REG	= 0x02,
78 	CMD_SET_VPP		= 0x03,
79 	CMD_SET_TARGET		= 0x04,
80 	CMD_READ_EEPROM		= 0x05,
81 	CMD_WRITE_EEPROM	= 0x06,
82 	CMD_SET_IO_LED		= 0x07,
83 	CMD_READ_PROG_INFO	= 0x08,
84 	CMD_SET_VCC		= 0x09,
85 	CMD_SET_STANDALONE	= 0x0A,
86 	CMD_SET_VOLTAGE		= 0x0B,	/* Only in firmware older than 6.0.0 */
87 	CMD_GET_BUTTON		= 0x11,
88 	CMD_GET_UID		= 0x12,
89 	CMD_SET_CS		= 0x14,
90 	CMD_IO_MODE		= 0x15,
91 	CMD_FW_UPDATE		= 0x1A,
92 	CMD_FPGA_UPDATE		= 0x1B,
93 	CMD_READ_FPGA_VERSION	= 0x1C,
94 	CMD_SET_HOLD		= 0x1D,
95 	CMD_READ		= 0x20,
96 	CMD_WRITE		= 0x30,
97 	CMD_WRITE_AT45DB	= 0x31,
98 	CMD_NAND_WRITE		= 0x32,
99 	CMD_NAND_READ		= 0x33,
100 	CMD_SET_SPI_CLK		= 0x61,
101 	CMD_CHECK_SOCKET	= 0x62,
102 	CMD_DOWNLOAD_PRJ	= 0x63,
103 	CMD_READ_PRJ_NAME	= 0x64,
104 	// New protocol/firmware only
105 	CMD_CHECK_SDCARD	= 0x65,
106 	CMD_READ_PRJ		= 0x66,
107 };
108 
109 enum dediprog_target {
110 	FLASH_TYPE_APPLICATION_FLASH_1	= 0,
111 	FLASH_TYPE_FLASH_CARD,
112 	FLASH_TYPE_APPLICATION_FLASH_2,
113 	FLASH_TYPE_SOCKET,
114 };
115 
116 enum dediprog_readmode {
117 	READ_MODE_STD			= 1,
118 	READ_MODE_FAST			= 2,
119 	READ_MODE_ATMEL45		= 3,
120 	READ_MODE_4B_ADDR_FAST		= 4,
121 	READ_MODE_4B_ADDR_FAST_0x0C	= 5, /* New protocol only */
122 };
123 
124 enum dediprog_writemode {
125 	WRITE_MODE_PAGE_PGM			= 1,
126 	WRITE_MODE_PAGE_WRITE			= 2,
127 	WRITE_MODE_1B_AAI			= 3,
128 	WRITE_MODE_2B_AAI			= 4,
129 	WRITE_MODE_128B_PAGE			= 5,
130 	WRITE_MODE_PAGE_AT26DF041		= 6,
131 	WRITE_MODE_SILICON_BLUE_FPGA		= 7,
132 	WRITE_MODE_64B_PAGE_NUMONYX_PCM		= 8,	/* unit of 512 bytes */
133 	WRITE_MODE_4B_ADDR_256B_PAGE_PGM	= 9,
134 	WRITE_MODE_32B_PAGE_PGM_MXIC_512K	= 10,	/* unit of 512 bytes */
135 	WRITE_MODE_4B_ADDR_256B_PAGE_PGM_0x12	= 11,
136 	WRITE_MODE_4B_ADDR_256B_PAGE_PGM_FLAGS	= 12,
137 };
138 
139 enum dediprog_standalone_mode {
140 	ENTER_STANDALONE_MODE = 0,
141 	LEAVE_STANDALONE_MODE = 1,
142 };
143 
144 /*
145  * These are not official designations; they are for use in flashrom only.
146  * Order must be preserved so that comparison operators work.
147  */
148 enum protocol {
149 	PROTOCOL_UNKNOWN,
150 	PROTOCOL_V1,
151 	PROTOCOL_V2,
152 	PROTOCOL_V3,
153 };
154 
155 const struct dev_entry devs_dediprog[] = {
156 	{0x0483, 0xDADA, OK, "Dediprog", "SF100/SF200/SF600"},
157 
158 	{0},
159 };
160 
161 static int dediprog_firmwareversion = FIRMWARE_VERSION(0, 0, 0);
162 static enum dediprog_devtype dediprog_devicetype = DEV_UNKNOWN;
163 
164 #if defined(LIBUSB_MAJOR) && defined(LIBUSB_MINOR) && defined(LIBUSB_MICRO) && \
165     LIBUSB_MAJOR <= 1 && LIBUSB_MINOR == 0 && LIBUSB_MICRO < 9
166 /* Quick and dirty replacement for missing libusb_error_name in libusb < 1.0.9 */
libusb_error_name(int error_code)167 const char * LIBUSB_CALL libusb_error_name(int error_code)
168 {
169 	if (error_code >= INT16_MIN && error_code <= INT16_MAX) {
170 		/* 18 chars for text, rest for number (16 b should be enough), sign, nullbyte. */
171 		static char my_libusb_error[18 + 5 + 2];
172 		sprintf(my_libusb_error, "libusb error code %i", error_code);
173 		return my_libusb_error;
174 	} else {
175 		return "UNKNOWN";
176 	}
177 }
178 #endif
179 
protocol(void)180 static enum protocol protocol(void)
181 {
182 	/* Firmware version < 5.0.0 is handled explicitly in some cases. */
183 	switch (dediprog_devicetype) {
184 	case DEV_SF100:
185 	case DEV_SF200:
186 		if (dediprog_firmwareversion < FIRMWARE_VERSION(5, 5, 0))
187 			return PROTOCOL_V1;
188 		else
189 			return PROTOCOL_V2;
190 	case DEV_SF600:
191 		if (dediprog_firmwareversion < FIRMWARE_VERSION(6, 9, 0))
192 			return PROTOCOL_V1;
193 		else if (dediprog_firmwareversion <= FIRMWARE_VERSION(7, 2, 21))
194 			return PROTOCOL_V2;
195 		else
196 			return PROTOCOL_V3;
197 	default:
198 		return PROTOCOL_UNKNOWN;
199 	}
200 }
201 
202 struct dediprog_transfer_status {
203 	int error; /* OK if 0, ERROR else */
204 	unsigned int queued_idx;
205 	unsigned int finished_idx;
206 };
207 
dediprog_bulk_read_cb(struct libusb_transfer * const transfer)208 static void LIBUSB_CALL dediprog_bulk_read_cb(struct libusb_transfer *const transfer)
209 {
210 	struct dediprog_transfer_status *const status = (struct dediprog_transfer_status *)transfer->user_data;
211 	if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
212 		status->error = 1;
213 		msg_perr("SPI bulk read failed!\n");
214 	}
215 	++status->finished_idx;
216 }
217 
dediprog_bulk_read_poll(const struct dediprog_transfer_status * const status,const int finish)218 static int dediprog_bulk_read_poll(const struct dediprog_transfer_status *const status, const int finish)
219 {
220 	if (status->finished_idx >= status->queued_idx)
221 		return 0;
222 
223 	do {
224 		struct timeval timeout = { 10, 0 };
225 		const int ret = libusb_handle_events_timeout(usb_ctx, &timeout);
226 		if (ret < 0) {
227 			msg_perr("Polling read events failed: %i %s!\n", ret, libusb_error_name(ret));
228 			return 1;
229 		}
230 	} while (finish && (status->finished_idx < status->queued_idx));
231 	return 0;
232 }
233 
dediprog_read(enum dediprog_cmds cmd,unsigned int value,unsigned int idx,uint8_t * bytes,size_t size)234 static int dediprog_read(enum dediprog_cmds cmd, unsigned int value, unsigned int idx, uint8_t *bytes, size_t size)
235 {
236 	return libusb_control_transfer(dediprog_handle, REQTYPE_EP_IN, cmd, value, idx,
237 				      (unsigned char *)bytes, size, DEFAULT_TIMEOUT);
238 }
239 
dediprog_write(enum dediprog_cmds cmd,unsigned int value,unsigned int idx,const uint8_t * bytes,size_t size)240 static int dediprog_write(enum dediprog_cmds cmd, unsigned int value, unsigned int idx, const uint8_t *bytes, size_t size)
241 {
242 	return libusb_control_transfer(dediprog_handle, REQTYPE_EP_OUT, cmd, value, idx,
243 				      (unsigned char *)bytes, size, DEFAULT_TIMEOUT);
244 }
245 
246 
247 /* This function sets the GPIOs connected to the LEDs as well as IO1-IO4. */
dediprog_set_leds(int leds)248 static int dediprog_set_leds(int leds)
249 {
250 	if (leds < LED_NONE || leds > LED_ALL)
251 		leds = LED_ALL;
252 
253 	/* Older Dediprogs with 2.x.x and 3.x.x firmware only had two LEDs, assigned to different bits. So map
254 	 * them around if we have an old device. On those devices the LEDs map as follows:
255 	 *   bit 2 == 0: green light is on.
256 	 *   bit 0 == 0: red light is on.
257 	 *
258 	 * Additionally, the command structure has changed with the "new" protocol.
259 	 *
260 	 * FIXME: take IO pins into account
261 	 */
262 	int target_leds, ret;
263 	if (protocol() >= PROTOCOL_V2) {
264 		target_leds = (leds ^ 7) << 8;
265 		ret = dediprog_write(CMD_SET_IO_LED, target_leds, 0, NULL, 0);
266 	} else {
267 		if (dediprog_firmwareversion < FIRMWARE_VERSION(5, 0, 0)) {
268 			target_leds = ((leds & LED_ERROR) >> 2) | ((leds & LED_PASS) << 2);
269 		} else {
270 			target_leds = leds;
271 		}
272 		target_leds ^= 7;
273 
274 		ret = dediprog_write(CMD_SET_IO_LED, 0x9, target_leds, NULL, 0);
275 	}
276 
277 	if (ret != 0x0) {
278 		msg_perr("Command Set LED 0x%x failed (%s)!\n", leds, libusb_error_name(ret));
279 		return 1;
280 	}
281 
282 	return 0;
283 }
284 
dediprog_set_spi_voltage(int millivolt)285 static int dediprog_set_spi_voltage(int millivolt)
286 {
287 	int ret;
288 	uint16_t voltage_selector;
289 
290 	switch (millivolt) {
291 	case 0:
292 		/* Admittedly this one is an assumption. */
293 		voltage_selector = 0x0;
294 		break;
295 	case 1800:
296 		voltage_selector = 0x12;
297 		break;
298 	case 2500:
299 		voltage_selector = 0x11;
300 		break;
301 	case 3500:
302 		voltage_selector = 0x10;
303 		break;
304 	default:
305 		msg_perr("Unknown voltage %i mV! Aborting.\n", millivolt);
306 		return 1;
307 	}
308 	msg_pdbg("Setting SPI voltage to %u.%03u V\n", millivolt / 1000,
309 		 millivolt % 1000);
310 
311 	if (voltage_selector == 0) {
312 		/* Wait some time as the original driver does. */
313 		programmer_delay(200 * 1000);
314 	}
315 	ret = dediprog_write(CMD_SET_VCC, voltage_selector, 0, NULL, 0);
316 	if (ret != 0x0) {
317 		msg_perr("Command Set SPI Voltage 0x%x failed!\n",
318 			 voltage_selector);
319 		return 1;
320 	}
321 	if (voltage_selector != 0) {
322 		/* Wait some time as the original driver does. */
323 		programmer_delay(200 * 1000);
324 	}
325 	return 0;
326 }
327 
328 struct dediprog_spispeeds {
329 	const char *const name;
330 	const int speed;
331 };
332 
333 static const struct dediprog_spispeeds spispeeds[] = {
334 	{ "24M",	0x0 },
335 	{ "12M",	0x2 },
336 	{ "8M",		0x1 },
337 	{ "3M",		0x3 },
338 	{ "2.18M",	0x4 },
339 	{ "1.5M",	0x5 },
340 	{ "750k",	0x6 },
341 	{ "375k",	0x7 },
342 	{ NULL,		0x0 },
343 };
344 
dediprog_set_spi_speed(unsigned int spispeed_idx)345 static int dediprog_set_spi_speed(unsigned int spispeed_idx)
346 {
347 	if (dediprog_firmwareversion < FIRMWARE_VERSION(5, 0, 0)) {
348 		msg_pwarn("Skipping to set SPI speed because firmware is too old.\n");
349 		return 0;
350 	}
351 
352 	const struct dediprog_spispeeds *spispeed = &spispeeds[spispeed_idx];
353 	msg_pdbg("SPI speed is %sHz\n", spispeed->name);
354 
355 	int ret = dediprog_write(CMD_SET_SPI_CLK, spispeed->speed, 0, NULL, 0);
356 	if (ret != 0x0) {
357 		msg_perr("Command Set SPI Speed 0x%x failed!\n", spispeed->speed);
358 		return 1;
359 	}
360 	return 0;
361 }
362 
prepare_rw_cmd(struct flashctx * const flash,uint8_t * data_packet,unsigned int count,uint8_t dedi_spi_cmd,unsigned int * value,unsigned int * idx,unsigned int start,int is_read)363 static int prepare_rw_cmd(
364 		struct flashctx *const flash, uint8_t *data_packet, unsigned int count,
365 		uint8_t dedi_spi_cmd, unsigned int *value, unsigned int *idx, unsigned int start, int is_read)
366 {
367 	if (count >= 1 << 16) {
368 		msg_perr("%s: Unsupported transfer length of %u blocks! "
369 			 "Please report a bug at flashrom@flashrom.org\n",
370 			 __func__, count);
371 		return 1;
372 	}
373 
374 	/* First 5 bytes are common in both generations. */
375 	data_packet[0] = count & 0xff;
376 	data_packet[1] = (count >> 8) & 0xff;
377 	data_packet[2] = 0; /* RFU */
378 	data_packet[3] = dedi_spi_cmd; /* Read/Write Mode (currently READ_MODE_STD, WRITE_MODE_PAGE_PGM or WRITE_MODE_2B_AAI) */
379 	data_packet[4] = 0; /* "Opcode". Specs imply necessity only for READ_MODE_4B_ADDR_FAST and WRITE_MODE_4B_ADDR_256B_PAGE_PGM */
380 
381 	if (protocol() >= PROTOCOL_V2) {
382 		if (is_read && flash->chip->feature_bits & FEATURE_4BA_FAST_READ) {
383 			data_packet[3] = READ_MODE_4B_ADDR_FAST_0x0C;
384 			data_packet[4] = JEDEC_READ_4BA_FAST;
385 		} else if (dedi_spi_cmd == WRITE_MODE_PAGE_PGM
386 			   && (flash->chip->feature_bits & FEATURE_4BA_WRITE)) {
387 			data_packet[3] = WRITE_MODE_4B_ADDR_256B_PAGE_PGM_0x12;
388 			data_packet[4] = JEDEC_BYTE_PROGRAM_4BA;
389 		}
390 
391 		*value = *idx = 0;
392 		data_packet[5] = 0; /* RFU */
393 		data_packet[6] = (start >>  0) & 0xff;
394 		data_packet[7] = (start >>  8) & 0xff;
395 		data_packet[8] = (start >> 16) & 0xff;
396 		data_packet[9] = (start >> 24) & 0xff;
397 		if (protocol() >= PROTOCOL_V3) {
398 			if (is_read) {
399 				data_packet[10] = 0x00;	/* address length (3 or 4) */
400 				data_packet[11] = 0x00;	/* dummy cycle / 2 */
401 			} else {
402 				/* 16 LSBs and 16 HSBs of page size */
403 				/* FIXME: This assumes page size of 256. */
404 				data_packet[10] = 0x00;
405 				data_packet[11] = 0x01;
406 				data_packet[12] = 0x00;
407 				data_packet[13] = 0x00;
408 			}
409 		}
410 	} else {
411 		if (flash->chip->feature_bits & FEATURE_4BA_EXT_ADDR) {
412 			if (spi_set_extended_address(flash, start >> 24))
413 				return 1;
414 		} else if (start >> 24) {
415 			msg_cerr("Can't handle 4-byte address with dediprog.\n");
416 			return 1;
417 		}
418 		/*
419 		 * We don't know how the dediprog firmware handles 4-byte
420 		 * addresses. So let's not tell it what we are doing and
421 		 * only send the lower 3 bytes.
422 		 */
423 		*value = start & 0xffff;
424 		*idx = (start >> 16) & 0xff;
425 	}
426 
427 	return 0;
428 }
429 
430 /* Bulk read interface, will read multiple 512 byte chunks aligned to 512 bytes.
431  * @start	start address
432  * @len		length
433  * @return	0 on success, 1 on failure
434  */
dediprog_spi_bulk_read(struct flashctx * flash,uint8_t * buf,unsigned int start,unsigned int len)435 static int dediprog_spi_bulk_read(struct flashctx *flash, uint8_t *buf, unsigned int start, unsigned int len)
436 {
437 	int err = 1;
438 
439 	/* chunksize must be 512, other sizes will NOT work at all. */
440 	const unsigned int chunksize = 512;
441 	const unsigned int count = len / chunksize;
442 
443 	struct dediprog_transfer_status status = { 0, 0, 0 };
444 	struct libusb_transfer *transfers[DEDIPROG_ASYNC_TRANSFERS] = { NULL, };
445 	struct libusb_transfer *transfer;
446 
447 	if (len == 0)
448 		return 0;
449 
450 	if ((start % chunksize) || (len % chunksize)) {
451 		msg_perr("%s: Unaligned start=%i, len=%i! Please report a bug at flashrom@flashrom.org\n",
452 			 __func__, start, len);
453 		return 1;
454 	}
455 
456 	int command_packet_size;
457 	switch (protocol()) {
458 	case PROTOCOL_V1:
459 		command_packet_size = 5;
460 		break;
461 	case PROTOCOL_V2:
462 		command_packet_size = 10;
463 		break;
464 	case PROTOCOL_V3:
465 		command_packet_size = 12;
466 		break;
467 	default:
468 		return 1;
469 	}
470 
471 	uint8_t data_packet[command_packet_size];
472 	unsigned int value, idx;
473 	if (prepare_rw_cmd(flash, data_packet, count, READ_MODE_STD, &value, &idx, start, 1))
474 		return 1;
475 
476 	int ret = dediprog_write(CMD_READ, value, idx, data_packet, sizeof(data_packet));
477 	if (ret != (int)sizeof(data_packet)) {
478 		msg_perr("Command Read SPI Bulk failed, %i %s!\n", ret, libusb_error_name(ret));
479 		return 1;
480 	}
481 
482 	/*
483 	 * Ring buffer of bulk transfers.
484 	 * Poll until at least one transfer is ready,
485 	 * schedule next transfers until buffer is full.
486 	 */
487 
488 	/* Allocate bulk transfers. */
489 	unsigned int i;
490 	for (i = 0; i < MIN(DEDIPROG_ASYNC_TRANSFERS, count); ++i) {
491 		transfers[i] = libusb_alloc_transfer(0);
492 		if (!transfers[i]) {
493 			msg_perr("Allocating libusb transfer %i failed: %s!\n", i, libusb_error_name(ret));
494 			goto err_free;
495 		}
496 	}
497 
498 	/* Now transfer requested chunks using libusb's asynchronous interface. */
499 	while (!status.error && (status.queued_idx < count)) {
500 		while ((status.queued_idx < count) &&
501 		       (status.queued_idx - status.finished_idx) < DEDIPROG_ASYNC_TRANSFERS)
502 		{
503 			transfer = transfers[status.queued_idx % DEDIPROG_ASYNC_TRANSFERS];
504 			libusb_fill_bulk_transfer(transfer, dediprog_handle, 0x80 | dediprog_in_endpoint,
505 					(unsigned char *)buf + status.queued_idx * chunksize, chunksize,
506 					dediprog_bulk_read_cb, &status, DEFAULT_TIMEOUT);
507 			transfer->flags |= LIBUSB_TRANSFER_SHORT_NOT_OK;
508 			ret = libusb_submit_transfer(transfer);
509 			if (ret < 0) {
510 				msg_perr("Submitting SPI bulk read %i failed: %s!\n",
511 					 status.queued_idx, libusb_error_name(ret));
512 				goto err_free;
513 			}
514 			++status.queued_idx;
515 		}
516 		if (dediprog_bulk_read_poll(&status, 0))
517 			goto err_free;
518 	}
519 	/* Wait for transfers to finish. */
520 	if (dediprog_bulk_read_poll(&status, 1))
521 		goto err_free;
522 	/* Check if everything has been transmitted. */
523 	if ((status.finished_idx < count) || status.error)
524 		goto err_free;
525 
526 	err = 0;
527 
528 err_free:
529 	dediprog_bulk_read_poll(&status, 1);
530 	for (i = 0; i < DEDIPROG_ASYNC_TRANSFERS; ++i)
531 		if (transfers[i]) libusb_free_transfer(transfers[i]);
532 	return err;
533 }
534 
dediprog_spi_read(struct flashctx * flash,uint8_t * buf,unsigned int start,unsigned int len)535 static int dediprog_spi_read(struct flashctx *flash, uint8_t *buf, unsigned int start, unsigned int len)
536 {
537 	int ret;
538 	/* chunksize must be 512, other sizes will NOT work at all. */
539 	const unsigned int chunksize = 0x200;
540 	unsigned int residue = start % chunksize ? min(len, chunksize - start % chunksize) : 0;
541 	unsigned int bulklen;
542 
543 	dediprog_set_leds(LED_BUSY);
544 
545 	if (residue) {
546 		msg_pdbg("Slow read for partial block from 0x%x, length 0x%x\n",
547 			 start, residue);
548 		ret = spi_read_chunked(flash, buf, start, residue, 16);
549 		if (ret)
550 			goto err;
551 	}
552 
553 	/* Round down. */
554 	bulklen = (len - residue) / chunksize * chunksize;
555 	ret = dediprog_spi_bulk_read(flash, buf + residue, start + residue, bulklen);
556 	if (ret)
557 		goto err;
558 
559 	len -= residue + bulklen;
560 	if (len != 0) {
561 		msg_pdbg("Slow read for partial block from 0x%x, length 0x%x\n",
562 			 start, len);
563 		ret = spi_read_chunked(flash, buf + residue + bulklen,
564 				       start + residue + bulklen, len, 16);
565 		if (ret)
566 			goto err;
567 	}
568 
569 	dediprog_set_leds(LED_PASS);
570 	return 0;
571 err:
572 	dediprog_set_leds(LED_ERROR);
573 	return ret;
574 }
575 
576 /* Bulk write interface, will write multiple chunksize byte chunks aligned to chunksize bytes.
577  * @chunksize       length of data chunks, only 256 supported by now
578  * @start           start address
579  * @len             length
580  * @dedi_spi_cmd    dediprog specific write command for spi bus
581  * @return          0 on success, 1 on failure
582  */
dediprog_spi_bulk_write(struct flashctx * flash,const uint8_t * buf,unsigned int chunksize,unsigned int start,unsigned int len,uint8_t dedi_spi_cmd)583 static int dediprog_spi_bulk_write(struct flashctx *flash, const uint8_t *buf, unsigned int chunksize,
584 				   unsigned int start, unsigned int len, uint8_t dedi_spi_cmd)
585 {
586 	/* USB transfer size must be 512, other sizes will NOT work at all.
587 	 * chunksize is the real data size per USB bulk transfer. The remaining
588 	 * space in a USB bulk transfer must be filled with 0xff padding.
589 	 */
590 	const unsigned int count = len / chunksize;
591 
592 	/*
593 	 * We should change this check to
594 	 *   chunksize > 512
595 	 * once we know how to handle different chunk sizes.
596 	 */
597 	if (chunksize != 256) {
598 		msg_perr("%s: Chunk sizes other than 256 bytes are unsupported, chunksize=%u!\n"
599 			 "Please report a bug at flashrom@flashrom.org\n", __func__, chunksize);
600 		return 1;
601 	}
602 
603 	if ((start % chunksize) || (len % chunksize)) {
604 		msg_perr("%s: Unaligned start=%i, len=%i! Please report a bug "
605 			 "at flashrom@flashrom.org\n", __func__, start, len);
606 		return 1;
607 	}
608 
609 	/* No idea if the hardware can handle empty writes, so chicken out. */
610 	if (len == 0)
611 		return 0;
612 
613 	int command_packet_size;
614 	switch (protocol()) {
615 	case PROTOCOL_V1:
616 		command_packet_size = 5;
617 		break;
618 	case PROTOCOL_V2:
619 		command_packet_size = 10;
620 		break;
621 	case PROTOCOL_V3:
622 		command_packet_size = 14;
623 		break;
624 	default:
625 		return 1;
626 	}
627 
628 	uint8_t data_packet[command_packet_size];
629 	unsigned int value, idx;
630 	if (prepare_rw_cmd(flash, data_packet, count, dedi_spi_cmd, &value, &idx, start, 0))
631 		return 1;
632 	int ret = dediprog_write(CMD_WRITE, value, idx, data_packet, sizeof(data_packet));
633 	if (ret != (int)sizeof(data_packet)) {
634 		msg_perr("Command Write SPI Bulk failed, %s!\n", libusb_error_name(ret));
635 		return 1;
636 	}
637 
638 	unsigned int i;
639 	for (i = 0; i < count; i++) {
640 		unsigned char usbbuf[512];
641 		memcpy(usbbuf, buf + i * chunksize, chunksize);
642 		memset(usbbuf + chunksize, 0xff, sizeof(usbbuf) - chunksize); // fill up with 0xFF
643 		int transferred;
644 		ret = libusb_bulk_transfer(dediprog_handle, dediprog_out_endpoint, usbbuf, 512, &transferred,
645 					   DEFAULT_TIMEOUT);
646 		if ((ret < 0) || (transferred != 512)) {
647 			msg_perr("SPI bulk write failed, expected %i, got %s!\n", 512, libusb_error_name(ret));
648 			return 1;
649 		}
650 	}
651 
652 	return 0;
653 }
654 
dediprog_spi_write(struct flashctx * flash,const uint8_t * buf,unsigned int start,unsigned int len,uint8_t dedi_spi_cmd)655 static int dediprog_spi_write(struct flashctx *flash, const uint8_t *buf,
656 			      unsigned int start, unsigned int len, uint8_t dedi_spi_cmd)
657 {
658 	int ret;
659 	const unsigned int chunksize = flash->chip->page_size;
660 	unsigned int residue = start % chunksize ? chunksize - start % chunksize : 0;
661 	unsigned int bulklen;
662 
663 	dediprog_set_leds(LED_BUSY);
664 
665 	if (chunksize != 256) {
666 		msg_pdbg("Page sizes other than 256 bytes are unsupported as "
667 			 "we don't know how dediprog\nhandles them.\n");
668 		/* Write everything like it was residue. */
669 		residue = len;
670 	}
671 
672 	if (residue) {
673 		msg_pdbg("Slow write for partial block from 0x%x, length 0x%x\n",
674 			 start, residue);
675 		/* No idea about the real limit. Maybe 16 including command and address, maybe more. */
676 		ret = spi_write_chunked(flash, buf, start, residue, 11);
677 		if (ret) {
678 			dediprog_set_leds(LED_ERROR);
679 			return ret;
680 		}
681 	}
682 
683 	/* Round down. */
684 	bulklen = (len - residue) / chunksize * chunksize;
685 	ret = dediprog_spi_bulk_write(flash, buf + residue, chunksize, start + residue, bulklen, dedi_spi_cmd);
686 	if (ret) {
687 		dediprog_set_leds(LED_ERROR);
688 		return ret;
689 	}
690 
691 	len -= residue + bulklen;
692 	if (len) {
693 		msg_pdbg("Slow write for partial block from 0x%x, length 0x%x\n",
694 			 start, len);
695 		ret = spi_write_chunked(flash, buf + residue + bulklen,
696 				        start + residue + bulklen, len, 11);
697 		if (ret) {
698 			dediprog_set_leds(LED_ERROR);
699 			return ret;
700 		}
701 	}
702 
703 	dediprog_set_leds(LED_PASS);
704 	return 0;
705 }
706 
dediprog_spi_write_256(struct flashctx * flash,const uint8_t * buf,unsigned int start,unsigned int len)707 static int dediprog_spi_write_256(struct flashctx *flash, const uint8_t *buf, unsigned int start, unsigned int len)
708 {
709 	return dediprog_spi_write(flash, buf, start, len, WRITE_MODE_PAGE_PGM);
710 }
711 
dediprog_spi_write_aai(struct flashctx * flash,const uint8_t * buf,unsigned int start,unsigned int len)712 static int dediprog_spi_write_aai(struct flashctx *flash, const uint8_t *buf, unsigned int start, unsigned int len)
713 {
714 	return dediprog_spi_write(flash, buf, start, len, WRITE_MODE_2B_AAI);
715 }
716 
dediprog_spi_send_command(struct flashctx * flash,unsigned int writecnt,unsigned int readcnt,const unsigned char * writearr,unsigned char * readarr)717 static int dediprog_spi_send_command(struct flashctx *flash,
718 				     unsigned int writecnt,
719 				     unsigned int readcnt,
720 				     const unsigned char *writearr,
721 				     unsigned char *readarr)
722 {
723 	int ret;
724 
725 	msg_pspew("%s, writecnt=%i, readcnt=%i\n", __func__, writecnt, readcnt);
726 	if (writecnt > flash->mst->spi.max_data_write) {
727 		msg_perr("Invalid writecnt=%i, aborting.\n", writecnt);
728 		return 1;
729 	}
730 	if (readcnt > flash->mst->spi.max_data_read) {
731 		msg_perr("Invalid readcnt=%i, aborting.\n", readcnt);
732 		return 1;
733 	}
734 
735 	unsigned int idx, value;
736 	/* New protocol has options and timeout combined as value while the old one used the value field for
737 	 * timeout and the index field for options. */
738 	if (protocol() >= PROTOCOL_V2) {
739 		idx = 0;
740 		value = readcnt ? 0x1 : 0x0; // Indicate if we require a read
741 	} else {
742 		idx = readcnt ? 0x1 : 0x0; // Indicate if we require a read
743 		value = 0;
744 	}
745 	ret = dediprog_write(CMD_TRANSCEIVE, value, idx, writearr, writecnt);
746 	if (ret != (int)writecnt) {
747 		msg_perr("Send SPI failed, expected %i, got %i %s!\n",
748 			 writecnt, ret, libusb_error_name(ret));
749 		return 1;
750 	}
751 	if (readcnt == 0) // If we don't require a response, we are done here
752 		return 0;
753 
754 	/* The specifications do state the possibility to set a timeout for transceive transactions.
755 	 * Apparently the "timeout" is a delay, and you can use long delays to accelerate writing - in case you
756 	 * can predict the time needed by the previous command or so (untested). In any case, using this
757 	 * "feature" to set sane-looking timouts for the read below will completely trash performance with
758 	 * SF600 and/or firmwares >= 6.0 while they seem to be benign on SF100 with firmwares <= 5.5.2. *shrug*
759 	 *
760 	 * The specification also uses only 0 in its examples, so the lesson to learn here:
761 	 * "Never trust the description of an interface in the documentation but use the example code and pray."
762 	const uint8_t read_timeout = 10 + readcnt/512;
763 	if (protocol() >= PROTOCOL_V2) {
764 		idx = 0;
765 		value = min(read_timeout, 0xFF) | (0 << 8) ; // Timeout in lower byte, option in upper byte
766 	} else {
767 		idx = (0 & 0xFF);  // Lower byte is option (0x01 = require SR, 0x02 keep CS low)
768 		value = min(read_timeout, 0xFF); // Possibly two bytes but we play safe here
769 	}
770 	ret = dediprog_read(CMD_TRANSCEIVE, value, idx, readarr, readcnt);
771 	*/
772 	ret = dediprog_read(CMD_TRANSCEIVE, 0, 0, readarr, readcnt);
773 	if (ret != (int)readcnt) {
774 		msg_perr("Receive SPI failed, expected %i, got %i %s!\n", readcnt, ret, libusb_error_name(ret));
775 		return 1;
776 	}
777 	return 0;
778 }
779 
dediprog_check_devicestring(void)780 static int dediprog_check_devicestring(void)
781 {
782 	int ret;
783 	char buf[0x11];
784 
785 	/* Command Receive Device String. */
786 	ret = dediprog_read(CMD_READ_PROG_INFO, 0, 0, (uint8_t *)buf, 0x10);
787 	if (ret != 0x10) {
788 		msg_perr("Incomplete/failed Command Receive Device String!\n");
789 		return 1;
790 	}
791 	buf[0x10] = '\0';
792 	msg_pdbg("Found a %s\n", buf);
793 	if (memcmp(buf, "SF100", 0x5) == 0)
794 		dediprog_devicetype = DEV_SF100;
795 	else if (memcmp(buf, "SF200", 0x5) == 0)
796 		dediprog_devicetype = DEV_SF200;
797 	else if (memcmp(buf, "SF600", 0x5) == 0)
798 		dediprog_devicetype = DEV_SF600;
799 	else {
800 		msg_perr("Device not a SF100, SF200, or SF600!\n");
801 		return 1;
802 	}
803 
804 	int sfnum;
805 	int fw[3];
806 	if (sscanf(buf, "SF%d V:%d.%d.%d ", &sfnum, &fw[0], &fw[1], &fw[2]) != 4 ||
807 	    sfnum != (int)dediprog_devicetype) {
808 		msg_perr("Unexpected firmware version string '%s'\n", buf);
809 		return 1;
810 	}
811 	/* Only these major versions were tested. */
812 	if (fw[0] < 2 || fw[0] > 7) {
813 		msg_perr("Unexpected firmware version %d.%d.%d!\n", fw[0], fw[1], fw[2]);
814 		return 1;
815 	}
816 
817 	dediprog_firmwareversion = FIRMWARE_VERSION(fw[0], fw[1], fw[2]);
818 	if (protocol() == PROTOCOL_UNKNOWN) {
819 		msg_perr("Internal error: Unable to determine protocol version.\n");
820 		return 1;
821 	}
822 
823 	return 0;
824 }
825 
826 /*
827  * Read the id from the dediprog. This should return the numeric part of the
828  * serial number found on a sticker on the back of the dediprog. Note this
829  * number is stored in writable eeprom, so it could get out of sync. Also note,
830  * this function only supports SF100 at this time, but SF600 support is not too
831  * much different.
832  * @return  the id on success, -1 on failure
833  */
dediprog_read_id(void)834 static int dediprog_read_id(void)
835 {
836 	int ret;
837 	uint8_t buf[3];
838 
839 	ret = libusb_control_transfer(dediprog_handle, REQTYPE_OTHER_IN,
840 				      0x7,    /* request */
841 				      0,      /* value */
842 				      0xEF00, /* index */
843 				      buf, sizeof(buf),
844 				      DEFAULT_TIMEOUT);
845 	if (ret != sizeof(buf)) {
846 		msg_perr("Failed to read dediprog id, error %d!\n", ret);
847 		return -1;
848 	}
849 
850 	return buf[0] << 16 | buf[1] << 8 | buf[2];
851 }
852 
853 /*
854  * This command presumably sets the voltage for the SF100 itself (not the
855  * SPI flash). Only use this command with firmware older than V6.0.0. Newer
856  * (including all SF600s) do not support it.
857  */
858 
859 /* This command presumably sets the voltage for the SF100 itself (not the SPI flash).
860  * Only use dediprog_set_voltage on SF100 programmers with firmware older
861  * than V6.0.0. Newer programmers (including all SF600s) do not support it. */
dediprog_set_voltage(void)862 static int dediprog_set_voltage(void)
863 {
864 	unsigned char buf[1] = {0};
865 	int ret = libusb_control_transfer(dediprog_handle, REQTYPE_OTHER_IN, CMD_SET_VOLTAGE, 0x0, 0x0,
866 			      buf, 0x1, DEFAULT_TIMEOUT);
867 	if (ret < 0) {
868 		msg_perr("Command Set Voltage failed (%s)!\n", libusb_error_name(ret));
869 		return 1;
870 	}
871 	if ((ret != 1) || (buf[0] != 0x6f)) {
872 		msg_perr("Unexpected response to init!\n");
873 		return 1;
874 	}
875 
876 	return 0;
877 }
878 
dediprog_standalone_mode(void)879 static int dediprog_standalone_mode(void)
880 {
881 	int ret;
882 
883 	if (dediprog_devicetype != DEV_SF600)
884 		return 0;
885 
886 	msg_pdbg2("Disabling standalone mode.\n");
887 	ret = dediprog_write(CMD_SET_STANDALONE, LEAVE_STANDALONE_MODE, 0, NULL, 0);
888 	if (ret) {
889 		msg_perr("Failed to disable standalone mode: %s\n", libusb_error_name(ret));
890 		return 1;
891 	}
892 
893 	return 0;
894 }
895 
896 #if 0
897 /* Something.
898  * Present in eng_detect_blink.log with firmware 3.1.8
899  * Always preceded by Command Receive Device String
900  */
901 static int dediprog_command_b(void)
902 {
903 	int ret;
904 	char buf[0x3];
905 
906 	ret = usb_control_msg(dediprog_handle, REQTYPE_OTHER_IN, 0x7, 0x0, 0xef00,
907 			      buf, 0x3, DEFAULT_TIMEOUT);
908 	if (ret < 0) {
909 		msg_perr("Command B failed (%s)!\n", libusb_error_name(ret));
910 		return 1;
911 	}
912 	if ((ret != 0x3) || (buf[0] != 0xff) || (buf[1] != 0xff) ||
913 	    (buf[2] != 0xff)) {
914 		msg_perr("Unexpected response to Command B!\n");
915 		return 1;
916 	}
917 
918 	return 0;
919 }
920 #endif
921 
set_target_flash(enum dediprog_target target)922 static int set_target_flash(enum dediprog_target target)
923 {
924 	int ret = dediprog_write(CMD_SET_TARGET, target, 0, NULL, 0);
925 	if (ret != 0) {
926 		msg_perr("set_target_flash failed (%s)!\n", libusb_error_name(ret));
927 		return 1;
928 	}
929 	return 0;
930 }
931 
932 #if 0
933 /* Returns true if the button is currently pressed. */
934 static bool dediprog_get_button(void)
935 {
936 	char buf[1];
937 	int ret = usb_control_msg(dediprog_handle, REQTYPE_EP_IN, CMD_GET_BUTTON, 0, 0,
938 			      buf, 0x1, DEFAULT_TIMEOUT);
939 	if (ret != 0) {
940 		msg_perr("Could not get button state (%s)!\n", libusb_error_name(ret));
941 		return 1;
942 	}
943 	return buf[0] != 1;
944 }
945 #endif
946 
parse_voltage(char * voltage)947 static int parse_voltage(char *voltage)
948 {
949 	char *tmp = NULL;
950 	int i;
951 	int millivolt = 0, fraction = 0;
952 
953 	if (!voltage || !strlen(voltage)) {
954 		msg_perr("Empty voltage= specified.\n");
955 		return -1;
956 	}
957 	millivolt = (int)strtol(voltage, &tmp, 0);
958 	voltage = tmp;
959 	/* Handle "," and "." as decimal point. Everything after it is assumed
960 	 * to be in decimal notation.
961 	 */
962 	if ((*voltage == '.') || (*voltage == ',')) {
963 		voltage++;
964 		for (i = 0; i < 3; i++) {
965 			fraction *= 10;
966 			/* Don't advance if the current character is invalid,
967 			 * but continue multiplying.
968 			 */
969 			if ((*voltage < '0') || (*voltage > '9'))
970 				continue;
971 			fraction += *voltage - '0';
972 			voltage++;
973 		}
974 		/* Throw away remaining digits. */
975 		voltage += strspn(voltage, "0123456789");
976 	}
977 	/* The remaining string must be empty or "mV" or "V". */
978 	tolower_string(voltage);
979 
980 	/* No unit or "V". */
981 	if ((*voltage == '\0') || !strncmp(voltage, "v", 1)) {
982 		millivolt *= 1000;
983 		millivolt += fraction;
984 	} else if (!strncmp(voltage, "mv", 2) ||
985 		   !strncmp(voltage, "milliv", 6)) {
986 		/* No adjustment. fraction is discarded. */
987 	} else {
988 		/* Garbage at the end of the string. */
989 		msg_perr("Garbage voltage= specified.\n");
990 		return -1;
991 	}
992 	return millivolt;
993 }
994 
995 static struct spi_master spi_master_dediprog = {
996 	.features	= SPI_MASTER_NO_4BA_MODES,
997 	.max_data_read	= 16, /* 18 seems to work fine as well, but 19 times out sometimes with FW 5.15. */
998 	.max_data_write	= 16,
999 	.command	= dediprog_spi_send_command,
1000 	.multicommand	= default_spi_send_multicommand,
1001 	.read		= dediprog_spi_read,
1002 	.write_256	= dediprog_spi_write_256,
1003 	.write_aai	= dediprog_spi_write_aai,
1004 };
1005 
1006 /*
1007  * Open a dediprog_handle with the USB device at the given index.
1008  * @index   index of the USB device
1009  * @return  0 for success, -1 for error, -2 for busy device
1010  */
dediprog_open(int index)1011 static int dediprog_open(int index)
1012 {
1013 	const uint16_t vid = devs_dediprog[0].vendor_id;
1014 	const uint16_t pid = devs_dediprog[0].device_id;
1015 	int ret;
1016 
1017 	dediprog_handle = usb_dev_get_by_vid_pid_number(usb_ctx, vid, pid, (unsigned int) index);
1018 	if (!dediprog_handle) {
1019 		msg_perr("Could not find a Dediprog programmer on USB.\n");
1020 		libusb_exit(usb_ctx);
1021 		return -1;
1022 	}
1023 	ret = libusb_set_configuration(dediprog_handle, 1);
1024 	if (ret != 0) {
1025 		msg_perr("Could not set USB device configuration: %i %s\n",
1026 			 ret, libusb_error_name(ret));
1027 		libusb_close(dediprog_handle);
1028 		return -2;
1029 	}
1030 	ret = libusb_claim_interface(dediprog_handle, 0);
1031 	if (ret < 0) {
1032 		msg_perr("Could not claim USB device interface %i: %i %s\n",
1033 			 0, ret, libusb_error_name(ret));
1034 		libusb_close(dediprog_handle);
1035 		return -2;
1036 	}
1037 	return 0;
1038 }
1039 
dediprog_shutdown(void * data)1040 static int dediprog_shutdown(void *data)
1041 {
1042 	dediprog_devicetype = DEV_UNKNOWN;
1043 
1044 	/* URB 28. Command Set SPI Voltage to 0. */
1045 	if (dediprog_set_spi_voltage(0x0))
1046 		return 1;
1047 
1048 	if (libusb_release_interface(dediprog_handle, 0)) {
1049 		msg_perr("Could not release USB interface!\n");
1050 		return 1;
1051 	}
1052 	libusb_close(dediprog_handle);
1053 	libusb_exit(usb_ctx);
1054 
1055 	return 0;
1056 }
1057 
dediprog_init(void)1058 int dediprog_init(void)
1059 {
1060 	char *voltage, *id_str, *device, *spispeed, *target_str;
1061 	int spispeed_idx = 1;
1062 	int millivolt = 3500;
1063 	int id = -1; /* -1 defaults to enumeration order */
1064 	int found_id;
1065 	long usedevice = 0;
1066 	long target = FLASH_TYPE_APPLICATION_FLASH_1;
1067 	int i, ret;
1068 
1069 	spispeed = extract_programmer_param("spispeed");
1070 	if (spispeed) {
1071 		for (i = 0; spispeeds[i].name; ++i) {
1072 			if (!strcasecmp(spispeeds[i].name, spispeed)) {
1073 				spispeed_idx = i;
1074 				break;
1075 			}
1076 		}
1077 		if (!spispeeds[i].name) {
1078 			msg_perr("Error: Invalid spispeed value: '%s'.\n", spispeed);
1079 			free(spispeed);
1080 			return 1;
1081 		}
1082 		free(spispeed);
1083 	}
1084 
1085 	voltage = extract_programmer_param("voltage");
1086 	if (voltage) {
1087 		millivolt = parse_voltage(voltage);
1088 		free(voltage);
1089 		if (millivolt < 0)
1090 			return 1;
1091 		msg_pinfo("Setting voltage to %i mV\n", millivolt);
1092 	}
1093 
1094 	id_str = extract_programmer_param("id");
1095 	if (id_str) {
1096 		char prefix0, prefix1;
1097 		if (sscanf(id_str, "%c%c%d", &prefix0, &prefix1, &id) != 3) {
1098 			msg_perr("Error: Could not parse dediprog 'id'.\n");
1099 			msg_perr("Expected a string like SF012345 or DP012345.\n");
1100 			free(id_str);
1101 			return 1;
1102 		}
1103 		if (id < 0 || id >= 0x1000000) {
1104 			msg_perr("Error: id %s is out of range!\n", id_str);
1105 			free(id_str);
1106 			return 1;
1107 		}
1108 		if (!(prefix0 == 'S' && prefix1 == 'F') && !(prefix0 == 'D' && prefix1 == 'P')) {
1109 			msg_perr("Error: %s is an invalid id!\n", id_str);
1110 			free(id_str);
1111 			return 1;
1112 		}
1113 		msg_pinfo("Will search for dediprog id %s.\n", id_str);
1114 	}
1115 	free(id_str);
1116 
1117 	device = extract_programmer_param("device");
1118 	if (device) {
1119 		char *dev_suffix;
1120 		if (id != -1) {
1121 			msg_perr("Error: Cannot use 'id' and 'device'.\n");
1122 		}
1123 		errno = 0;
1124 		usedevice = strtol(device, &dev_suffix, 10);
1125 		if (errno != 0 || device == dev_suffix) {
1126 			msg_perr("Error: Could not convert 'device'.\n");
1127 			free(device);
1128 			return 1;
1129 		}
1130 		if (usedevice < 0 || usedevice > INT_MAX) {
1131 			msg_perr("Error: Value for 'device' is out of range.\n");
1132 			free(device);
1133 			return 1;
1134 		}
1135 		if (strlen(dev_suffix) > 0) {
1136 			msg_perr("Error: Garbage following 'device' value.\n");
1137 			free(device);
1138 			return 1;
1139 		}
1140 		msg_pinfo("Using device %li.\n", usedevice);
1141 	}
1142 	free(device);
1143 
1144 	target_str = extract_programmer_param("target");
1145 	if (target_str) {
1146 		char *target_suffix;
1147 		errno = 0;
1148 		target = strtol(target_str, &target_suffix, 10);
1149 		if (errno != 0 || target_str == target_suffix) {
1150 			msg_perr("Error: Could not convert 'target'.\n");
1151 			free(target_str);
1152 			return 1;
1153 		}
1154 		if (target < 1 || target > 2) {
1155 			msg_perr("Error: Value for 'target' is out of range.\n");
1156 			free(target_str);
1157 			return 1;
1158 		}
1159 		if (strlen(target_suffix) > 0) {
1160 			msg_perr("Error: Garbage following 'target' value.\n");
1161 			free(target_str);
1162 			return 1;
1163 		}
1164 		switch (target) {
1165 		case 1:
1166 			msg_pinfo("Using target %s.\n", "FLASH_TYPE_APPLICATION_FLASH_1");
1167 			target = FLASH_TYPE_APPLICATION_FLASH_1;
1168 			break;
1169 		case 2:
1170 			msg_pinfo("Using target %s.\n", "FLASH_TYPE_APPLICATION_FLASH_2");
1171 			target = FLASH_TYPE_APPLICATION_FLASH_2;
1172 			break;
1173 		default:
1174 			break;
1175 		}
1176 	}
1177 	free(target_str);
1178 
1179 	/* Here comes the USB stuff. */
1180 	libusb_init(&usb_ctx);
1181 	if (!usb_ctx) {
1182 		msg_perr("Could not initialize libusb!\n");
1183 		return 1;
1184 	}
1185 
1186 	if (id != -1) {
1187 		for (i = 0; ; i++) {
1188 			ret = dediprog_open(i);
1189 			if (ret == -1) {
1190 				/* no dev */
1191 				libusb_exit(usb_ctx);
1192 				return 1;
1193 			} else if (ret == -2) {
1194 				/* busy dev */
1195 				continue;
1196 			}
1197 
1198 			/* Notice we can only call dediprog_read_id() after
1199 			 * libusb_set_configuration() and
1200 			 * libusb_claim_interface(). When searching by id and
1201 			 * either configuration or claim fails (usually the
1202 			 * device is in use by another instance of flashrom),
1203 			 * the device is skipped and the next device is tried.
1204 			 */
1205 			found_id = dediprog_read_id();
1206 			if (found_id < 0) {
1207 				msg_perr("Could not read id.\n");
1208 				libusb_release_interface(dediprog_handle, 0);
1209 				libusb_close(dediprog_handle);
1210 				continue;
1211 			}
1212 			msg_pinfo("Found dediprog id SF%06d.\n", found_id);
1213 			if (found_id != id) {
1214 				libusb_release_interface(dediprog_handle, 0);
1215 				libusb_close(dediprog_handle);
1216 				continue;
1217 			}
1218 			break;
1219 		}
1220 	} else {
1221 		if (dediprog_open(usedevice)) {
1222 			return 1;
1223 		}
1224 		found_id = dediprog_read_id();
1225 	}
1226 
1227 	if (found_id >= 0) {
1228 		msg_pinfo("Using dediprog id SF%06d.\n", found_id);
1229 	}
1230 
1231 	if (register_shutdown(dediprog_shutdown, NULL))
1232 		return 1;
1233 
1234 	/* Try reading the devicestring. If that fails and the device is old (FW < 6.0.0, which we can not know)
1235 	 * then we need to try the "set voltage" command and then attempt to read the devicestring again. */
1236 	if (dediprog_check_devicestring()) {
1237 		if (dediprog_set_voltage())
1238 			return 1;
1239 		if (dediprog_check_devicestring())
1240 			return 1;
1241 	}
1242 
1243 	/* SF100/SF200 uses one in/out endpoint, SF600 uses separate in/out endpoints */
1244 	dediprog_in_endpoint = 2;
1245 	switch (dediprog_devicetype) {
1246 	case DEV_SF100:
1247 	case DEV_SF200:
1248 		dediprog_out_endpoint = 2;
1249 		break;
1250 	default:
1251 		dediprog_out_endpoint = 1;
1252 		break;
1253 	}
1254 
1255 	/* Set all possible LEDs as soon as possible to indicate activity.
1256 	 * Because knowing the firmware version is required to set the LEDs correctly we need to this after
1257 	 * dediprog_check_devicestring() has queried the device. */
1258 	dediprog_set_leds(LED_ALL);
1259 
1260 	/* Select target/socket, frequency and VCC. */
1261 	if (set_target_flash(target) ||
1262 	    dediprog_set_spi_speed(spispeed_idx) ||
1263 	    dediprog_set_spi_voltage(millivolt)) {
1264 		dediprog_set_leds(LED_ERROR);
1265 		return 1;
1266 	}
1267 
1268 	if (dediprog_standalone_mode())
1269 		return 1;
1270 
1271 	if (dediprog_devicetype == DEV_SF100 && protocol() == PROTOCOL_V1)
1272 		spi_master_dediprog.features &= ~SPI_MASTER_NO_4BA_MODES;
1273 
1274 	if (protocol() == PROTOCOL_V2)
1275 		spi_master_dediprog.features |= SPI_MASTER_4BA;
1276 
1277 	if (register_spi_master(&spi_master_dediprog) || dediprog_set_leds(LED_NONE))
1278 		return 1;
1279 
1280 	return 0;
1281 }
1282