flashrom 

flashrom Svn Source Tree

Root/trunk/ch341a_spi.c

  • Property svn:eol-style set to native
1/*
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_TIMEOUT1000/* 1000 ms is plenty and we have no backup strategy anyway. */
37#define WRITE_EP0x02
38#define READ_EP0x82
39
40#define CH341_PACKET_LENGTH0x20
41#define CH341_MAX_PACKETS256
42#define CH341_MAX_PACKET_LEN(CH341_PACKET_LENGTH * CH341_MAX_PACKETS)
43
44#define CH341A_CMD_SET_OUTPUT0xA1
45#define CH341A_CMD_IO_ADDR0xA2
46#define CH341A_CMD_PRINT_OUT0xA3
47#define CH341A_CMD_SPI_STREAM0xA8
48#define CH341A_CMD_SIO_STREAM0xA9
49#define CH341A_CMD_I2C_STREAM0xAA
50#define CH341A_CMD_UIO_STREAM0xAB
51
52#define CH341A_CMD_I2C_STM_START0x74
53#define CH341A_CMD_I2C_STM_STOP0x75
54#define CH341A_CMD_I2C_STM_OUT0x80
55#define CH341A_CMD_I2C_STM_IN0xC0
56#define CH341A_CMD_I2C_STM_MAX( min( 0x3F, CH341_PACKET_LENGTH ) )
57#define CH341A_CMD_I2C_STM_SET0x60 // bit 2: SPI with two data pairs D5,D4=out, D7,D6=in
58#define CH341A_CMD_I2C_STM_US0x40
59#define CH341A_CMD_I2C_STM_MS0x50
60#define CH341A_CMD_I2C_STM_DLY0x0F
61#define CH341A_CMD_I2C_STM_END0x00
62
63#define CH341A_CMD_UIO_STM_IN0x00
64#define CH341A_CMD_UIO_STM_DIR0x40
65#define CH341A_CMD_UIO_STM_OUT0x80
66#define CH341A_CMD_UIO_STM_US0xC0
67#define CH341A_CMD_UIO_STM_END0x20
68
69#define CH341A_STM_I2C_20K0x00
70#define CH341A_STM_I2C_100K0x01
71#define CH341A_STM_I2C_400K0x02
72#define CH341A_STM_I2C_750K0x03
73#define CH341A_STM_SPI_DBL0x04
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{
100size_t i;
101for (i = 0; i < len; i++) {
102msg_pspew(" %02x", ((uint8_t *)buf)[i]);
103if (i % CH341_PACKET_LENGTH == CH341_PACKET_LENGTH - 1)
104msg_pspew("\n");
105}
106}
107
108static void cb_common(const char *func, struct libusb_transfer *transfer)
109{
110int *transfer_cnt = (int*)transfer->user_data;
111
112if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
113/* Silently ACK and exit. */
114*transfer_cnt = TRANS_IDLE;
115return;
116}
117
118if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
119msg_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{
129cb_common(__func__, transfer);
130}
131
132/* callback for bulk in async transfer */
133static void LIBUSB_CALL cb_in(struct libusb_transfer *transfer)
134{
135cb_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{
140if (handle == NULL)
141return -1;
142
143int state_out = TRANS_IDLE;
144transfer_out->buffer = (uint8_t*)writearr;
145transfer_out->length = writecnt;
146transfer_out->user_data = &state_out;
147
148/* Schedule write first */
149if (writecnt > 0) {
150state_out = TRANS_ACTIVE;
151int ret = libusb_submit_transfer(transfer_out);
152if (ret) {
153msg_perr("%s: failed to submit OUT transfer: %s\n", func, libusb_error_name(ret));
154state_out = TRANS_ERR;
155goto 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. */
161unsigned int free_idx = 0; /* The IN transfer we expect to be free next. */
162unsigned int in_idx = 0; /* The IN transfer we expect to be completed next. */
163unsigned int in_done = 0;
164unsigned int in_active = 0;
165unsigned int out_done = 0;
166uint8_t *in_buf = readarr;
167int state_in[USB_IN_TRANSFERS] = {0};
168do {
169/* Schedule new reads as long as there are free transfers and unscheduled bytes to read. */
170while ((in_done + in_active) < readcnt && state_in[free_idx] == TRANS_IDLE) {
171unsigned int cur_todo = min(CH341_PACKET_LENGTH - 1, readcnt - in_done - in_active);
172transfer_ins[free_idx]->length = cur_todo;
173transfer_ins[free_idx]->buffer = in_buf;
174transfer_ins[free_idx]->user_data = &state_in[free_idx];
175int ret = libusb_submit_transfer(transfer_ins[free_idx]);
176if (ret) {
177state_in[free_idx] = TRANS_ERR;
178msg_perr("%s: failed to submit IN transfer: %s\n",
179 func, libusb_error_name(ret));
180goto err;
181}
182in_buf += cur_todo;
183in_active += cur_todo;
184state_in[free_idx] = TRANS_ACTIVE;
185free_idx = (free_idx + 1) % USB_IN_TRANSFERS; /* Increment (and wrap around). */
186}
187
188/* Actually get some work done. */
189libusb_handle_events_timeout(NULL, &(struct timeval){1, 0});
190
191/* Check for the write */
192if (out_done < writecnt) {
193if (state_out == TRANS_ERR) {
194goto err;
195} else if (state_out > 0) {
196out_done += state_out;
197state_out = TRANS_IDLE;
198}
199}
200/* Check for completed transfers. */
201while (state_in[in_idx] != TRANS_IDLE && state_in[in_idx] != TRANS_ACTIVE) {
202if (state_in[in_idx] == TRANS_ERR) {
203goto err;
204}
205/* If a transfer is done, record the number of bytes read and reuse it later. */
206in_done += state_in[in_idx];
207in_active -= state_in[in_idx];
208state_in[in_idx] = TRANS_IDLE;
209in_idx = (in_idx + 1) % USB_IN_TRANSFERS; /* Increment (and wrap around). */
210}
211} while ((out_done < writecnt) || (in_done < readcnt));
212
213if (out_done > 0) {
214msg_pspew("Wrote %d bytes:\n", out_done);
215print_hex(writearr, out_done);
216msg_pspew("\n\n");
217}
218if (in_done > 0) {
219msg_pspew("Read %d bytes:\n", in_done);
220print_hex(readarr, in_done);
221msg_pspew("\n\n");
222}
223return 0;
224err:
225/* Clean up on errors. */
226msg_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. */
229if ((writecnt > 0) && (state_out == TRANS_ACTIVE)) {
230if (libusb_cancel_transfer(transfer_out) != 0)
231state_out = TRANS_ERR;
232}
233if (readcnt > 0) {
234unsigned int i;
235for (i = 0; i < USB_IN_TRANSFERS; i++) {
236if (state_in[i] == TRANS_ACTIVE)
237if (libusb_cancel_transfer(transfer_ins[i]) != 0)
238state_in[i] = TRANS_ERR;
239}
240}
241
242/* Wait for cancellations to complete. */
243while (1) {
244bool finished = true;
245if ((writecnt > 0) && (state_out == TRANS_ACTIVE))
246finished = false;
247if (readcnt > 0) {
248unsigned int i;
249for (i = 0; i < USB_IN_TRANSFERS; i++) {
250if (state_in[i] == TRANS_ACTIVE)
251finished = false;
252}
253}
254if (finished)
255break;
256libusb_handle_events_timeout(NULL, &(struct timeval){1, 0});
257}
258return -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{
265if (handle == NULL)
266return -1;
267
268uint8_t buf[] = {
269CH341A_CMD_I2C_STREAM,
270CH341A_CMD_I2C_STM_SET | (speed & 0x7),
271CH341A_CMD_I2C_STM_END
272};
273
274int32_t ret = usb_transfer(__func__, sizeof(buf), 0, buf, NULL);
275if (ret < 0) {
276msg_perr("Could not configure stream interface.\n");
277}
278return 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{
284x = ((x >> 1) & 0x55) | ((x << 1) & 0xaa);
285x = ((x >> 2) & 0x33) | ((x << 2) & 0xcc);
286x = ((x >> 4) & 0x0f) | ((x << 4) & 0xf0);
287return x;
288}
289
290/* The assumed map between UIO command bits, pins on CH341A chip and pins on SPI chip:
291 * UIOCH341ASPICH341A SPI name
292 * 0D0/15CS/1 (CS0)
293 * 1D1/16unused(CS1)
294 * 2D2/17unused(CS2)
295 * 3D3/18SCK/6(DCK)
296 * 4D4/19unused(DOUT2)
297 * 5D5/20SI/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/21unused(DIN2)
301 *D7/22SO/2(DIN)
302 */
303static int32_t enable_pins(bool enable)
304{
305uint8_t buf[] = {
306CH341A_CMD_UIO_STREAM,
307CH341A_CMD_UIO_STM_OUT | 0x37, // CS high (all of them), SCK=0, DOUT*=1
308CH341A_CMD_UIO_STM_DIR | (enable ? 0x3F : 0x00), // Interface output enable / disable
309CH341A_CMD_UIO_STM_END,
310};
311
312int32_t ret = usb_transfer(__func__, sizeof(buf), 0, buf, NULL);
313if (ret < 0) {
314msg_perr("Could not %sable output pins.\n", enable ? "en" : "dis");
315}
316return 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). */
324int delay_cnt = 2;
325if (stored_delay_us) {
326delay_cnt = (stored_delay_us * 4) / 3;
327stored_delay_us = 0;
328}
329*ptr++ = CH341A_CMD_UIO_STREAM;
330*ptr++ = CH341A_CMD_UIO_STM_OUT | 0x37; /* deasserted */
331int i;
332for (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. */
343if ((usecs + stored_delay_us) > 20) {
344unsigned int inc = 20 - stored_delay_us;
345internal_delay(usecs - inc);
346usecs = inc;
347}
348stored_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{
353if (handle == NULL)
354return -1;
355
356/* How many packets ... */
357const 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. */
360uint8_t wbuf[packets+1][CH341_PACKET_LENGTH];
361uint8_t rbuf[writecnt + readcnt];
362/* Initialize the write buffer to zero to prevent writing random stack contents to device. */
363memset(wbuf[0], 0, CH341_PACKET_LENGTH);
364
365uint8_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. */
368pluck_cs(ptr);
369unsigned int write_left = writecnt;
370unsigned int read_left = readcnt;
371unsigned int p;
372for (p = 0; p < packets; p++) {
373unsigned int write_now = min(CH341_PACKET_LENGTH - 1, write_left);
374unsigned int read_now = min ((CH341_PACKET_LENGTH - 1) - write_now, read_left);
375ptr = wbuf[p+1];
376*ptr++ = CH341A_CMD_SPI_STREAM;
377unsigned int i;
378for (i = 0; i < write_now; ++i)
379*ptr++ = swap_byte(*writearr++);
380if (read_now) {
381memset(ptr, 0xFF, read_now);
382read_left -= read_now;
383}
384write_left -= write_now;
385}
386
387int32_t ret = usb_transfer(__func__, CH341_PACKET_LENGTH + packets + writecnt + readcnt,
388 writecnt + readcnt, wbuf[0], rbuf);
389if (ret < 0)
390return -1;
391
392unsigned int i;
393for (i = 0; i < readcnt; i++) {
394*readarr++ = swap_byte(rbuf[writecnt + i]);
395}
396
397return 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{
416if (handle == NULL)
417return -1;
418
419enable_pins(false);
420libusb_free_transfer(transfer_out);
421transfer_out = NULL;
422int i;
423for (i = 0; i < USB_IN_TRANSFERS; i++) {
424libusb_free_transfer(transfer_ins[i]);
425transfer_ins[i] = NULL;
426}
427libusb_release_interface(handle, 0);
428libusb_close(handle);
429libusb_exit(NULL);
430handle = NULL;
431return 0;
432}
433
434int ch341a_spi_init(void)
435{
436if (handle != NULL) {
437msg_cerr("%s: handle already set! Please report a bug at flashrom@flashrom.org\n", __func__);
438return -1;
439}
440
441int32_t ret = libusb_init(NULL);
442if (ret < 0) {
443msg_perr("Couldnt initialize libusb!\n");
444return -1;
445}
446
447libusb_set_debug(NULL, 3); // Enable information, warning and error messages (only).
448
449uint16_t vid = devs_ch341a_spi[0].vendor_id;
450uint16_t pid = devs_ch341a_spi[0].device_id;
451handle = libusb_open_device_with_vid_pid(NULL, vid, pid);
452if (handle == NULL) {
453msg_perr("Couldn't open device %04x:%04x.\n", vid, pid);
454return -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
460ret = libusb_detach_kernel_driver(handle, 0);
461if (ret == LIBUSB_ERROR_NOT_SUPPORTED) {
462msg_pwarn("Detaching kernel drivers is not supported. Further accesses may fail.\n");
463} else if (ret != 0 && ret != LIBUSB_ERROR_NOT_FOUND) {
464msg_pwarn("Failed to detach kernel driver: '%s'. Further accesses will probably fail.\n",
465 libusb_error_name(ret));
466}
467#endif
468
469ret = libusb_claim_interface(handle, 0);
470if (ret != 0) {
471msg_perr("Failed to claim interface 0: '%s'\n", libusb_error_name(ret));
472goto close_handle;
473}
474
475struct libusb_device *dev;
476if (!(dev = libusb_get_device(handle))) {
477msg_perr("Failed to get device from device handle.\n");
478goto close_handle;
479}
480
481struct libusb_device_descriptor desc;
482ret = libusb_get_device_descriptor(dev, &desc);
483if (ret < 0) {
484msg_perr("Failed to get device descriptor: '%s'\n", libusb_error_name(ret));
485goto release_interface;
486}
487
488msg_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. */
494transfer_out = libusb_alloc_transfer(0);
495if (!transfer_out) {
496msg_perr("Failed to alloc libusb OUT transfer\n");
497goto release_interface;
498}
499int i;
500for (i = 0; i < USB_IN_TRANSFERS; i++) {
501transfer_ins[i] = libusb_alloc_transfer(0);
502if (transfer_ins[i] == NULL) {
503msg_perr("Failed to alloc libusb IN transfer %d\n", i);
504goto dealloc_transfers;
505}
506}
507/* We use these helpers but dont fill the actual buffer yet. */
508libusb_fill_bulk_transfer(transfer_out, handle, WRITE_EP, NULL, 0, cb_out, NULL, USB_TIMEOUT);
509for (i = 0; i < USB_IN_TRANSFERS; i++)
510libusb_fill_bulk_transfer(transfer_ins[i], handle, READ_EP, NULL, 0, cb_in, NULL, USB_TIMEOUT);
511
512if ((config_stream(CH341A_STM_I2C_100K) < 0) || (enable_pins(true) < 0))
513goto dealloc_transfers;
514
515register_shutdown(ch341a_spi_shutdown, NULL);
516register_spi_master(&spi_master_ch341a_spi);
517
518return 0;
519
520dealloc_transfers:
521for (i = 0; i < USB_IN_TRANSFERS; i++) {
522if (transfer_ins[i] == NULL)
523break;
524libusb_free_transfer(transfer_ins[i]);
525transfer_ins[i] = NULL;
526}
527libusb_free_transfer(transfer_out);
528transfer_out = NULL;
529release_interface:
530libusb_release_interface(handle, 0);
531close_handle:
532libusb_close(handle);
533handle = NULL;
534return -1;
535}

Archive Download this file

Revision: HEAD