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