blob: 6eb28048b8be855a9b53a7acedf859fc48bd317f [file] [log] [blame]
Urja Rannikko0870b022016-01-31 22:10:29 +00001/*
2 * This file is part of the flashrom project.
3 *
4 * Copyright (C) 2011 asbokid <ballymunboy@gmail.com>
5 * Copyright (C) 2014 Pluto Yang <yangyj.ee@gmail.com>
6 * Copyright (C) 2015-2016 Stefan Tauner
7 * Copyright (C) 2015 Urja Rannikko <urjaman@gmail.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24#include <string.h>
25#include <libusb.h>
26#include "flash.h"
27#include "programmer.h"
28
29/* LIBUSB_CALL ensures the right calling conventions on libusb callbacks.
30 * However, the macro is not defined everywhere. m(
31 */
32#ifndef LIBUSB_CALL
33#define LIBUSB_CALL
34#endif
35
36#define USB_TIMEOUT 1000 /* 1000 ms is plenty and we have no backup strategy anyway. */
37#define WRITE_EP 0x02
38#define READ_EP 0x82
39
40#define CH341_PACKET_LENGTH 0x20
41#define CH341_MAX_PACKETS 256
42#define CH341_MAX_PACKET_LEN (CH341_PACKET_LENGTH * CH341_MAX_PACKETS)
43
44#define CH341A_CMD_SET_OUTPUT 0xA1
45#define CH341A_CMD_IO_ADDR 0xA2
46#define CH341A_CMD_PRINT_OUT 0xA3
47#define CH341A_CMD_SPI_STREAM 0xA8
48#define CH341A_CMD_SIO_STREAM 0xA9
49#define CH341A_CMD_I2C_STREAM 0xAA
50#define CH341A_CMD_UIO_STREAM 0xAB
51
52#define CH341A_CMD_I2C_STM_START 0x74
53#define CH341A_CMD_I2C_STM_STOP 0x75
54#define CH341A_CMD_I2C_STM_OUT 0x80
55#define CH341A_CMD_I2C_STM_IN 0xC0
56#define CH341A_CMD_I2C_STM_MAX ( min( 0x3F, CH341_PACKET_LENGTH ) )
57#define CH341A_CMD_I2C_STM_SET 0x60 // bit 2: SPI with two data pairs D5,D4=out, D7,D6=in
58#define CH341A_CMD_I2C_STM_US 0x40
59#define CH341A_CMD_I2C_STM_MS 0x50
60#define CH341A_CMD_I2C_STM_DLY 0x0F
61#define CH341A_CMD_I2C_STM_END 0x00
62
63#define CH341A_CMD_UIO_STM_IN 0x00
64#define CH341A_CMD_UIO_STM_DIR 0x40
65#define CH341A_CMD_UIO_STM_OUT 0x80
66#define CH341A_CMD_UIO_STM_US 0xC0
67#define CH341A_CMD_UIO_STM_END 0x20
68
69#define CH341A_STM_I2C_20K 0x00
70#define CH341A_STM_I2C_100K 0x01
71#define CH341A_STM_I2C_400K 0x02
72#define CH341A_STM_I2C_750K 0x03
73#define CH341A_STM_SPI_DBL 0x04
74
75
76/* Number of parallel IN transfers. 32 seems to produce the most stable throughput on Windows. */
77#define USB_IN_TRANSFERS 32
78
79/* We need to use many queued IN transfers for any resemblance of performance (especially on Windows)
80 * because USB spec says that transfers end on non-full packets and the device sends the 31 reply
81 * data bytes to each 32-byte packet with command + 31 bytes of data... */
82static struct libusb_transfer *transfer_out = NULL;
83static struct libusb_transfer *transfer_ins[USB_IN_TRANSFERS] = {0};
84
85/* Accumulate delays to be plucked between CS deassertion and CS assertions. */
86static unsigned int stored_delay_us = 0;
87
88static struct libusb_device_handle *handle = NULL;
89
90const struct dev_entry devs_ch341a_spi[] = {
91 {0x1A86, 0x5512, OK, "Winchiphead (WCH)", "CH341A"},
92
93 {0},
94};
95
96enum trans_state {TRANS_ACTIVE = -2, TRANS_ERR = -1, TRANS_IDLE = 0};
97
98static void print_hex(const void *buf, size_t len)
99{
100 size_t i;
101 for (i = 0; i < len; i++) {
102 msg_pspew(" %02x", ((uint8_t *)buf)[i]);
103 if (i % CH341_PACKET_LENGTH == CH341_PACKET_LENGTH - 1)
104 msg_pspew("\n");
105 }
106}
107
108static void cb_common(const char *func, struct libusb_transfer *transfer)
109{
110 int *transfer_cnt = (int*)transfer->user_data;
111
112 if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
113 /* Silently ACK and exit. */
114 *transfer_cnt = TRANS_IDLE;
115 return;
116 }
117
118 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
119 msg_perr("\n%s: error: %s\n", func, libusb_error_name(transfer->status));
120 *transfer_cnt = TRANS_ERR;
121 } else {
122 *transfer_cnt = transfer->actual_length;
123 }
124}
125
126/* callback for bulk out async transfer */
127static void LIBUSB_CALL cb_out(struct libusb_transfer *transfer)
128{
129 cb_common(__func__, transfer);
130}
131
132/* callback for bulk in async transfer */
133static void LIBUSB_CALL cb_in(struct libusb_transfer *transfer)
134{
135 cb_common(__func__, transfer);
136}
137
138static int32_t usb_transfer(const char *func, unsigned int writecnt, unsigned int readcnt, const uint8_t *writearr, uint8_t *readarr)
139{
140 if (handle == NULL)
141 return -1;
142
143 int state_out = TRANS_IDLE;
144 transfer_out->buffer = (uint8_t*)writearr;
145 transfer_out->length = writecnt;
146 transfer_out->user_data = &state_out;
147
148 /* Schedule write first */
149 if (writecnt > 0) {
150 state_out = TRANS_ACTIVE;
151 int ret = libusb_submit_transfer(transfer_out);
152 if (ret) {
153 msg_perr("%s: failed to submit OUT transfer: %s\n", func, libusb_error_name(ret));
154 state_out = TRANS_ERR;
155 goto err;
156 }
157 }
158
159 /* Handle all asynchronous packets as long as we have stuff to write or read. The write(s) simply need
160 * to complete but we need to scheduling reads as long as we are not done. */
161 unsigned int free_idx = 0; /* The IN transfer we expect to be free next. */
162 unsigned int in_idx = 0; /* The IN transfer we expect to be completed next. */
163 unsigned int in_done = 0;
164 unsigned int in_active = 0;
165 unsigned int out_done = 0;
166 uint8_t *in_buf = readarr;
167 int state_in[USB_IN_TRANSFERS] = {0};
168 do {
169 /* Schedule new reads as long as there are free transfers and unscheduled bytes to read. */
170 while ((in_done + in_active) < readcnt && state_in[free_idx] == TRANS_IDLE) {
171 unsigned int cur_todo = min(CH341_PACKET_LENGTH - 1, readcnt - in_done - in_active);
172 transfer_ins[free_idx]->length = cur_todo;
173 transfer_ins[free_idx]->buffer = in_buf;
174 transfer_ins[free_idx]->user_data = &state_in[free_idx];
175 int ret = libusb_submit_transfer(transfer_ins[free_idx]);
176 if (ret) {
177 state_in[free_idx] = TRANS_ERR;
178 msg_perr("%s: failed to submit IN transfer: %s\n",
179 func, libusb_error_name(ret));
180 goto err;
181 }
182 in_buf += cur_todo;
183 in_active += cur_todo;
184 state_in[free_idx] = TRANS_ACTIVE;
185 free_idx = (free_idx + 1) % USB_IN_TRANSFERS; /* Increment (and wrap around). */
186 }
187
188 /* Actually get some work done. */
189 libusb_handle_events_timeout(NULL, &(struct timeval){1, 0});
190
191 /* Check for the write */
192 if (out_done < writecnt) {
193 if (state_out == TRANS_ERR) {
194 goto err;
195 } else if (state_out > 0) {
196 out_done += state_out;
197 state_out = TRANS_IDLE;
198 }
199 }
200 /* Check for completed transfers. */
201 while (state_in[in_idx] != TRANS_IDLE && state_in[in_idx] != TRANS_ACTIVE) {
202 if (state_in[in_idx] == TRANS_ERR) {
203 goto err;
204 }
205 /* If a transfer is done, record the number of bytes read and reuse it later. */
206 in_done += state_in[in_idx];
207 in_active -= state_in[in_idx];
208 state_in[in_idx] = TRANS_IDLE;
209 in_idx = (in_idx + 1) % USB_IN_TRANSFERS; /* Increment (and wrap around). */
210 }
211 } while ((out_done < writecnt) || (in_done < readcnt));
212
213 if (out_done > 0) {
214 msg_pspew("Wrote %d bytes:\n", out_done);
215 print_hex(writearr, out_done);
216 msg_pspew("\n\n");
217 }
218 if (in_done > 0) {
219 msg_pspew("Read %d bytes:\n", in_done);
220 print_hex(readarr, in_done);
221 msg_pspew("\n\n");
222 }
223 return 0;
224err:
225 /* Clean up on errors. */
226 msg_perr("%s: Failed to %s %d bytes\n", func, (state_out == TRANS_ERR) ? "write" : "read",
227 (state_out == TRANS_ERR) ? writecnt : readcnt);
228 /* First, we must cancel any ongoing requests and wait for them to be canceled. */
229 if ((writecnt > 0) && (state_out == TRANS_ACTIVE)) {
230 if (libusb_cancel_transfer(transfer_out) != 0)
231 state_out = TRANS_ERR;
232 }
233 if (readcnt > 0) {
234 unsigned int i;
235 for (i = 0; i < USB_IN_TRANSFERS; i++) {
236 if (state_in[i] == TRANS_ACTIVE)
237 if (libusb_cancel_transfer(transfer_ins[i]) != 0)
238 state_in[i] = TRANS_ERR;
239 }
240 }
241
242 /* Wait for cancellations to complete. */
243 while (1) {
244 bool finished = true;
245 if ((writecnt > 0) && (state_out == TRANS_ACTIVE))
246 finished = false;
247 if (readcnt > 0) {
248 unsigned int i;
249 for (i = 0; i < USB_IN_TRANSFERS; i++) {
250 if (state_in[i] == TRANS_ACTIVE)
251 finished = false;
252 }
253 }
254 if (finished)
255 break;
256 libusb_handle_events_timeout(NULL, &(struct timeval){1, 0});
257 }
258 return -1;
259}
260
261/* Set the I2C bus speed (speed(b1b0): 0 = 20kHz; 1 = 100kHz, 2 = 400kHz, 3 = 750kHz).
262 * Set the SPI bus data width (speed(b2): 0 = Single, 1 = Double). */
263static int32_t config_stream(uint32_t speed)
264{
265 if (handle == NULL)
266 return -1;
267
268 uint8_t buf[] = {
269 CH341A_CMD_I2C_STREAM,
270 CH341A_CMD_I2C_STM_SET | (speed & 0x7),
271 CH341A_CMD_I2C_STM_END
272 };
273
274 int32_t ret = usb_transfer(__func__, sizeof(buf), 0, buf, NULL);
275 if (ret < 0) {
276 msg_perr("Could not configure stream interface.\n");
277 }
278 return ret;
279}
280
281/* ch341 requires LSB first, swap the bit order before send and after receive */
282static uint8_t swap_byte(uint8_t x)
283{
284 x = ((x >> 1) & 0x55) | ((x << 1) & 0xaa);
285 x = ((x >> 2) & 0x33) | ((x << 2) & 0xcc);
286 x = ((x >> 4) & 0x0f) | ((x << 4) & 0xf0);
287 return x;
288}
289
290/* The assumed map between UIO command bits, pins on CH341A chip and pins on SPI chip:
291 * UIO CH341A SPI CH341A SPI name
292 * 0 D0/15 CS/1 (CS0)
293 * 1 D1/16 unused (CS1)
294 * 2 D2/17 unused (CS2)
295 * 3 D3/18 SCK/6 (DCK)
296 * 4 D4/19 unused (DOUT2)
297 * 5 D5/20 SI/5 (DOUT)
298 * - The UIO stream commands seem to only have 6 bits of output, and D6/D7 are the SPI inputs,
299 * mapped as follows:
300 * D6/21 unused (DIN2)
301 * D7/22 SO/2 (DIN)
302 */
303static int32_t enable_pins(bool enable)
304{
305 uint8_t buf[] = {
306 CH341A_CMD_UIO_STREAM,
307 CH341A_CMD_UIO_STM_OUT | 0x37, // CS high (all of them), SCK=0, DOUT*=1
308 CH341A_CMD_UIO_STM_DIR | (enable ? 0x3F : 0x00), // Interface output enable / disable
309 CH341A_CMD_UIO_STM_END,
310 };
311
312 int32_t ret = usb_transfer(__func__, sizeof(buf), 0, buf, NULL);
313 if (ret < 0) {
314 msg_perr("Could not %sable output pins.\n", enable ? "en" : "dis");
315 }
316 return ret;
317}
318
319/* De-assert and assert CS in one operation. */
320static void pluck_cs(uint8_t *ptr)
321{
322 /* This was measured to give a minumum deassertion time of 2.25 us,
323 * >20x more than needed for most SPI chips (100ns). */
324 int delay_cnt = 2;
325 if (stored_delay_us) {
326 delay_cnt = (stored_delay_us * 4) / 3;
327 stored_delay_us = 0;
328 }
329 *ptr++ = CH341A_CMD_UIO_STREAM;
330 *ptr++ = CH341A_CMD_UIO_STM_OUT | 0x37; /* deasserted */
331 int i;
332 for (i = 0; i < delay_cnt; i++)
333 *ptr++ = CH341A_CMD_UIO_STM_OUT | 0x37; /* "delay" */
334 *ptr++ = CH341A_CMD_UIO_STM_OUT | 0x36; /* asserted */
335 *ptr++ = CH341A_CMD_UIO_STM_END;
336}
337
338void ch341a_spi_delay(unsigned int usecs)
339{
340 /* There is space for 28 bytes instructions of 750 ns each in the CS packet (32 - 4 for the actual CS
341 * instructions), thus max 21 us, but we avoid getting too near to this boundary and use
342 * internal_delay() for durations over 20 us. */
343 if ((usecs + stored_delay_us) > 20) {
344 unsigned int inc = 20 - stored_delay_us;
345 internal_delay(usecs - inc);
346 usecs = inc;
347 }
348 stored_delay_us += usecs;
349}
350
351static int ch341a_spi_spi_send_command(struct flashctx *flash, unsigned int writecnt, unsigned int readcnt, const unsigned char *writearr, unsigned char *readarr)
352{
353 if (handle == NULL)
354 return -1;
355
356 /* How many packets ... */
357 const size_t packets = (writecnt + readcnt + CH341_PACKET_LENGTH - 2) / (CH341_PACKET_LENGTH - 1);
358
359 /* We pluck CS/timeout handling into the first packet thus we need to allocate one extra package. */
360 uint8_t wbuf[packets+1][CH341_PACKET_LENGTH];
361 uint8_t rbuf[writecnt + readcnt];
362 /* Initialize the write buffer to zero to prevent writing random stack contents to device. */
363 memset(wbuf[0], 0, CH341_PACKET_LENGTH);
364
365 uint8_t *ptr = wbuf[0];
366 /* CS usage is optimized by doing both transitions in one packet.
367 * Final transition to deselected state is in the pin disable. */
368 pluck_cs(ptr);
369 unsigned int write_left = writecnt;
370 unsigned int read_left = readcnt;
371 unsigned int p;
372 for (p = 0; p < packets; p++) {
373 unsigned int write_now = min(CH341_PACKET_LENGTH - 1, write_left);
374 unsigned int read_now = min ((CH341_PACKET_LENGTH - 1) - write_now, read_left);
375 ptr = wbuf[p+1];
376 *ptr++ = CH341A_CMD_SPI_STREAM;
377 unsigned int i;
378 for (i = 0; i < write_now; ++i)
379 *ptr++ = swap_byte(*writearr++);
380 if (read_now) {
381 memset(ptr, 0xFF, read_now);
382 read_left -= read_now;
383 }
384 write_left -= write_now;
385 }
386
387 int32_t ret = usb_transfer(__func__, CH341_PACKET_LENGTH + packets + writecnt + readcnt,
388 writecnt + readcnt, wbuf[0], rbuf);
389 if (ret < 0)
390 return -1;
391
392 unsigned int i;
393 for (i = 0; i < readcnt; i++) {
394 *readarr++ = swap_byte(rbuf[writecnt + i]);
395 }
396
397 return 0;
398}
399
400static const struct spi_master spi_master_ch341a_spi = {
401 .type = SPI_CONTROLLER_CH341A_SPI,
402 /* flashrom's current maximum is 256 B. CH341A was tested on Linux and Windows to accept atleast
403 * 128 kB. Basically there should be no hard limit because transfers are broken up into USB packets
404 * sent to the device and most of their payload streamed via SPI. */
405 .max_data_read = 4 * 1024,
406 .max_data_write = 4 * 1024,
407 .command = ch341a_spi_spi_send_command,
408 .multicommand = default_spi_send_multicommand,
409 .read = default_spi_read,
410 .write_256 = default_spi_write_256,
411 .write_aai = default_spi_write_aai,
412};
413
414static int ch341a_spi_shutdown(void *data)
415{
416 if (handle == NULL)
417 return -1;
418
419 enable_pins(false);
420 libusb_free_transfer(transfer_out);
421 transfer_out = NULL;
422 int i;
423 for (i = 0; i < USB_IN_TRANSFERS; i++) {
424 libusb_free_transfer(transfer_ins[i]);
425 transfer_ins[i] = NULL;
426 }
427 libusb_release_interface(handle, 0);
428 libusb_close(handle);
429 libusb_exit(NULL);
430 handle = NULL;
431 return 0;
432}
433
434int ch341a_spi_init(void)
435{
436 if (handle != NULL) {
437 msg_cerr("%s: handle already set! Please report a bug at flashrom@flashrom.org\n", __func__);
438 return -1;
439 }
440
441 int32_t ret = libusb_init(NULL);
442 if (ret < 0) {
443 msg_perr("Couldnt initialize libusb!\n");
444 return -1;
445 }
446
447 libusb_set_debug(NULL, 3); // Enable information, warning and error messages (only).
448
449 uint16_t vid = devs_ch341a_spi[0].vendor_id;
450 uint16_t pid = devs_ch341a_spi[0].device_id;
451 handle = libusb_open_device_with_vid_pid(NULL, vid, pid);
452 if (handle == NULL) {
453 msg_perr("Couldn't open device %04x:%04x.\n", vid, pid);
454 return -1;
455 }
456
457/* libusb_detach_kernel_driver() and friends basically only work on Linux. We simply try to detach on Linux
458 * without a lot of passion here. If that works fine else we will fail on claiming the interface anyway. */
459#if IS_LINUX
460 ret = libusb_detach_kernel_driver(handle, 0);
461 if (ret == LIBUSB_ERROR_NOT_SUPPORTED) {
462 msg_pwarn("Detaching kernel drivers is not supported. Further accesses may fail.\n");
463 } else if (ret != 0 && ret != LIBUSB_ERROR_NOT_FOUND) {
464 msg_pwarn("Failed to detach kernel driver: '%s'. Further accesses will probably fail.\n",
465 libusb_error_name(ret));
466 }
467#endif
468
469 ret = libusb_claim_interface(handle, 0);
470 if (ret != 0) {
471 msg_perr("Failed to claim interface 0: '%s'\n", libusb_error_name(ret));
472 goto close_handle;
473 }
474
475 struct libusb_device *dev;
476 if (!(dev = libusb_get_device(handle))) {
477 msg_perr("Failed to get device from device handle.\n");
478 goto close_handle;
479 }
480
481 struct libusb_device_descriptor desc;
482 ret = libusb_get_device_descriptor(dev, &desc);
483 if (ret < 0) {
484 msg_perr("Failed to get device descriptor: '%s'\n", libusb_error_name(ret));
485 goto release_interface;
486 }
487
488 msg_pdbg("Device revision is %d.%01d.%01d\n",
489 (desc.bcdDevice >> 8) & 0x00FF,
490 (desc.bcdDevice >> 4) & 0x000F,
491 (desc.bcdDevice >> 0) & 0x000F);
492
493 /* Allocate and pre-fill transfer structures. */
494 transfer_out = libusb_alloc_transfer(0);
495 if (!transfer_out) {
496 msg_perr("Failed to alloc libusb OUT transfer\n");
497 goto release_interface;
498 }
499 int i;
500 for (i = 0; i < USB_IN_TRANSFERS; i++) {
501 transfer_ins[i] = libusb_alloc_transfer(0);
502 if (transfer_ins[i] == NULL) {
503 msg_perr("Failed to alloc libusb IN transfer %d\n", i);
504 goto dealloc_transfers;
505 }
506 }
507 /* We use these helpers but dont fill the actual buffer yet. */
508 libusb_fill_bulk_transfer(transfer_out, handle, WRITE_EP, NULL, 0, cb_out, NULL, USB_TIMEOUT);
509 for (i = 0; i < USB_IN_TRANSFERS; i++)
510 libusb_fill_bulk_transfer(transfer_ins[i], handle, READ_EP, NULL, 0, cb_in, NULL, USB_TIMEOUT);
511
512 if ((config_stream(CH341A_STM_I2C_100K) < 0) || (enable_pins(true) < 0))
513 goto dealloc_transfers;
514
515 register_shutdown(ch341a_spi_shutdown, NULL);
516 register_spi_master(&spi_master_ch341a_spi);
517
518 return 0;
519
520dealloc_transfers:
521 for (i = 0; i < USB_IN_TRANSFERS; i++) {
522 if (transfer_ins[i] == NULL)
523 break;
524 libusb_free_transfer(transfer_ins[i]);
525 transfer_ins[i] = NULL;
526 }
527 libusb_free_transfer(transfer_out);
528 transfer_out = NULL;
529release_interface:
530 libusb_release_interface(handle, 0);
531close_handle:
532 libusb_close(handle);
533 handle = NULL;
534 return -1;
535}