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