OpenOCD
ch347.c
Go to the documentation of this file.
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 /***************************************************************************
4  * Driver for CH347-JTAG interface V1.1 *
5  * *
6  * Copyright (C) 2022 by oidcat. *
7  * Author: oidcatiot@163.com *
8  * *
9  * Enhancements by EasyDevKits - info@easydevkits.com *
10  * *
11  * CH347 is a high-speed USB bus converter chip that provides UART, I2C *
12  * and SPI synchronous serial ports and JTAG interface through USB bus. *
13  * *
14  * The JTAG interface by CH347 can supports transmission frequency *
15  * configuration up to 60MHz. *
16  * *
17  * The USB2.0 to JTAG scheme based on CH347 can be used to build *
18  * customized USB high-speed JTAG debugger and other products. *
19  * *
20  * _____________ *
21  * | |____JTAG/SWD (TDO,TDI,TMS,TCK,TRST) *
22  * USB__| CH347T/F | *
23  * |_____________|____UART(TXD1,RXD1,RTS1,CTS1,DTR1) *
24  * ______|______ *
25  * | | *
26  * | 8 MHz XTAL | *
27  * |_____________| *
28  * *
29  * This CH347 driver is tested with the CH347T chip in mode 3 and *
30  * with the CH347F chip. *
31  * *
32  * The datasheet for the wch-ic.com's CH347 part is here: *
33  * https://www.wch-ic.com/downloads/CH347DS1_PDF.html *
34  * *
35  ***************************************************************************/
36 
37 #ifdef HAVE_CONFIG_H
38 #include "config.h"
39 #endif
40 
41 #if IS_CYGWIN == 1
42 #include "windows.h"
43 #undef LOG_ERROR
44 #endif
45 
46 // project specific includes
47 #include <jtag/interface.h>
48 #include <jtag/commands.h>
49 #include <jtag/swd.h>
50 #include <jtag/adapter.h>
51 #include <helper/time_support.h>
52 #include <helper/replacements.h>
53 #include <helper/list.h>
54 #include <helper/binarybuffer.h>
55 #include "libusb_helper.h"
56 
57 // system includes
58 #include <stdlib.h>
59 #include <string.h>
60 #include <sys/time.h>
61 #include <time.h>
62 #include <unistd.h>
63 
64 #define TDI_H BIT(4)
65 #define TDI_L 0
66 #define TMS_H BIT(1)
67 #define TMS_L 0
68 #define TCK_H BIT(0)
69 #define TCK_L 0
70 #define TRST_H BIT(5)
71 #define TRST_L 0
72 #define LED_ON 1
73 #define LED_OFF 0
74 #define GPIO_CNT 8 // the CH347 has 8 GPIO's
75 /* mask which GPIO's are available in mode 3 of the CH347T: only GPIO3 (Pin11 / SCL),
76  GPIO4 (Pin15 / ACT), GPIO5 (Pin9 / TRST) and GPIO6 (Pin2 / CTS1) are possible */
77 #define CH347T_USABLE_GPIOS 0x78
78 /* On the CH347F the GPIO's share the pins with the interface signals: GPIO0 (Pin17),
79  GPIO1 (Pin18), GPIO2 (Pin10), GPIO3 (Pin9 / TRST), GPIO4 (Pin23 / TCK + SWDCLK),
80  GPIO5 (Pin24 / TDO), GPIO6 (Pin25 / TDI), GPIO7 (Pin26 / TMS + SWDIO). GPIO4 to GPIO7
81  always carry a signal of the JTAG or SWD interface, so only GPIO0 to GPIO3 are left.
82  GPIO3 is TRST, which is not a SWD signal. */
83 #define CH347F_USABLE_GPIOS 0x0F
84 /* In SWD mode the TRST pin is unused as a JTAG signal, so it can drive SRST through the GPIO
85  command. TRST is Pin9 on both chips, but has a different GPIO number: GPIO5 on CH347T,
86  GPIO3 on CH347F. */
87 #define CH347T_TRST_GPIO 5
88 #define CH347F_TRST_GPIO 3
89 /* For GPIO command: always set bits 7 and 6 for GPIO enable
90  bits 5 and 4 for pin direction output bit 3 is the data bit */
91 #define GPIO_SET_L (BIT(4) | BIT(5) | BIT(6) | BIT(7)) // value for setting a GPIO to low
92 #define GPIO_SET_H (BIT(3) | BIT(4) | BIT(5) | BIT(6) | BIT(7)) // value for setting a GPIO to high
93 // enable the pin and set the direction to input, so the pin gets released
94 #define GPIO_SET_INPUT (BIT(6) | BIT(7))
95 
96 #define VENDOR_VERSION 0x5F // for getting the chip version
97 
98 // maybe the hardware of the CH347 chip can capture only this amount of TDO bits
99 #define HW_TDO_BUF_SIZE 4096
100 // Don't send more than this amount of bytes via libusb in one packet. Also that is the limit for LARGER_PACK mode.
101 #define LARGER_PACK_MAX_SIZE 51200
102 // The data length contained in each command packet during USB high-speed operation
103 #define UCMDPKT_DATA_MAX_BYTES_USBHS 507
104 #define USBC_PACKET_USBHS 512 // Maximum data length per packet at USB high speed
105 #define CH347_CMD_HEADER 3 // Protocol header length (1 byte command type + 2 bytes data length)
106 #define CH347_CMD_INIT_READ_LEN 1 // for JTAG_INIT/SWD_INIT we have only one data byte
107 // if we send 9 in the init command we get the STANDARD mode or LARGER_PACK mode flag
108 #define CH347_CMD_INIT_GET_MODE_CLOCK_INDEX_VALUE 9
109 // No more bits are allowed per CH347_CMD_JTAG_BIT_OP command; this should be dividable by 8
110 #define MAX_BITS_PER_BIT_OP 248
111 
112 /* Protocol transmission format: CMD (1 byte) + Length (2 bytes) + Data
113  Parameter acquisition, used to obtain firmware version, JTAG interface related parameters, etc */
114 #define CH347_CMD_INFO_RD 0xCA
115 #define CH347_CMD_GPIO 0xCC // GPIO Command
116 #define CH347_CMD_JTAG_INIT 0xD0 // JTAG Interface initialization command
117 #define CH347_CMD_JTAG_BIT_OP 0xD1 // JTAG interface pin bit control command
118 #define CH347_CMD_JTAG_BIT_OP_RD 0xD2 // JTAG interface pin bit control and read commands
119 #define CH347_CMD_JTAG_DATA_SHIFT 0xD3 // JTAG interface data shift command
120 #define CH347_CMD_JTAG_DATA_SHIFT_RD 0xD4 // JTAG interface data shift and read command
121 // for a single command these amount of data can be read at max
122 #define CH347_SINGLE_CMD_MAX_READ MAX(GPIO_CNT, CH347_CMD_INIT_READ_LEN)
123 
124 // for SWD
125 #define CH347_CMD_SWD_INIT 0xE5 // SWD Interface Initialization Command
126 #define CH347_CMD_SWD 0xE8 // SWD Command group header
127 #define CH347_CMD_SWD_REG_W 0xA0 // SWD Interface write reg
128 #define CH347_CMD_SWD_SEQ_W 0xA1 // SWD Interface write spec seq
129 #define CH347_CMD_SWD_REG_R 0xA2 // SWD Interface read reg
130 #define CH347_MAX_PROCESSING_US 7000 // max time in us for packet processing
131  // USB hosts disconnect the adapter if SWD processing takes more!
132 #define CH347_MAX_SEND_BUF USBC_PACKET_USBHS
133 #define CH347_MAX_RECV_BUF USBC_PACKET_USBHS
134 #define CH347_MAX_CMD_BUF 128
135 #define CH347_SWD_CLOCK_MAX 5000
136 #define CH347_SWD_CLOCK_BASE 1000
137 // limited by the longest sequence processing time
138 #define CH347_SWD_CLOCK_MAX_DIVISOR (CH347_MAX_PROCESSING_US / swd_seq_dormant_to_swd_len)
139 
140 #define CH347_EPOUT 0x06u // the usb endpoint number for writing
141 #define CH347_EPIN 0x86u // the usb endpoint number for reading
142 #define CH347T_MPHSI_INTERFACE 2 // the CH347T JTAG interface is number 2
143 #define CH347F_MPHSI_INTERFACE 4 // the CH347F JTAG interface is number 4
144 #define USB_WRITE_TIMEOUT 500 // write timeout in milliseconds
145 #define USB_READ_TIMEOUT 500 // read timeout in milliseconds
146 // BCD version for devices that can use bytewise mode below this version only bitwise mode can be used
147 #define BYTEWISE_MODE_VERSION 0x241
148 /* if the configuration is not setting the vendor id / product id we search for vendor id 1a86
149  and product id's 0x55dd (CH347T chip in mode 3), 0x55de (CH347F chip) and 0x55e7 (other chip) */
150 #define DEFAULT_VENDOR_ID 0x1a86
151 #define DEFAULT_CH347T_PRODUCT_ID 0x55dd
152 #define DEFAULT_CH347F_PRODUCT_ID 0x55de
153 #define DEFAULT_OTHER_PRODUCT_ID 0x55e7
154 
155 /* There are 3 different CH347 variants. The datasheet mentions the CH347T chip which has the product id 0x55dd
156  as default when it's configured to mode 3. The CH347F chip is also mentioned in the datasheet and has the
157  default product id 0x55de. The 3rd variant is not mentioned in a datasheet but was found here
158  https://github.com/WCHSoftGroup/ch347
159  The code from WCHSoftGroup is also searching for this product id */
161  CH347T = 0, // The CH347T chip
162  CH347F = 1, // The CH347F chip
163  OTHER_PRODUCT_ID = 2, // other product id not mentioned in the datasheet
164 };
165 
166 /* STANDARD_PACK means that we can send only one USBC_PACKET_USBHS-sized USB packet
167  and then read data back. LARGER_PACK means, we can send packets as large as
168  LARGER_PACK_MAX_SIZE. libusb splits there large packets into smaller USB packets and
169  transmit the data. Then we read back the data in a bigger packet. */
170 enum pack_size {
171  UNSET = -1,
174 };
175 
176 // for STANDARD_PACK mode: these are the 6 possible speeds; values in kHz
177 static const int ch347_standard_pack_clock_speeds[] = {
178  1875, // 1.875 MHz (60000 : 32)
179  3750, // 3.75 MHz (60000 : 16)
180  7500, // 7.5 MHz (60000 : 8)
181  15000, // 15 MHz (60000 : 4)
182  30000, // 30 MHz (60000 : 2)
183  60000 // 60 MHz
184 };
185 
186 // for LARGER_PACK mode: these are the 8 possible speeds; values in kHz
187 static const int ch347_larger_pack_clock_speeds[] = {
188  469, // 468.75 kHz (60000 : 128)
189  938, // 937.5 kHz (60000 : 64)
190  1875, // 1.875 MHz (60000 : 32)
191  3750, // 3.75 MHz (60000 : 16)
192  7500, // 7.5 MHz (60000 : 8)
193  15000, // 15 MHz (60000 : 4)
194  30000, // 30 MHz (60000 : 2)
195  60000 // 60 MHz
196 };
197 
198 struct ch347_cmd {
199  uint8_t type; // the command type
200  uint8_t *write_data; // data bytes for write
201  uint16_t write_data_len; // count of data bytes in the write_data buffer
202  uint16_t read_len; // if >0 a read is needed after this command
203  uint16_t tdo_bit_count; // how many TDO bits are needed to shift in by this read
204  struct list_head queue; // for handling a queue (list)
205 };
206 
207 struct ch347_scan {
208  struct scan_field *fields; // array of scan_field's for data from the device
209  int fields_len; // scan_fields array length
210  struct list_head queue; // for handling a queue (list)
211 };
212 
213 struct ch347_info {
214  // Record the CH347 pin status
215  int tms_pin;
216  int tdi_pin;
217  int tck_pin;
218  int trst_pin;
219 
220  enum ch347_variant chip_variant; // ch347_variant for explanation
221  // if true then we can't us the bytewise commands due to a bug of the chip; depends on BYTEWISE_MODE_VERSION
223  enum pack_size pack_size; // see: pack_size for explanation
224  int max_len; // in STANDARD_PACK or bitwise mode we can send only one USBC_PACKET_USBHS sized package
226 
227  // a "scratchpad" where we record all bytes for one command
228  uint8_t scratchpad_cmd_type; // command type
229  uint8_t scratchpad[UCMDPKT_DATA_MAX_BYTES_USBHS]; // scratchpad buffer
230  int scratchpad_idx; // current index in scratchpad
231 
232  // after a command is complete it will be stored for later processing
233  struct list_head cmd_queue;
234  // all data input scan fields are queued here
235  struct list_head scan_queue;
236  // read buffer for the single commands like CH347_CMD_GPIO and CH347_CMD_JTAG_INIT
238  int singe_read_len; // data length in single_read
239 };
240 
241 struct ch347_swd_io {
242  uint8_t usb_cmd; // 0xA0, 0xA1, 0xA2
243  uint8_t cmd;
244  uint32_t *dst;
245  uint32_t value;
246  struct list_head list_entry;
247 };
248 
252  int send_len;
253  int recv_len;
257  unsigned int clk_divisor;
258  unsigned int total_swd_clk;
259  struct list_head send_cmd_head;
260  struct list_head free_cmd_head;
262 };
263 
265 static bool swd_mode;
269 static uint8_t ch347_activity_led_gpio_pin = 0xFF;
271 // GPIO driving SRST in SWD mode, defaults to the otherwise unused TRST pin
272 static uint8_t ch347_srst_gpio_pin = 0xFF;
274 static struct ch347_info ch347;
275 static struct libusb_device_handle *ch347_handle;
276 
277 /* there are "single" commands. These commands can't be chained together and
278  need to be send as single command and need a read after write */
279 static inline bool ch347_is_single_cmd_type(uint8_t type)
280 {
282 }
283 
284 static void log_buf_dump(const uint8_t *data, unsigned int size, bool recv)
285 {
286  unsigned int i = 0, j = 0;
287  unsigned int n = size * 3 + 1;
288  char *str = malloc(n);
289  if (!str)
290  return;
291 
292  while (i < size && j < n) {
293  uint8_t cmd = data[i++];
294  hexify(str + j, &cmd, 1, n - j);
295  j += 2;
296  str[j++] = ' ';
297 
298  unsigned int cmd_payload_size = le_to_h_u16(data + i);
299  if (i + 2 <= size && j + 4 < n) {
300  hexify(str + j, data + i, 2, n - j);
301  i += 2;
302  j += 4;
303  str[j++] = ' ';
304  }
305 
306  if (cmd == CH347_CMD_SWD) {
307  // nested SWD commands
308  str[j] = '\0';
309  if (i + cmd_payload_size > size) {
310  LOG_DEBUG_IO("%s - bad size", str);
311  cmd_payload_size = size - i;
312  } else {
313  LOG_DEBUG_IO("%s", str);
314  }
315  j = 0;
316  unsigned int swd_base_i = i;
317 
318  while (i < swd_base_i + cmd_payload_size) {
319  uint8_t swd_cmd = data[i++];
320  hexify(str + j, &swd_cmd, 1, n - j);
321  j += 2;
322  str[j++] = ' ';
323 
324  unsigned int swd_bits = 0;
325  unsigned int swd_payload_size = 0;
326  if (!recv) {
327  if (i + 2 <= size) {
328  swd_bits = le_to_h_u16(data + i);
329  hexify(str + j, data + i, 2, n - j);
330  i += 2;
331  j += 4;
332  str[j++] = ' ';
333  }
334  }
335 
336  switch (swd_cmd) {
337  case CH347_CMD_SWD_REG_W:
338  if (recv)
339  swd_payload_size = 1;
340  else
341  swd_payload_size = DIV_ROUND_UP(swd_bits, 8);
342  break;
343  case CH347_CMD_SWD_SEQ_W:
344  if (!recv)
345  swd_payload_size = DIV_ROUND_UP(swd_bits, 8);
346  break;
347  case CH347_CMD_SWD_REG_R:
348  if (recv)
349  swd_payload_size = 1 + 4 + 1;
350  else
351  swd_payload_size = 1;
352  break;
353  }
354 
355  hexify(str + j, data + i, MIN(swd_payload_size, size - i), n - j);
356  i += swd_payload_size;
357  j += 2 * swd_payload_size;
358  str[j] = '\0';
359  if (i > size)
360  LOG_DEBUG_IO(" %s - bad size", str);
361  else
362  LOG_DEBUG_IO(" %s", str);
363  j = 0;
364  }
365  } else {
366  hexify(str + j, data + i, MIN(cmd_payload_size, size - i), n - j);
367  i += cmd_payload_size;
368  j += 2 * cmd_payload_size;
369  str[j] = '\0';
370  if (i > size)
371  LOG_DEBUG_IO("%s - bad size", str);
372  else
373  LOG_DEBUG_IO("%s", str);
374  j = 0;
375  }
376  }
377  free(str);
378 }
379 
387 static int ch347_write_data(uint8_t *data, int *length)
388 {
389  int write_len = *length;
390  int i = 0;
391  int transferred = 0;
392 
393  while (true) {
394  int retval = jtag_libusb_bulk_write(ch347_handle, CH347_EPOUT, (char *)&data[i],
395  write_len, USB_WRITE_TIMEOUT, &transferred);
396  if (retval != ERROR_OK) {
397  LOG_ERROR("CH347 write fail");
398  *length = 0;
399  return retval;
400  }
401  i += transferred;
402  if (i >= *length)
403  break;
404  write_len = *length - i;
405  }
406 
408  LOG_DEBUG_IO("size=%d, buf=", i);
409  log_buf_dump(data, i, false);
410  }
411 
412  *length = i;
413  return ERROR_OK;
414 }
415 
423 static int ch347_read_data(uint8_t *data, int *length)
424 {
425  int read_len = *length;
426  int i = 0;
427  int transferred = 0;
428 
429  while (true) {
430  int retval = jtag_libusb_bulk_read(ch347_handle, CH347_EPIN, (char *)&data[i],
431  read_len, USB_READ_TIMEOUT, &transferred);
432  if (retval != ERROR_OK) {
433  LOG_ERROR("CH347 read fail");
434  *length = 0;
435  return retval;
436  }
437 
438  i += transferred;
439  if (i >= *length)
440  break;
441  read_len = *length - i;
442  }
443 
445  LOG_DEBUG_IO("size=%d, buf=", i);
446  log_buf_dump(data, i, true);
447  }
448 
449  *length = i;
450  return ERROR_OK;
451 }
452 
459 static void ch347_cmd_calc_reads(struct ch347_cmd *cmd)
460 {
461  cmd->read_len = 0;
462  cmd->tdo_bit_count = 0;
463 
464  switch (cmd->type) {
465  case CH347_CMD_GPIO:
466  // for GPIO we need to read back the same amount of data that we had send
467  cmd->read_len = cmd->write_data_len;
468  break;
469  case CH347_CMD_JTAG_INIT:
470  case CH347_CMD_SWD_INIT:
471  // for JTAG_INIT/SWD_INIT the amount is fixed
472  cmd->read_len = CH347_CMD_INIT_READ_LEN;
473  break;
475  // for bit operations we need to count the TCK high edges
476  for (int i = 0; i < cmd->write_data_len; i++) {
477  if ((cmd->write_data[i] & TCK_H) == TCK_H) {
478  cmd->read_len++;
479  cmd->tdo_bit_count++;
480  }
481  }
482  break;
484  // for byte operations: need to read one byte back for each data byte
485  cmd->read_len = cmd->write_data_len;
486  // we occupy 8 bits per byte in the TDO hardware buffer
487  cmd->tdo_bit_count = cmd->read_len * 8;
488  break;
489  }
490 }
491 
500 {
501  // nothing to do if no bytes are recorded
502  if (!ch347.scratchpad_idx)
503  return ERROR_OK;
504 
505  // malloc for the command and data bytes
506  struct ch347_cmd *cmd = malloc(sizeof(struct ch347_cmd));
507  if (cmd)
508  cmd->write_data = malloc(ch347.scratchpad_idx);
509  if (!cmd || !cmd->write_data) {
510  LOG_ERROR("malloc failed");
511  free(cmd);
512  return ERROR_FAIL;
513  }
514 
515  // copy data, calculate the reads and add to the command queue
516  cmd->type = ch347.scratchpad_cmd_type;
517  cmd->write_data_len = ch347.scratchpad_idx;
518  memcpy(cmd->write_data, ch347.scratchpad, ch347.scratchpad_idx);
520  list_add_tail(&cmd->queue, &ch347.cmd_queue);
521 
522  // cleanup the scratchpad for the next command
524  ch347.scratchpad_idx = 0;
525  return ERROR_OK;
526 }
527 
537 static int ch347_read_scan(uint8_t *decoded_buf, int decoded_buf_len, int raw_read_len)
538 {
539  int read_len = raw_read_len;
540  uint8_t *read_buf = malloc(read_len);
541  if (!read_buf) {
542  LOG_ERROR("malloc failed");
543  return ERROR_FAIL;
544  }
545 
546  int retval = ch347_read_data(read_buf, &read_len);
547  if (retval != ERROR_OK) {
548  free(read_buf);
549  return retval;
550  }
551 
552  int rd_idx = 0;
553  int decoded_buf_idx = 0;
554 
555  while (rd_idx < read_len) {
556  unsigned int type = read_buf[rd_idx++];
557  uint16_t data_len = le_to_h_u16(&read_buf[rd_idx]);
558  rd_idx += 2;
559  if (decoded_buf_idx > decoded_buf_len) {
560  LOG_ERROR("CH347 decoded_buf too small");
561  free(read_buf);
562  return ERROR_FAIL;
563  }
564 
565  // nothing to decode? Only read to make the CH347 happy!
566  if (!decoded_buf) {
567  rd_idx += data_len;
568  continue;
569  }
570 
571  switch (type) {
572  case CH347_CMD_GPIO:
573  case CH347_CMD_JTAG_INIT:
574  case CH347_CMD_SWD_INIT:
576  // for all bytewise commands: copy the data bytes
577  memcpy(&decoded_buf[decoded_buf_idx], &read_buf[rd_idx], data_len);
578  decoded_buf_idx += data_len;
579  rd_idx += data_len;
580  break;
582  // for CH347_CMD_JTAG_BIT_OP_RD we need to copy bit by bit
583  for (int i = 0; i < data_len; i++) {
584  if (read_buf[rd_idx + i] & BIT(0))
585  decoded_buf[decoded_buf_idx + i / 8] |= BIT(i % 8);
586  else
587  decoded_buf[decoded_buf_idx + i / 8] &= ~(BIT(i % 8));
588  }
589  rd_idx += data_len;
590  decoded_buf_idx += DIV_ROUND_UP(data_len, 8);
591  break;
592  default:
593  LOG_ERROR("CH347 read command fail");
594  free(read_buf);
595  return ERROR_FAIL;
596  }
597  }
598 
599  free(read_buf);
600  return ERROR_OK;
601 }
602 
610 static int ch347_scan_data_to_fields(uint8_t *decoded_buf, int decoded_buf_len)
611 {
612  int byte_offset = 0;
613  struct ch347_scan *scan;
614  struct ch347_scan *tmp;
615  int bit_offset = 0;
617  for (int i = 0; i < scan->fields_len; i++) {
618  int num_bits = scan->fields[i].num_bits;
619  LOG_DEBUG("fields[%d].in_value[%d], read from bit offset: %d", i, num_bits, bit_offset);
620  // only if we need the value
621  if (scan->fields[i].in_value) {
622  uint8_t *capture_buf = malloc(DIV_ROUND_UP(num_bits, 8));
623  if (!capture_buf) {
624  LOG_ERROR("malloc failed");
625  return ERROR_FAIL;
626  }
627  uint8_t *captured = buf_set_buf(decoded_buf, bit_offset, capture_buf, 0, num_bits);
628 
630  char *str = buf_to_hex_str(captured, num_bits);
631  LOG_DEBUG_IO("size=%d, buf=[%s]", num_bits, str);
632  free(str);
633  }
634 
635  buf_cpy(captured, scan->fields[i].in_value, num_bits);
636  free(capture_buf);
637  } else {
639  LOG_DEBUG_IO("field skipped");
640  }
641  bit_offset += num_bits;
642  }
643  list_del(&scan->queue);
644  free(scan);
645  /* after one round of scan field processing the
646  next data bits are read from the next data byte
647  => round up and calculate the next start bit */
648  byte_offset = DIV_ROUND_UP(bit_offset, 8);
649  bit_offset = byte_offset * 8;
650  }
651 
652  // if not all bytes are transferred: put the rest into single_read buffer
653  if (byte_offset < decoded_buf_len) {
654  ch347.singe_read_len = decoded_buf_len - byte_offset;
655  LOG_DEBUG("single read of %d bytes", ch347.singe_read_len);
657  LOG_ERROR("Can't read more than %d bytes for a single command!", CH347_SINGLE_CMD_MAX_READ);
659  }
660  memcpy(ch347.single_read, &decoded_buf[byte_offset], ch347.singe_read_len);
661  }
662 
663  return ERROR_OK;
664 }
665 
672 static int ch347_cmd_transmit_queue(void)
673 {
674  // queue last command
675  int retval = ch347_cmd_from_scratchpad();
676  if (retval != ERROR_OK)
677  return retval;
678 
679  // nothing to do! => done here
680  if (list_empty(&ch347.cmd_queue))
681  return ERROR_OK;
682 
683  // calculate the needed buffer length for all decoded bytes
684  struct ch347_cmd *cmd;
685  int decoded_buf_len = 0;
687  if (cmd->read_len > 0)
688  decoded_buf_len += ch347_is_single_cmd_type(cmd->type) ?
689  cmd->read_len : DIV_ROUND_UP(cmd->tdo_bit_count, 8);
690 
691  // create the buffer for all decoded bytes
692  uint8_t *decoded_buf = NULL;
693  int decoded_buf_idx = 0;
694  if (decoded_buf_len > 0) {
695  decoded_buf = malloc(decoded_buf_len);
696  if (!decoded_buf) {
697  LOG_ERROR("malloc failed");
698  return ERROR_FAIL;
699  }
700  }
701 
702  while (!list_empty(&ch347.cmd_queue)) {
703  struct ch347_cmd *last_cmd = NULL;
704  int total_len = 0;
705  int total_tdo_count = 0;
706  int bytes_to_write = 0;
707 
709  total_len += CH347_CMD_HEADER + cmd->write_data_len;
710  total_tdo_count += cmd->tdo_bit_count;
711  // don't exceed max length or max TDO bit count
712  if (total_len >= ch347.max_len || total_tdo_count >= HW_TDO_BUF_SIZE)
713  break;
714  // remember the last cmd to send and bytes to send
715  last_cmd = cmd;
716  bytes_to_write = total_len;
717  }
718 
719  // sanity checks
720  if (!last_cmd || bytes_to_write == 0) {
721  LOG_ERROR("Nothing to send!");
722  free(decoded_buf);
723  return ERROR_FAIL;
724  }
725 
726  // create the write buffer
727  uint8_t *write_buf = malloc(bytes_to_write);
728  if (!write_buf) {
729  LOG_ERROR("malloc failed");
730  free(decoded_buf);
731  return ERROR_FAIL;
732  }
733 
734  int idx = 0;
735  int bytes_to_read = 0;
736  int current_decoded_buf_len = 0;
737  struct ch347_cmd *tmp;
738 
740  // copy command to buffer
741  write_buf[idx++] = cmd->type;
742  h_u16_to_le(&write_buf[idx], cmd->write_data_len);
743  idx += 2;
744  memcpy(&write_buf[idx], cmd->write_data, cmd->write_data_len);
745  idx += cmd->write_data_len;
746  // need to read something back?
747  if (cmd->read_len > 0) {
748  bytes_to_read += CH347_CMD_HEADER + cmd->read_len;
749  current_decoded_buf_len += ch347_is_single_cmd_type(cmd->type) ?
750  cmd->read_len : DIV_ROUND_UP(cmd->tdo_bit_count, 8);
751  }
752 
753  // cmd data no longer needed
754  list_del(&cmd->queue);
755  free(cmd->write_data);
756  free(cmd);
757 
758  if (cmd == last_cmd)
759  break;
760  }
761 
762  // write data to device
763  retval = ch347_write_data(write_buf, &idx);
764  free(write_buf);
765  if (retval != ERROR_OK) {
766  free(decoded_buf);
767  return retval;
768  }
769 
770  if (!bytes_to_read)
771  continue;
772 
773  // Need only to execute a read without decoding the data to make the CH347 happy?
774  if (!current_decoded_buf_len) {
775  // read but don't decode anything
776  retval = ch347_read_scan(NULL, 0, bytes_to_read);
777  } else {
778  retval = ch347_read_scan(&decoded_buf[decoded_buf_idx], current_decoded_buf_len, bytes_to_read);
779  decoded_buf_idx += current_decoded_buf_len;
780  }
781 
782  if (retval != ERROR_OK) {
783  free(decoded_buf);
784  return retval;
785  }
786  }
787 
788  // something decoded from the data read back from CH347?
789  if (decoded_buf) {
790  // put the decoded data into the scan fields or single_read buffer
791  retval = ch347_scan_data_to_fields(decoded_buf, decoded_buf_len);
792  free(decoded_buf);
793  }
794 
795  return retval;
796 }
797 
804 static int ch347_cmd_start_next(uint8_t type)
805 {
806  // different command type or non chainable command? (GPIO commands can't be concat)
807  uint8_t prev_type = ch347.scratchpad_cmd_type;
808  if (prev_type != type || ch347_is_single_cmd_type(type)) {
809  // something written in the scratchpad? => store it as command
810  if (prev_type != 0 && ch347.scratchpad_idx > 0) {
811  int retval = ch347_cmd_from_scratchpad();
812  if (retval != ERROR_OK)
813  return retval;
814 
815  /* if the last queued command is not chainable we should send it immediately
816  because e.g. the GPIO command can't be combined with any other command */
817  if (ch347_is_single_cmd_type(prev_type)) {
818  retval = ch347_cmd_transmit_queue();
819  if (retval != ERROR_OK)
820  return retval;
821  }
822  }
823 
824  /* before we can send non chainable command ("single" like GPIO command) we should send all
825  other commands because we can't send it together with other commands */
827  int retval = ch347_cmd_transmit_queue();
828  if (retval != ERROR_OK)
829  return retval;
830  }
831 
832  // store the next command type
834  }
835 
836  return ERROR_OK;
837 }
838 
846 static int ch347_scan_queue_fields(struct scan_field *scan_fields, int scan_fields_len)
847 {
848  // malloc for the scan struct
849  struct ch347_scan *scan = malloc(sizeof(struct ch347_scan));
850  if (!scan) {
851  LOG_ERROR("malloc failed");
852  return ERROR_FAIL;
853  }
854 
855  scan->fields = scan_fields;
856  scan->fields_len = scan_fields_len;
857  list_add_tail(&scan->queue, &ch347.scan_queue);
858  return ERROR_OK;
859 }
860 
869 static int ch347_single_read_get_byte(int read_buf_idx, uint8_t *byte)
870 {
871  int retval = ch347_cmd_transmit_queue();
872  if (retval != ERROR_OK)
873  return retval;
874 
875  if (read_buf_idx > CH347_SINGLE_CMD_MAX_READ || read_buf_idx < 0) {
876  LOG_ERROR("read_buf_idx out of range");
877  return ERROR_FAIL;
878  }
879 
880  *byte = ch347.single_read[read_buf_idx];
881  return ERROR_OK;
882 }
883 
889 {
890  // if full create a new command in the queue
892  uint8_t type = ch347.scratchpad_cmd_type;
895  }
896 }
897 
906 static int ch347_scratchpad_add_byte(uint8_t byte)
907 {
908  if (ch347.scratchpad_cmd_type == 0) {
909  LOG_ERROR("call ch347_next_cmd first!");
910  return ERROR_FAIL;
911  }
912 
915  return ERROR_OK;
916 }
917 
926 {
928 }
929 
940 static int ch347_scratchpad_add_bytes(uint8_t *bytes, int count)
941 {
942  if (ch347.scratchpad_cmd_type == 0) {
943  LOG_ERROR("call ch347_next_cmd first!");
944  return ERROR_FAIL;
945  }
946 
947  int remaining = count;
948  int bytes_idx = 0;
949  while (remaining > 0) {
950  int bytes_to_store = ch347.scratchpad_idx + remaining <= UCMDPKT_DATA_MAX_BYTES_USBHS ?
952 
953  if (bytes)
954  memcpy(&ch347.scratchpad[ch347.scratchpad_idx], &bytes[bytes_idx], bytes_to_store);
955  else
956  memset(&ch347.scratchpad[ch347.scratchpad_idx], 0, bytes_to_store);
957 
958  ch347.scratchpad_idx += bytes_to_store;
959  bytes_idx += bytes_to_store;
960  remaining -= bytes_to_store;
962  }
963 
964  return ERROR_OK;
965 }
966 
974 static int ch347_scratchpad_add_clock_tms(bool tms)
975 {
976  ch347.tms_pin = tms ? TMS_H : TMS_L;
977  ch347.tck_pin = TCK_L;
978  int retval = ch347_scratchpad_add_pin_byte();
979  if (retval != ERROR_OK)
980  return retval;
981 
982  ch347.tck_pin = TCK_H;
984 }
985 
993 {
994  if (ch347.scratchpad_cmd_type == 0) {
996  if (retval != ERROR_OK)
997  return retval;
998  }
999 
1000  bool tms = ch347.tms_pin == TMS_H;
1001  for (int i = 0; i < count; i++) {
1002  int retval = ch347_scratchpad_add_clock_tms(tms);
1003  if (retval != ERROR_OK)
1004  return retval;
1005  }
1006 
1007  return ERROR_OK;
1008 }
1009 
1016 {
1017  ch347.tck_pin = TCK_L;
1019 }
1020 
1029 static int ch347_scratchpad_add_tms_change(const uint8_t *tms_value, int step, int skip)
1030 {
1031  LOG_DEBUG_IO("TMS Value: %02x..., step = %d, skip = %d", tms_value[0], step, skip);
1032 
1034  if (retval != ERROR_OK)
1035  return retval;
1036 
1037  for (int i = skip; i < step; i++) {
1038  retval = ch347_scratchpad_add_clock_tms((tms_value[i / 8] >> (i % 8)) & BIT(0));
1039  if (retval != ERROR_OK)
1040  return retval;
1041  }
1042 
1044 }
1045 
1053 {
1054  LOG_DEBUG_IO("num_states=%d, last_state=%d", cmd->num_states, cmd->path[cmd->num_states - 1]);
1055 
1057  if (retval != ERROR_OK)
1058  return retval;
1059 
1060  for (unsigned int i = 0; i < cmd->num_states; i++) {
1061  if (tap_state_transition(tap_get_state(), false) == cmd->path[i]) {
1062  retval = ch347_scratchpad_add_clock_tms(0);
1063  if (retval != ERROR_OK)
1064  return retval;
1065  } else if (tap_state_transition(tap_get_state(), true) == cmd->path[i]) {
1066  retval = ch347_scratchpad_add_clock_tms(1);
1067  if (retval != ERROR_OK)
1068  return retval;
1069  } else {
1070  LOG_ERROR("No transition possible!");
1072  }
1073  tap_set_state(cmd->path[i]);
1074  }
1075 
1077 }
1078 
1087 {
1088  uint8_t tms_scan;
1089  int tms_len;
1090 
1092  // don't do anything if we are already in the right state; but do execute always the TAP_RESET
1093  if (tap_get_state() == state && state != TAP_RESET)
1094  return ERROR_OK;
1095 
1096  tms_scan = tap_get_tms_path(tap_get_state(), state);
1098  int retval = ch347_scratchpad_add_tms_change(&tms_scan, tms_len, skip);
1100  return retval;
1101 }
1102 
1112 static int ch347_scratchpad_add_write_read(struct scan_command *cmd, uint8_t *bits, int bits_len, enum scan_type scan)
1113 {
1114  // the bits and bytes to transfer
1115  int byte_count = bits_len / 8;
1116  int bit_count = bits_len % 8;
1117 
1118  // only bytes are not possible because we need to set TMS high for the last bit
1119  if (byte_count > 0 && bit_count == 0) {
1120  // make one byte to eight bits
1121  byte_count--;
1122  bit_count = 8;
1123  }
1124 
1125  // in bitwise mode only bits are allowed
1126  if (ch347.use_bitwise_mode) {
1127  byte_count = 0;
1128  bit_count = bits_len;
1129  }
1130 
1131  bool is_read = (scan == SCAN_IN || scan == SCAN_IO);
1132 
1133  // if we need to send bytes
1134  if (byte_count > 0) {
1135  // start the next cmd and copy the data out bytes to it
1137  if (retval != ERROR_OK)
1138  return retval;
1139 
1140  if (bits)
1141  retval = ch347_scratchpad_add_bytes(bits, byte_count);
1142  else
1143  retval = ch347_scratchpad_add_bytes(NULL, byte_count);
1144 
1145  if (retval != ERROR_OK)
1146  return retval;
1147  }
1148 
1149  // bits are always need to send; no possibility to not send bits
1151  if (retval != ERROR_OK)
1152  return retval;
1153 
1154  ch347.tms_pin = TMS_L;
1155  ch347.tdi_pin = TDI_L;
1156 
1157  for (int i = 0; i < bit_count; i++) {
1158  if (bits)
1159  ch347.tdi_pin = ((bits[byte_count + i / 8] >> i % 8) & BIT(0)) ? TDI_H : TDI_L;
1160 
1161  // for the last bit set TMS high to exit the shift state
1162  if (i + 1 == bit_count)
1163  ch347.tms_pin = TMS_H;
1164 
1165  ch347.tck_pin = TCK_L;
1166  retval = ch347_scratchpad_add_pin_byte();
1167  if (retval != ERROR_OK)
1168  return retval;
1169 
1170  ch347.tck_pin = TCK_H;
1171  retval = ch347_scratchpad_add_pin_byte();
1172  if (retval != ERROR_OK)
1173  return retval;
1174 
1175  /* cut the package after each MAX_BITS_PER_BIT_OP bits because it
1176  needs a dividable by 8 bits package */
1177  if (i > 0 && (i + 1) % MAX_BITS_PER_BIT_OP == 0) {
1178  retval = ch347_cmd_from_scratchpad();
1179  if (retval != ERROR_OK)
1180  return retval;
1181 
1183  if (retval != ERROR_OK)
1184  return retval;
1185  }
1186  }
1187 
1188  // one TCK_L after the last bit
1190  if (retval != ERROR_OK)
1191  return retval;
1192 
1193  // if read is involved we need to queue the scan fields
1194  if (is_read)
1195  return ch347_scan_queue_fields(cmd->fields, cmd->num_fields);
1196 
1197  return ERROR_OK;
1198 }
1199 
1207 static int ch347_scratchpad_add_run_test(int cycles, enum tap_state state)
1208 {
1209  LOG_DEBUG_IO("cycles=%d, end_state=%d", cycles, state);
1210  int retval;
1211  if (tap_get_state() != TAP_IDLE) {
1213  if (retval != ERROR_OK)
1214  return retval;
1215  }
1216 
1217  retval = ch347_scratchpad_add_stableclocks(cycles);
1218  if (retval != ERROR_OK)
1219  return retval;
1220 
1222 }
1223 
1231 {
1232  static const char *const type2str[] = {"", "SCAN_IN", "SCAN_OUT", "SCAN_IO"};
1233 
1234  enum scan_type type = jtag_scan_type(cmd);
1235  uint8_t *buf = NULL;
1236  int scan_bits = jtag_build_buffer(cmd, &buf);
1237 
1238  // add a move to IRSHIFT or DRSHIFT state
1239  int retval;
1240  if (cmd->ir_scan)
1242  else
1244 
1245  if (retval != ERROR_OK) {
1246  free(buf);
1247  return retval;
1248  }
1249 
1251  char *log_buf = buf_to_hex_str(buf, scan_bits);
1252  LOG_DEBUG_IO("scan=%s, type=%s, bits=%d, buf=[%s], end_state=%d",
1253  cmd->ir_scan ? "IRSCAN" : "DRSCAN",
1254  type2str[type],
1255  scan_bits, log_buf, cmd->end_state);
1256  free(log_buf);
1257  }
1258 
1259  retval = ch347_scratchpad_add_write_read(cmd, buf, scan_bits, type);
1260  free(buf);
1261  if (retval != ERROR_OK)
1262  return retval;
1263 
1264  // add a move to the final state
1265  return ch347_scratchpad_add_move_state(cmd->end_state, 1);
1266 }
1267 
1273 static uint8_t ch347_usable_gpios(void)
1274 {
1276 }
1277 
1291 static int ch347_gpio_cmd(unsigned int gpio, uint8_t value, uint8_t *state)
1292 {
1293  if (gpio >= GPIO_CNT) {
1294  LOG_ERROR("GPIO %u out of range", gpio);
1295  return ERROR_FAIL;
1296  }
1297 
1298  int retval = ch347_cmd_start_next(CH347_CMD_GPIO);
1299  if (retval != ERROR_OK)
1300  return retval;
1301 
1302  uint8_t gpios[GPIO_CNT];
1303  memset(gpios, 0, GPIO_CNT);
1304  gpios[gpio] = value;
1306  if (retval != ERROR_OK)
1307  return retval;
1308 
1309  return ch347_single_read_get_byte(gpio, state);
1310 }
1311 
1323 static uint8_t ch347_gpio_drive_value(bool level, enum adapter_gpio_drive_mode drive)
1324 {
1325  switch (drive) {
1327  return level ? GPIO_SET_INPUT : GPIO_SET_L;
1329  return level ? GPIO_SET_H : GPIO_SET_INPUT;
1331  break;
1332  }
1333 
1334  return level ? GPIO_SET_H : GPIO_SET_L;
1335 }
1336 
1344 static int ch347_gpio_set(int gpio, bool data)
1345 {
1346  /* always set bits 7 and 6 for GPIO enable
1347  bits 5 and 4 for pin direction output
1348  bit 3 is the data bit */
1349  uint8_t state;
1350  int retval = ch347_gpio_cmd(gpio, data ? GPIO_SET_H : GPIO_SET_L, &state);
1351  if (retval != ERROR_OK)
1352  return retval;
1353 
1354  // check in the read if the bit is set/cleared correctly
1355  if ((bool)(state & BIT(6)) != data) {
1356  LOG_ERROR("Output not set.");
1357  return ERROR_FAIL;
1358  }
1359 
1360  return ERROR_OK;
1361 }
1362 
1369 static int ch347_activity_led_set(int led_state)
1370 {
1371  if (ch347_activity_led_gpio_pin != 0xFF)
1372  return ch347_gpio_set(ch347_activity_led_gpio_pin, ch347_activity_led_active_high ? led_state : 1 - led_state);
1373 
1374  // not configured => also OK
1375  return ERROR_OK;
1376 }
1377 
1391 static int ch347_reset(int trst, int srst)
1392 {
1393  LOG_DEBUG_IO("reset trst: %i srst %i", trst, srst);
1394 
1395  if (swd_mode) {
1396  if (trst)
1397  LOG_WARNING("Asserting TRST not supported in SWD mode!");
1398 
1399  if (ch347_srst_gpio_pin == 0xFF) {
1400  if (srst) {
1401  LOG_ERROR("Asserting SRST not supported: no usable GPIO configured");
1402  return ERROR_FAIL;
1403  }
1404  return ERROR_OK;
1405  }
1406 
1407  /* Honour the drive mode of 'reset_config'. It defaults to open drain,
1408  which releases the pin instead of driving the inactive level, so the
1409  target can keep the line low on its own.
1410  Don't verify the readback: it reports the pin level, and the target
1411  is free to hold the reset line low itself, e.g. while it is in a
1412  watchdog reset loop. */
1413  bool level = srst ? ch347_srst_active_high : !ch347_srst_active_high;
1414  uint8_t value = ch347_gpio_drive_value(level,
1416  uint8_t state;
1417  return ch347_gpio_cmd(ch347_srst_gpio_pin, value, &state);
1418  }
1419 
1420  if (srst) {
1421  LOG_ERROR("Asserting SRST not supported");
1422  return ERROR_FAIL;
1423  }
1424 
1426  if (retval != ERROR_OK)
1427  return retval;
1428 
1429  ch347.trst_pin = trst ? TRST_L : TRST_H;
1430  retval = ch347_scratchpad_add_pin_byte();
1431  if (retval != ERROR_OK)
1432  return retval;
1433 
1435  if (retval != ERROR_OK)
1436  return retval;
1437 
1438  return ch347_cmd_transmit_queue();
1439 }
1440 
1447 static int ch347_sleep(int us)
1448 {
1449  LOG_DEBUG_IO("us=%d", us);
1450  int retval = ch347_cmd_transmit_queue();
1451  jtag_sleep(us);
1452  return retval;
1453 }
1454 
1460 static int ch347_execute_queue(struct jtag_command *cmd_queue)
1461 {
1462  struct jtag_command *cmd = cmd_queue;
1463 
1464  int retval = ch347_activity_led_set(LED_ON);
1465  if (retval != ERROR_OK)
1466  return retval;
1467 
1468  while (retval == ERROR_OK && cmd) {
1469  switch (cmd->type) {
1470  case JTAG_RUNTEST:
1471  retval = ch347_scratchpad_add_run_test(cmd->cmd.runtest->num_cycles, cmd->cmd.runtest->end_state);
1472  break;
1473  case JTAG_STABLECLOCKS:
1474  retval = ch347_scratchpad_add_stableclocks(cmd->cmd.stableclocks->num_cycles);
1475  break;
1476  case JTAG_TLR_RESET:
1477  retval = ch347_scratchpad_add_move_state(cmd->cmd.statemove->end_state, 0);
1478  break;
1479  case JTAG_PATHMOVE:
1480  retval = ch347_scratchpad_add_move_path(cmd->cmd.pathmove);
1481  break;
1482  case JTAG_TMS:
1483  retval = ch347_scratchpad_add_tms_change(cmd->cmd.tms->bits, cmd->cmd.tms->num_bits, 0);
1484  break;
1485  case JTAG_SLEEP:
1486  retval = ch347_sleep(cmd->cmd.sleep->us);
1487  break;
1488  case JTAG_SCAN:
1489  retval = ch347_scratchpad_add_scan(cmd->cmd.scan);
1490  break;
1491  default:
1492  LOG_ERROR("BUG: unknown JTAG command type 0x%X", cmd->type);
1493  retval = ERROR_FAIL;
1494  break;
1495  }
1496 
1497  cmd = cmd->next;
1498  }
1499 
1500  if (retval != ERROR_OK)
1501  return retval;
1502 
1503  retval = ch347_cmd_transmit_queue();
1504  if (retval != ERROR_OK)
1505  return retval;
1506 
1508 }
1509 
1515 static int ch347_open_device(void)
1516 {
1517  const uint16_t *ch347_vids = default_ch347_vids;
1518  const uint16_t *ch347_pids = default_ch347_pids;
1519 
1520  if (adapter_usb_get_vids()[0] != 0) {
1521  ch347_vids = adapter_usb_get_vids();
1522  ch347_pids = adapter_usb_get_pids();
1523  }
1524 
1525  int retval = jtag_libusb_open(ch347_vids, ch347_pids,
1527  if (retval != ERROR_OK) {
1528  char error_message[256];
1529  snprintf(error_message, sizeof(error_message), "CH347 not found. Tried VID/PID pairs: ");
1530  for (int i = 0; ch347_vids[i] != 0; i++)
1531  snprintf(error_message + strlen(error_message), sizeof(error_message) - strlen(error_message),
1532  "%04x:%04x ", ch347_vids[i], ch347_pids[i]);
1533 
1534  LOG_ERROR("%s", error_message);
1535  return retval;
1536  }
1537 
1538  struct libusb_device_descriptor ch347_device_descriptor;
1539  libusb_device *device = libusb_get_device(ch347_handle);
1540  if (!device) {
1541  LOG_ERROR("CH347 error calling libusb_get_device");
1543  return ERROR_FAIL;
1544  }
1545 
1546  retval = libusb_get_device_descriptor(device, &ch347_device_descriptor);
1547  if (retval != ERROR_OK) {
1548  LOG_ERROR("CH347 error getting device descriptor: %s", libusb_error_name(retval));
1550  return retval;
1551  }
1552 
1553  // Fix for CH347F on ARM64
1554  // Force set configuration 1 (required on some ARM64 platforms)
1555  retval = libusb_set_configuration(ch347_handle, 1);
1556  if (retval != LIBUSB_SUCCESS && retval != LIBUSB_ERROR_BUSY)
1557  LOG_WARNING("CH347 set_configuration failed: %s", libusb_error_name(retval));
1558 
1559  // CH347T / CH347F detection
1560  // if we can claim interface 4 we found a CH347F chip; if we can claim interface 2 we found CH347T chip
1561  retval = libusb_claim_interface(ch347_handle, CH347F_MPHSI_INTERFACE);
1562  if (retval != ERROR_OK) {
1563  retval = libusb_claim_interface(ch347_handle, CH347T_MPHSI_INTERFACE);
1564  if (retval != ERROR_OK) {
1565  LOG_ERROR("CH347 unable to claim interface: %s", libusb_error_name(retval));
1567  return retval;
1568  }
1570  } else {
1572  }
1573 
1574  char firmware_version;
1576  LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
1577  VENDOR_VERSION, 0, 0, &firmware_version, sizeof(firmware_version),
1579  if (retval != ERROR_OK) {
1580  LOG_ERROR("CH347 unable to get firmware version");
1582  return retval;
1583  }
1584 
1585  char manufacturer[256 + 1];
1586  if (libusb_get_string_descriptor_ascii(ch347_handle, ch347_device_descriptor.iManufacturer,
1587  (unsigned char *)manufacturer, sizeof(manufacturer) - 1) < 0) {
1588  strcpy(manufacturer, "(unknown)");
1589  }
1590  char product[256 + 1];
1591  if (libusb_get_string_descriptor_ascii(ch347_handle, ch347_device_descriptor.iProduct,
1592  (unsigned char *)product, sizeof(product) - 1) < 0) {
1593  strcpy(product, "(unknown)");
1594  }
1595  char serial_number[256 + 1];
1596  if (libusb_get_string_descriptor_ascii(ch347_handle, ch347_device_descriptor.iSerialNumber,
1597  (unsigned char *)serial_number, sizeof(serial_number) - 1) < 0) {
1598  strcpy(serial_number, "(unknown)");
1599  }
1600 
1601  LOG_INFO("CH347 %s from vendor %s with serial number %s found. (Chip version=%X.%2X, Firmware=0x%02X)",
1602  product,
1603  manufacturer,
1604  serial_number,
1605  (ch347_device_descriptor.bcdDevice >> 8) & 0xFF,
1606  ch347_device_descriptor.bcdDevice & 0xFF,
1607  firmware_version);
1608 
1609  if (ch347.chip_variant == CH347T && ch347_device_descriptor.bcdDevice < BYTEWISE_MODE_VERSION) {
1610  LOG_INFO("CH347T old version of the chip, JTAG only working in bitwise mode. For bytewise mode at least version %X.%X is needed.",
1611  (BYTEWISE_MODE_VERSION >> 8) & 0xFF,
1612  BYTEWISE_MODE_VERSION & 0xFF);
1613  ch347.use_bitwise_mode = true;
1614  } else {
1615  ch347.use_bitwise_mode = false;
1616  }
1617 
1618  if (ch347.chip_variant == CH347T) {
1619  if (swd_mode) {
1620  ch347.swclk_5mhz_supported = ch347_device_descriptor.bcdDevice >= 0x544;
1621 
1622  if (ch347_device_descriptor.bcdDevice < 0x441)
1623  LOG_WARNING("CH347T version older than 4.41 probably does not support SWD transport");
1624 
1625  if (ch347_device_descriptor.bcdDevice == 0x441)
1626  LOG_WARNING("If CH347T version 4.41 cannot connect or SWD fails often, insert a resistor to SWDIO circuit");
1627 
1628  } else if (ch347_device_descriptor.bcdDevice == 0x241) {
1629  LOG_WARNING("CH347T version 2.41 has very weird clock timing, may not work with a slower JTAG device");
1630  }
1631 
1632  if (ch347_device_descriptor.bcdDevice < 0x544)
1633  LOG_INFO("Please upgrade CH347T firmware to a production version >= 5.44");
1634 
1635  } else if (ch347.chip_variant == CH347F) {
1636  ch347.swclk_5mhz_supported = ch347_device_descriptor.bcdDevice >= 0x101;
1637 
1638  if (ch347_device_descriptor.bcdDevice < 0x101)
1639  LOG_INFO("Please upgrade CH347F firmware to a production version >= 1.1");
1640  }
1641 
1642  return ERROR_OK;
1643 }
1644 
1650 static int ch347_quit(void)
1651 {
1652  // on close set the LED on, because the state without JTAG is on
1654  int retval = ch347_cmd_transmit_queue();
1656  LOG_DEBUG_IO("CH347 close");
1657  return retval;
1658 }
1659 
1671 static int ch347_adapter_init(uint8_t clock_index, bool *supports_larger_pack_mode)
1672 {
1674  if (retval != ERROR_OK)
1675  return retval;
1676 
1677  retval = ch347_scratchpad_add_byte(0);
1678  if (retval != ERROR_OK)
1679  return retval;
1680 
1681  retval = ch347_scratchpad_add_byte(clock_index);
1682  if (retval != ERROR_OK)
1683  return retval;
1684 
1685  for (int i = 0; i < 4; i++) {
1686  retval = ch347_scratchpad_add_pin_byte();
1687  if (retval != ERROR_OK)
1688  return retval;
1689  }
1690 
1691  uint8_t mode;
1692  retval = ch347_single_read_get_byte(0, &mode);
1693  if (retval != ERROR_OK)
1694  return retval;
1695 
1696  *supports_larger_pack_mode = mode != 0;
1697  return ERROR_OK;
1698 }
1699 
1708 static int ch347_adapter_supports_larger_pack_mode(bool *supports_larger_pack_mode)
1709 {
1710  return ch347_adapter_init(CH347_CMD_INIT_GET_MODE_CLOCK_INDEX_VALUE, supports_larger_pack_mode);
1711 }
1712 
1720 static int ch347_adapter_set_speed(uint8_t clock_index)
1721 {
1722  bool unused;
1723  return ch347_adapter_init(clock_index, &unused);
1724 }
1725 
1732 static int ch347_swd_init_cmd(uint8_t clock_divisor)
1733 {
1735  if (retval != ERROR_OK)
1736  return retval;
1737 
1738  uint8_t cmd_data[] = {0x40, 0x42, 0x0f, 0x00, clock_divisor, 0x00, 0x00, 0x00 };
1739  retval = ch347_scratchpad_add_bytes(cmd_data, ARRAY_SIZE(cmd_data));
1740  if (retval != ERROR_OK)
1741  return retval;
1742 
1743  /* TODO: CH347_CMD_SWD_INIT reads one data byte.
1744  But how can we decide if SWD init was successfully executed?
1745  Return an error code if init was failed */
1746  uint8_t init_result = 0;
1747  retval = ch347_single_read_get_byte(0, &init_result);
1748  LOG_DEBUG("SWD init clk div %" PRIu8 ", result %02" PRIx8,
1749  clock_divisor, init_result);
1750  ch347_swd_context.clk_divisor = clock_divisor;
1751  return retval;
1752 }
1753 
1760 static int ch347_speed_set(int speed_index)
1761 {
1762  if (swd_mode)
1763  return ch347_swd_init_cmd(speed_index);
1764 
1765  int retval = ch347_adapter_set_speed(speed_index);
1766  if (retval != ERROR_OK) {
1767  LOG_ERROR("Couldn't set CH347 speed");
1768  return retval;
1769  }
1770 
1771  return ERROR_OK;
1772 }
1773 
1779 static int ch347_init_pack_size(void)
1780 {
1781  // already set?
1782  if (ch347.pack_size != UNSET)
1783  return ERROR_OK;
1784 
1785  // set the lower limit for starting
1787  bool supports_larger_pack_mode;
1788  int retval = ch347_adapter_supports_larger_pack_mode(&supports_larger_pack_mode);
1789  if (retval != ERROR_OK)
1790  return retval;
1791 
1792  ch347.pack_size = supports_larger_pack_mode ? LARGER_PACK : STANDARD_PACK;
1795  return ERROR_OK;
1796 }
1797 
1805 static int ch347_speed_get(int speed_idx, int *khz)
1806 {
1807  if (swd_mode) {
1808  if (speed_idx)
1809  *khz = DIV_ROUND_UP(CH347_SWD_CLOCK_BASE, speed_idx);
1810  else
1811  *khz = CH347_SWD_CLOCK_MAX;
1812  return ERROR_OK;
1813  }
1814 
1815  int retval = ch347_init_pack_size();
1816  if (retval != ERROR_OK)
1817  return retval;
1818  const int *speeds = ch347.pack_size == STANDARD_PACK ?
1820  *khz = speeds[speed_idx];
1821  return ERROR_OK;
1822 }
1823 
1831 static int ch347_speed_get_index(int khz, int *speed_idx)
1832 {
1833  if (khz == 0) {
1834  LOG_ERROR("Adaptive clocking not supported");
1835  return ERROR_FAIL;
1836  }
1837 
1838  if (swd_mode) {
1840  *speed_idx = 0;
1841  } else {
1842  // Don't allow too low clk speeds: packet processing is limited to ~8 msec
1843  // or triggers host USB disconnect
1844  *speed_idx = MIN(DIV_ROUND_UP(CH347_SWD_CLOCK_BASE, khz),
1846  }
1847  return ERROR_OK;
1848  }
1849 
1850  // when checking with speed index 9 we can see if the device supports STANDARD_PACK or LARGER_PACK mode
1851  int retval = ch347_init_pack_size();
1852  if (retval != ERROR_OK)
1853  return retval;
1854  // depending on pack size there are different fixed clock speeds possible
1855  const int *speeds = ch347.pack_size == STANDARD_PACK ?
1857  int length = ch347.pack_size == STANDARD_PACK ?
1859  int idx = -1;
1860  int lower_bound = 0;
1861  // find the suitable speed index
1862  for (int i = 0; i < length; i++) {
1863  if (khz >= lower_bound && khz <= speeds[i]) {
1864  idx = i;
1865  break;
1866  }
1867  lower_bound = speeds[i];
1868  }
1869  // too high! => use max possible speed
1870  if (idx == -1) {
1871  LOG_INFO("Speed %d kHz is higher than highest speed of %d kHz. Using %d khz!",
1872  khz, speeds[length - 1], speeds[length - 1]);
1873  idx = length - 1;
1874  } else if (speeds[idx] != khz) {
1875  LOG_INFO("Requested speed of %d kHz is not possible. Using the next higher speed of %d kHz!",
1876  khz, speeds[idx]);
1877  }
1878  *speed_idx = idx;
1879  return ERROR_OK;
1880 }
1881 
1882 static const struct command_registration ch347_command_handlers[] = {
1883  {
1884  .name = "ch347",
1885  .mode = COMMAND_ANY,
1886  .help = "perform ch347 management",
1887  .usage = "",
1888  },
1890 };
1891 
1901 static void ch347_configure_activity_led(const struct adapter_gpio_config *led_config)
1902 {
1903  uint8_t gpio = led_config->gpio_num;
1904  if (gpio >= GPIO_CNT || (BIT(gpio) & ch347_usable_gpios()) == 0)
1905  return;
1906 
1909 }
1910 
1922 static void ch347_configure_srst_gpio(const struct adapter_gpio_config *srst_config)
1923 {
1924  ch347_srst_active_high = !srst_config->active_low;
1925 
1926  unsigned int gpio;
1927  if (srst_config->gpio_num == ADAPTER_GPIO_NOT_SET) {
1928  // the TRST pin is free in SWD mode, so use it by default
1930  } else {
1931  gpio = srst_config->gpio_num;
1932  if (gpio >= GPIO_CNT || (BIT(gpio) & ch347_usable_gpios()) == 0) {
1933  LOG_ERROR("GPIO %u can't be used for SRST, disabling SRST", gpio);
1934  ch347_srst_gpio_pin = 0xFF;
1935  return;
1936  }
1937  }
1938 
1939  /* Driving the same pin from two functions would let the LED activity
1940  toggle the reset line, so refuse to share it. */
1941  if (gpio == ch347_activity_led_gpio_pin) {
1942  LOG_ERROR("GPIO %u is already used as the activity LED, disabling SRST", gpio);
1943  ch347_srst_gpio_pin = 0xFF;
1944  return;
1945  }
1946 
1947  ch347_srst_gpio_pin = gpio;
1948 }
1949 
1955 static int ch347_init(void)
1956 {
1957  int retval = ch347_open_device();
1958 
1959  if (retval != ERROR_OK) {
1960  LOG_ERROR("CH347 open error");
1961  return retval;
1962  }
1963 
1964  LOG_DEBUG_IO("CH347 open success");
1965 
1966  // CH347 JTAG init
1967  ch347.tck_pin = TCK_L;
1968  ch347.tms_pin = TMS_H;
1969  ch347.tdi_pin = TDI_L;
1970  ch347.trst_pin = TRST_H;
1973 
1974  ch347.pack_size = UNSET;
1975 
1977 
1978  if (!swd_mode) {
1980  } else {
1982 
1983  retval = ch347_init_pack_size();
1984  if (retval != ERROR_OK)
1985  return retval;
1986 
1987  retval = ch347_swd_init_cmd(1);
1988  }
1989  return retval;
1990 }
1991 
1997 static int ch347_swd_init(void)
1998 {
1999  LOG_INFO("CH347 SWD mode enabled");
2000  swd_mode = true;
2001  memset(&ch347_swd_context, 0, sizeof(ch347_swd_context));
2002 
2005 
2007  // 0XE8 + 2byte len + N byte cmds
2009  // 0XE8 + 2byte len + N byte ack + data
2011  struct ch347_swd_io *pswd_io = ch347_swd_context.ch347_cmd_buf;
2012  for (int i = 0; i < CH347_MAX_CMD_BUF; i++, pswd_io++) {
2013  INIT_LIST_HEAD(&pswd_io->list_entry);
2015  }
2016  return ERROR_OK;
2017 }
2018 
2020 {
2021  struct ch347_swd_io *pswd_io;
2023  return NULL;
2024 
2026  struct ch347_swd_io, list_entry);
2027  list_del_init(&pswd_io->list_entry);
2028  pswd_io->cmd = 0;
2029  pswd_io->usb_cmd = CH347_CMD_SWD_SEQ_W;
2030  pswd_io->dst = NULL;
2031  return pswd_io;
2032 }
2033 
2034 static int ch347_swd_queue_flush(void)
2035 {
2040  if (retval != ERROR_OK) {
2042  LOG_DEBUG("CH347WriteData error");
2043  return retval;
2044  }
2045 
2049  if (retval != ERROR_OK) {
2051  LOG_DEBUG("CH347ReadData error");
2052  return retval;
2053  }
2054 
2057  LOG_ERROR("write/read failed %d %d",
2060  retval = ERROR_FAIL;
2061  }
2062 
2063  return retval;
2064 }
2065 
2066 static void ch347_write_swd_reg(uint8_t cmd, const uint32_t out)
2067 {
2069  // 8bit + 32bit +1bit
2076  // 0xA0 + 1 byte(3bit ACK)
2077  ch347_swd_context.need_recv_len += (1 + 1);
2079 }
2080 
2081 static void ch347_write_spec_seq(const uint8_t *out, uint8_t out_len)
2082 {
2087  for (uint8_t i = 0; i < DIV_ROUND_UP(out_len, 8); i++)
2088  ch347_swd_context.send_buf[ch347_swd_context.send_len++] = out ? out[i] : 0x00;
2089  ch347_swd_context.need_recv_len += 1; // 0xA1
2090  ch347_swd_context.total_swd_clk += out_len;
2091 }
2092 
2093 static void ch347_read_swd_reg(uint8_t cmd)
2094 {
2099  // 0xA2 + 1 byte(3bit ACK) + 4 byte(data) + 1 byte(1bit parity+1bit trn)
2100  ch347_swd_context.need_recv_len += 1 + 1 + 4 + 1;
2102 }
2103 
2104 static int ch347_swd_switch_out(enum swd_special_seq seq, const uint8_t *out, unsigned int out_len)
2105 {
2106  if ((ch347_swd_context.send_len + (1 + 2 + DIV_ROUND_UP(out_len, 8))) > CH347_MAX_SEND_BUF)
2107  return ERROR_FAIL;
2109  return ERROR_FAIL;
2110 
2111  struct ch347_swd_io *pswd_io = ch347_get_one_swd_io();
2112  if (pswd_io) {
2113  ch347_write_spec_seq(out, out_len);
2115  return ERROR_OK;
2116  } else {
2117  return ERROR_FAIL;
2118  }
2119 }
2120 
2121 // check read/write REG can fill in remaining buff
2122 static bool ch347_chk_buf_size(uint8_t cmd, uint32_t ap_delay_clk)
2123 {
2124  bool flush = false;
2125  int send_len = ch347_swd_context.send_len;
2126  int recv_len = ch347_swd_context.need_recv_len;
2127  int len;
2128  do {
2129  if (cmd & SWD_CMD_RNW) {
2130  len = 1 + 1 + 1 + 1; // 0xA2 + len + rev + cmd
2131  if (send_len + len > CH347_MAX_SEND_BUF)
2132  break;
2133  send_len += len;
2134  len = 1 + 1 + 4 + 1;
2135  /* 0xA2 + 1byte(3bit ack) + 4byte(data) +
2136  1byte(1bit parity+1bit trn) */
2137  if (recv_len + len > CH347_MAX_RECV_BUF)
2138  break;
2139  recv_len += len;
2140  } else { // write reg
2141  len = 1 + 1 + 1 + 1 + 4 + 1;
2142  // 0xA0 + len + rev + cmd +data + parity
2143  if (send_len + len > CH347_MAX_SEND_BUF)
2144  break;
2145  send_len += len;
2146  len = 1 + 1; // 0xA0 + 1byte(3bit ack)
2147  if (recv_len + len > CH347_MAX_RECV_BUF)
2148  break;
2149  recv_len += len;
2150  }
2151  if (cmd & SWD_CMD_APNDP) {
2152  len = 1 + 1 + 1 + DIV_ROUND_UP(ap_delay_clk, 8);
2153  // 0xA1 + Len + rev + n byte(delay)
2154  if (send_len + len > CH347_MAX_SEND_BUF)
2155  break;
2156  len = 1; // 0xA1
2157  if ((recv_len + len) > CH347_MAX_RECV_BUF)
2158  break;
2159  }
2160  // swd packet requests
2161  flush = true;
2162  } while (false);
2163 
2164  return flush;
2165 }
2166 
2167 static int ch347_swd_run_queue_inner(void);
2168 
2169 static int ch347_swd_send_idle(uint32_t ap_delay_clk)
2170 {
2171  bool run_q = false;
2172  struct ch347_swd_io *pswd_io = NULL;
2173  unsigned int max_processing_clk = ch347_swd_context.clk_divisor
2176  bool more_q_runs =
2177  1 + 1 + 1 + DIV_ROUND_UP(ap_delay_clk, 8) > CH347_MAX_SEND_BUF
2178  && ap_delay_clk > max_processing_clk;
2179 
2181  unsigned int expected_total_clk = ch347_swd_context.total_swd_clk + ap_delay_clk;
2182  unsigned int expected_send_len = ch347_swd_context.send_len
2183  + 1 + 1 + 1 + DIV_ROUND_UP(ap_delay_clk, 8);
2184  // 0xA1 + Len + rev + n byte(delay)
2185  unsigned int expected_recv_len = ch347_swd_context.need_recv_len + 1;
2186  // 0xA1
2187  unsigned int expected_time = ch347_swd_context.clk_divisor
2188  ? expected_total_clk * ch347_swd_context.clk_divisor
2189  : expected_total_clk / 5;
2190  if (expected_time > CH347_MAX_PROCESSING_US
2191  || expected_send_len > CH347_MAX_SEND_BUF
2192  || expected_recv_len > CH347_MAX_RECV_BUF) {
2193  int send_room = CH347_MAX_SEND_BUF - ch347_swd_context.send_len - 1 - 1 - 1;
2194  if (more_q_runs
2195  && send_room > 0
2196  && expected_recv_len <= CH347_MAX_RECV_BUF
2197  && ch347_swd_context.total_swd_clk < max_processing_clk) {
2198  pswd_io = ch347_get_one_swd_io();
2199  if (pswd_io) {
2200  // fill the rest of queue/time by part of delay
2201  unsigned int this_delay_clk = MIN(ap_delay_clk, 255);
2202  if ((unsigned int)send_room * 8 < this_delay_clk)
2203  this_delay_clk = send_room * 8;
2204  if (max_processing_clk - ch347_swd_context.total_swd_clk < this_delay_clk)
2205  this_delay_clk = max_processing_clk - ch347_swd_context.total_swd_clk;
2206  LOG_DEBUG_IO("partial delay %u clk", this_delay_clk);
2207  ch347_write_spec_seq(NULL, this_delay_clk);
2209  ap_delay_clk -= this_delay_clk;
2210  }
2211  }
2212  run_q = true;
2213  }
2214  }
2215 
2216  do {
2217  if (!run_q)
2218  pswd_io = ch347_get_one_swd_io();
2219 
2220  if (!pswd_io) {
2221  int retval = ch347_swd_run_queue_inner();
2222  if (retval != ERROR_OK)
2223  return retval;
2224 
2225  pswd_io = ch347_get_one_swd_io();
2226  if (!pswd_io) {
2227  LOG_ERROR("ch347 SWD queue not empty after ch347_swd_run_queue");
2229  return ERROR_FAIL;
2230  }
2231  }
2232 
2233  unsigned int send_room = CH347_MAX_SEND_BUF - 1 - 1 - 1;
2234  unsigned int this_delay_clk = MIN(ap_delay_clk, 255);
2235  if (send_room * 8 < this_delay_clk)
2236  this_delay_clk = send_room * 8;
2237  if (max_processing_clk < this_delay_clk)
2238  this_delay_clk = max_processing_clk;
2239  LOG_DEBUG_IO("delay %u clk", this_delay_clk);
2240  ch347_write_spec_seq(NULL, this_delay_clk);
2242  ap_delay_clk -= this_delay_clk;
2243  run_q = true;
2244  pswd_io = NULL;
2245  } while (ap_delay_clk);
2246  return ERROR_OK;
2247 }
2248 
2250 {
2251  LOG_DEBUG_IO("Executing %u queued transactions", ch347_swd_context.sent_cmd_count);
2253  LOG_DEBUG_IO("Skipping due to previous errors: %d", ch347_swd_context.queued_retval);
2254  goto skip;
2255  }
2256 
2257  int retval = ch347_swd_queue_flush();
2258  if (retval != ERROR_OK)
2259  return retval;
2260 
2262  LOG_ERROR("CH347 usb write/read failed - queued_retval");
2263  goto skip;
2264  }
2265  uint8_t *recv_buf = ch347_swd_context.recv_buf;
2266  int recv_len = 0;
2267  if (recv_buf[recv_len++] != CH347_CMD_SWD) { // 0XE8
2269  LOG_ERROR("CH347 usb write/read failed - not CH347_CMD_SWD");
2270  goto skip;
2271  }
2272 
2273  int cmds_len = le_to_h_u16(&recv_buf[recv_len]);
2274  recv_len += 2; // cmds_len
2275  if ((cmds_len + CH347_CMD_HEADER) > ch347_swd_context.recv_len) {
2277  LOG_ERROR("CH347 usb write/read failed - too long");
2278  goto skip;
2279  }
2280 
2281  struct list_head *tmp;
2282  struct list_head *pos;
2283  struct ch347_swd_io *pswd_io;
2284 
2286  pswd_io = list_entry(pos, struct ch347_swd_io, list_entry);
2287  if (pswd_io->usb_cmd == CH347_CMD_SWD_SEQ_W) {
2288  if (recv_buf[recv_len++] != CH347_CMD_SWD_SEQ_W) {
2290  LOG_ERROR("CH347 usb write/read failed - not CH347_CMD_SWD_SEQ_W");
2291  goto skip;
2292  }
2293  } else { // read/write Reg
2294  uint32_t ack;
2295  bool check_ack;
2296  // read Reg
2297  if (recv_buf[recv_len] == CH347_CMD_SWD_REG_R) {
2298  recv_len++;
2299  ack = buf_get_u32(&recv_buf[recv_len++], 0, 3);
2300  /* Devices do not reply to DP_TARGETSEL write
2301  cmd, ignore received ack */
2302  check_ack = swd_cmd_returns_ack(pswd_io->cmd);
2303  if (pswd_io->cmd & SWD_CMD_RNW) {
2304  uint32_t data = buf_get_u32(&recv_buf[recv_len], 0, 32);
2305 
2306  LOG_CUSTOM_LEVEL((check_ack && ack != SWD_ACK_OK)
2308  "%s%s %s read reg %X = %08" PRIx32,
2309  check_ack ? "" : "ack ignored ",
2310  ack == SWD_ACK_OK ? "OK" :
2311  ack == SWD_ACK_WAIT ? "WAIT" :
2312  ack == SWD_ACK_FAULT ? "FAULT" : "JUNK",
2313  pswd_io->cmd & SWD_CMD_APNDP ? "AP" : "DP",
2314  (pswd_io->cmd & SWD_CMD_A32) >> 1,
2315  data);
2316 
2317  if (ack != SWD_ACK_OK && check_ack) {
2319  goto skip;
2320  }
2321 
2322  uint32_t parity = buf_get_u32(&recv_buf[recv_len], 32, 1);
2323  if (parity != (uint32_t)parity_u32(data)) {
2324  LOG_ERROR("SWD Read data parity mismatch");
2326  goto skip;
2327  }
2328 
2329  if (pswd_io->dst)
2330  *pswd_io->dst = data;
2331  } else {
2333  LOG_ERROR("CH347 usb write/read failed - not SWD_CMD_RNW");
2334  goto skip;
2335  }
2336  recv_len += 5;
2337  } else if (recv_buf[recv_len] == CH347_CMD_SWD_REG_W) {
2338  recv_len++;
2339  ack = buf_get_u32(&recv_buf[recv_len++], 0, 3);
2340  /* Devices do not reply to DP_TARGETSEL write
2341  cmd, ignore received ack */
2342  check_ack = swd_cmd_returns_ack(pswd_io->cmd);
2343 
2344  LOG_CUSTOM_LEVEL((check_ack && ack != SWD_ACK_OK)
2346  "%s%s %s write reg %X = %08" PRIx32,
2347  check_ack ? "" : "ack ignored ",
2348  ack == SWD_ACK_OK ? "OK" :
2349  ack == SWD_ACK_WAIT ? "WAIT" :
2350  ack == SWD_ACK_FAULT ? "FAULT" : "JUNK",
2351  pswd_io->cmd & SWD_CMD_APNDP ? "AP" : "DP",
2352  (pswd_io->cmd & SWD_CMD_A32) >> 1,
2353  pswd_io->value);
2354 
2355  if (ack != SWD_ACK_OK && check_ack) {
2357  goto skip;
2358  }
2359  } else {
2361  LOG_ERROR("CH347 usb write/read failed recv_len = %d", recv_len);
2362  goto skip;
2363  }
2364  }
2365  list_del_init(&pswd_io->list_entry);
2366  list_add_tail(&pswd_io->list_entry,
2368  }
2369 
2370 skip:
2373  pswd_io = list_entry(pos, struct ch347_swd_io, list_entry);
2374  list_del_init(&pswd_io->list_entry);
2375  list_add_tail(&pswd_io->list_entry,
2377  }
2378  }
2379 
2380  // 0xE8 + 2byte len
2382  // 0xE8 + 2byte len
2389  return retval;
2390 }
2391 
2392 static int ch347_swd_run_queue(void)
2393 {
2394  /* A transaction must be followed by another transaction or at least 8
2395  idle cycles to ensure that data is clocked through the AP. */
2396  int retval = ch347_swd_send_idle(8);
2397  if (retval != ERROR_OK)
2398  return retval;
2399 
2400  return ch347_swd_run_queue_inner();
2401 }
2402 
2403 static int ch347_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk)
2404 {
2405  int retval = ERROR_OK;
2406  bool run_q = false;
2408  unsigned int expected_total_clk = ch347_swd_context.total_swd_clk
2409  + 46 // SWD transaction
2410  + ap_delay_clk
2411  + 8; // 8 idle cycles at the end of queue
2412  unsigned int expected_time = ch347_swd_context.clk_divisor
2413  ? expected_total_clk * ch347_swd_context.clk_divisor
2414  : expected_total_clk / 5;
2415  if (expected_time > CH347_MAX_PROCESSING_US) {
2416  LOG_DEBUG_IO("Expected queue run %u cycles, with this cmd %u",
2417  ch347_swd_context.total_swd_clk, expected_total_clk);
2418  run_q = true;
2419  } else if (!ch347_chk_buf_size(cmd, ap_delay_clk)) {
2420  run_q = true;
2421  }
2422  }
2423 
2424  struct ch347_swd_io *pswd_io = NULL;
2425  if (!run_q)
2426  pswd_io = ch347_get_one_swd_io();
2427 
2428  if (!pswd_io) {
2429  retval = ch347_swd_run_queue_inner();
2430  if (retval != ERROR_OK)
2431  return retval;
2432 
2433  pswd_io = ch347_get_one_swd_io();
2434  if (!pswd_io) {
2435  LOG_ERROR("ch347 SWD queue not empty after ch347_swd_run_queue");
2437  return ERROR_FAIL;
2438  }
2439  }
2440 
2441  pswd_io->cmd = cmd | SWD_CMD_START | SWD_CMD_PARK;
2442 
2443  if (pswd_io->cmd & SWD_CMD_RNW) {
2444  pswd_io->usb_cmd = CH347_CMD_SWD_REG_R;
2445  pswd_io->dst = dst;
2446  ch347_read_swd_reg(pswd_io->cmd);
2447  } else {
2448  pswd_io->usb_cmd = CH347_CMD_SWD_REG_W;
2449  pswd_io->value = data;
2450  ch347_write_swd_reg(pswd_io->cmd, data);
2451  }
2452 
2455 
2456  // Insert idle cycles after AP accesses to avoid WAIT
2457  if (ap_delay_clk)
2458  retval = ch347_swd_send_idle(ap_delay_clk);
2459 
2460  return retval;
2461 }
2462 
2464 {
2465  switch (seq) {
2466  case LINE_RESET:
2467  LOG_DEBUG("SWD line reset");
2469  case JTAG_TO_SWD:
2470  LOG_DEBUG("JTAG-to-SWD");
2472  case JTAG_TO_DORMANT:
2473  LOG_DEBUG("JTAG-to-DORMANT");
2475  case SWD_TO_JTAG:
2476  LOG_DEBUG("SWD-to-JTAG");
2478  case SWD_TO_DORMANT:
2479  LOG_DEBUG("SWD-to-DORMANT");
2481  case DORMANT_TO_SWD:
2482  LOG_DEBUG("DORMANT-to-SWD");
2484  case DORMANT_TO_JTAG:
2485  LOG_DEBUG("DORMANT-to-JTAG");
2487  default:
2488  LOG_ERROR("Sequence %d not supported", seq);
2489  return ERROR_FAIL;
2490  }
2491 }
2492 
2493 static int ch347_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
2494 {
2495  assert(cmd & SWD_CMD_RNW);
2496  return ch347_swd_queue_cmd(cmd, value, 0, ap_delay_clk);
2497 }
2498 
2499 static int ch347_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
2500 {
2501  assert(!(cmd & SWD_CMD_RNW));
2502  return ch347_swd_queue_cmd(cmd, NULL, value, ap_delay_clk);
2503 }
2504 
2505 static const struct swd_driver ch347_swd = {
2506  .init = ch347_swd_init,
2507  .switch_seq = ch347_swd_switch_seq,
2508  .read_reg = ch347_swd_read_reg,
2509  .write_reg = ch347_swd_write_reg,
2510  .run = ch347_swd_run_queue,
2511 };
2512 
2513 static struct jtag_interface ch347_interface = {
2515  .execute_queue = ch347_execute_queue,
2516 };
2517 
2519  .name = "ch347",
2520  .transport_ids = TRANSPORT_JTAG | TRANSPORT_SWD,
2521  .transport_preferred_id = TRANSPORT_JTAG,
2522  .commands = ch347_command_handlers,
2523 
2524  .init = ch347_init,
2525  .quit = ch347_quit,
2526  .reset = ch347_reset,
2527  .speed = ch347_speed_set,
2528  .khz = ch347_speed_get_index,
2529  .speed_div = ch347_speed_get,
2530 
2531  .jtag_ops = &ch347_interface,
2532  .swd_ops = &ch347_swd,
2533 };
const struct adapter_gpio_config * adapter_gpio_get_config(void)
Retrieves gpio configuration set with command "adapter gpio <signal_name>".
Definition: adapter.c:1339
const uint16_t * adapter_usb_get_pids(void)
Definition: adapter.c:340
const char * adapter_usb_get_product_name(void)
Definition: adapter.c:350
const uint16_t * adapter_usb_get_vids(void)
Definition: adapter.c:335
struct adapter_gpio_config gpios[ADAPTER_GPIO_IDX_NUM]
Definition: adapter.c:53
@ ADAPTER_GPIO_IDX_LED
Definition: adapter.h:62
@ ADAPTER_GPIO_IDX_SRST
Definition: adapter.h:61
adapter_gpio_drive_mode
Supported output drive modes for adaptor GPIO.
Definition: adapter.h:16
@ ADAPTER_GPIO_DRIVE_MODE_OPEN_SOURCE
Definition: adapter.h:19
@ ADAPTER_GPIO_DRIVE_MODE_OPEN_DRAIN
Definition: adapter.h:18
@ ADAPTER_GPIO_DRIVE_MODE_PUSH_PULL
Definition: adapter.h:17
#define ADAPTER_GPIO_NOT_SET
Definition: adapter.h:142
#define SWD_ACK_FAULT
Definition: arm_adi_v5.h:33
swd_special_seq
Definition: arm_adi_v5.h:236
@ DORMANT_TO_JTAG
Definition: arm_adi_v5.h:243
@ JTAG_TO_SWD
Definition: arm_adi_v5.h:238
@ DORMANT_TO_SWD
Definition: arm_adi_v5.h:242
@ LINE_RESET
Definition: arm_adi_v5.h:237
@ JTAG_TO_DORMANT
Definition: arm_adi_v5.h:239
@ SWD_TO_DORMANT
Definition: arm_adi_v5.h:241
@ SWD_TO_JTAG
Definition: arm_adi_v5.h:240
#define SWD_ACK_WAIT
Definition: arm_adi_v5.h:32
#define SWD_ACK_OK
Definition: arm_adi_v5.h:31
enum arm_mode mode
Definition: armv4_5.c:280
static const struct device_t * device
Definition: at91rm9200.c:94
char * buf_to_hex_str(const void *_buf, unsigned int buf_len)
Definition: binarybuffer.c:178
void * buf_set_buf(const void *_src, unsigned int src_start, void *_dst, unsigned int dst_start, unsigned int len)
Definition: binarybuffer.c:120
void * buf_cpy(const void *from, void *_to, unsigned int size)
Copies size bits out of from and into to.
Definition: binarybuffer.c:43
size_t hexify(char *hex, const uint8_t *bin, size_t count, size_t length)
Convert binary data into a string of hexadecimal pairs.
Definition: binarybuffer.c:380
Support functions to access arbitrary bits in a byte array.
static uint32_t buf_get_u32(const uint8_t *_buffer, unsigned int first, unsigned int num)
Retrieves num bits from _buffer, starting at the first bit, returning the bits in a 32-bit word.
Definition: binarybuffer.h:104
static int ch347_scratchpad_add_idle_clock(void)
Function to ensure that the clock is in a low state.
Definition: ch347.c:1015
static int ch347_scratchpad_add_move_state(enum tap_state state, int skip)
Toggle the tap state to the target state.
Definition: ch347.c:1086
static int ch347_cmd_from_scratchpad(void)
copy the scratchpad content into a new command in the command queue
Definition: ch347.c:499
struct adapter_driver ch347_adapter_driver
Definition: ch347.c:2518
static int ch347_scratchpad_add_bytes(uint8_t *bytes, int count)
adds bytes from a buffer to the scratchpad if scratchpad is full after this byte the command will be ...
Definition: ch347.c:940
#define CH347_MAX_CMD_BUF
Definition: ch347.c:134
static int ch347_init_pack_size(void)
inits ch347.pack_size and ch347.max_len
Definition: ch347.c:1779
static bool ch347_srst_active_high
Definition: ch347.c:273
#define TDI_L
Definition: ch347.c:65
static int ch347_swd_switch_out(enum swd_special_seq seq, const uint8_t *out, unsigned int out_len)
Definition: ch347.c:2104
#define HW_TDO_BUF_SIZE
Definition: ch347.c:99
static int ch347_read_data(uint8_t *data, int *length)
reads data from the CH347 via libusb driver
Definition: ch347.c:423
static int ch347_scan_data_to_fields(uint8_t *decoded_buf, int decoded_buf_len)
Used to put the data from the decoded buffer into the scan command fields.
Definition: ch347.c:610
#define CH347_CMD_SWD
Definition: ch347.c:126
static const int ch347_larger_pack_clock_speeds[]
Definition: ch347.c:187
#define CH347_EPOUT
Definition: ch347.c:140
static int ch347_quit(void)
CH347 Device Release Function.
Definition: ch347.c:1650
#define CH347F_MPHSI_INTERFACE
Definition: ch347.c:143
#define DEFAULT_CH347F_PRODUCT_ID
Definition: ch347.c:152
static struct ch347_swd_io * ch347_get_one_swd_io(void)
Definition: ch347.c:2019
#define CH347_MAX_PROCESSING_US
Definition: ch347.c:130
static int ch347_scratchpad_add_move_path(struct pathmove_command *cmd)
Obtain the current Tap status and switch to the status TMS value passed down by cmd.
Definition: ch347.c:1052
#define CH347_SWD_CLOCK_MAX
Definition: ch347.c:135
#define DEFAULT_OTHER_PRODUCT_ID
Definition: ch347.c:153
#define CH347_CMD_INIT_GET_MODE_CLOCK_INDEX_VALUE
Definition: ch347.c:108
#define CH347_EPIN
Definition: ch347.c:141
#define CH347T_USABLE_GPIOS
Definition: ch347.c:77
static void ch347_cmd_calc_reads(struct ch347_cmd *cmd)
calculates the amount of bits and bytes that should be read for this command
Definition: ch347.c:459
#define CH347T_TRST_GPIO
Definition: ch347.c:87
#define VENDOR_VERSION
Definition: ch347.c:96
#define GPIO_SET_INPUT
Definition: ch347.c:94
#define TMS_L
Definition: ch347.c:67
static void ch347_configure_activity_led(const struct adapter_gpio_config *led_config)
Configure which GPIO pin is used as the activity LED.
Definition: ch347.c:1901
#define TMS_H
Definition: ch347.c:66
#define TDI_H
Definition: ch347.c:64
static const struct command_registration ch347_command_handlers[]
Definition: ch347.c:1882
#define DEFAULT_VENDOR_ID
Definition: ch347.c:150
static void ch347_write_swd_reg(uint8_t cmd, const uint32_t out)
Definition: ch347.c:2066
static uint8_t ch347_usable_gpios(void)
Mask of the GPIO's that don't collide with an interface signal.
Definition: ch347.c:1273
#define CH347_CMD_JTAG_INIT
Definition: ch347.c:116
static int ch347_cmd_start_next(uint8_t type)
starts the next command in the scratchpad.
Definition: ch347.c:804
#define CH347_SWD_CLOCK_BASE
Definition: ch347.c:136
#define USB_READ_TIMEOUT
Definition: ch347.c:145
#define CH347_MAX_SEND_BUF
Definition: ch347.c:132
static bool ch347_is_single_cmd_type(uint8_t type)
Definition: ch347.c:279
static bool swd_mode
Definition: ch347.c:265
static int ch347_gpio_cmd(unsigned int gpio, uint8_t value, uint8_t *state)
Sends a GPIO command for a single pin and returns the pin state that the device reports back.
Definition: ch347.c:1291
#define CH347_CMD_INIT_READ_LEN
Definition: ch347.c:106
static int ch347_swd_run_queue(void)
Definition: ch347.c:2392
static const struct swd_driver ch347_swd
Definition: ch347.c:2505
#define CH347_SINGLE_CMD_MAX_READ
Definition: ch347.c:122
static int ch347_speed_get_index(int khz, int *speed_idx)
multiplies the input speed by 1000
Definition: ch347.c:1831
#define TCK_H
Definition: ch347.c:68
static int ch347_adapter_set_speed(uint8_t clock_index)
Sends the CH347_CMD_JTAG_INIT (D0) command to get the JTAG interface initialized with the speed index...
Definition: ch347.c:1720
static int ch347_open_device(void)
opens the CH347 device via libusb driver
Definition: ch347.c:1515
static int ch347_scratchpad_add_stableclocks(int count)
Function adds a certain amount of TCK pulses without changing the TMS pin.
Definition: ch347.c:992
#define GPIO_SET_H
Definition: ch347.c:92
static int ch347_scratchpad_add_byte(uint8_t byte)
adds one byte to the scratchpad if scratchpad is full after this byte the command will be created fro...
Definition: ch347.c:906
static int ch347_execute_queue(struct jtag_command *cmd_queue)
Executes the command queue.
Definition: ch347.c:1460
static void ch347_configure_srst_gpio(const struct adapter_gpio_config *srst_config)
Configure which GPIO pin drives SRST in SWD mode.
Definition: ch347.c:1922
static int ch347_swd_send_idle(uint32_t ap_delay_clk)
Definition: ch347.c:2169
static uint8_t ch347_srst_gpio_pin
Definition: ch347.c:272
#define TRST_L
Definition: ch347.c:71
#define LED_OFF
Definition: ch347.c:73
static int ch347_cmd_transmit_queue(void)
Sends the write buffer via libusb and if LARGER_PACK mode is active read also data back.
Definition: ch347.c:672
static void log_buf_dump(const uint8_t *data, unsigned int size, bool recv)
Definition: ch347.c:284
static int ch347_activity_led_set(int led_state)
Turn the activity LED on or off.
Definition: ch347.c:1369
#define CH347_CMD_SWD_INIT
Definition: ch347.c:125
#define CH347F_TRST_GPIO
Definition: ch347.c:88
static int ch347_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
Definition: ch347.c:2499
static int ch347_gpio_set(int gpio, bool data)
Sets a GPIO bit.
Definition: ch347.c:1344
static int ch347_swd_queue_flush(void)
Definition: ch347.c:2034
static int ch347_scratchpad_add_pin_byte(void)
adds the output pin byte to the scratchpad if scratchpad is full after this byte the command will be ...
Definition: ch347.c:925
static void ch347_write_spec_seq(const uint8_t *out, uint8_t out_len)
Definition: ch347.c:2081
static struct libusb_device_handle * ch347_handle
Definition: ch347.c:275
#define UCMDPKT_DATA_MAX_BYTES_USBHS
Definition: ch347.c:103
static uint16_t default_ch347_pids[]
Definition: ch347.c:267
#define CH347F_USABLE_GPIOS
Definition: ch347.c:83
static int ch347_scan_queue_fields(struct scan_field *scan_fields, int scan_fields_len)
queue the scan fields into the scan queue
Definition: ch347.c:846
static int ch347_scratchpad_add_run_test(int cycles, enum tap_state state)
Toggle the Tap state to run test/idle.
Definition: ch347.c:1207
#define CH347_MAX_RECV_BUF
Definition: ch347.c:133
static int ch347_speed_get(int speed_idx, int *khz)
returns the speed in kHz by the give speed index
Definition: ch347.c:1805
#define CH347_CMD_GPIO
Definition: ch347.c:115
static int ch347_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk)
Definition: ch347.c:2403
static int ch347_swd_switch_seq(enum swd_special_seq seq)
Definition: ch347.c:2463
static struct jtag_interface ch347_interface
Definition: ch347.c:2513
ch347_variant
Definition: ch347.c:160
@ CH347F
Definition: ch347.c:162
@ OTHER_PRODUCT_ID
Definition: ch347.c:163
@ CH347T
Definition: ch347.c:161
static bool ch347_chk_buf_size(uint8_t cmd, uint32_t ap_delay_clk)
Definition: ch347.c:2122
static int ch347_scratchpad_add_write_read(struct scan_command *cmd, uint8_t *bits, int bits_len, enum scan_type scan)
CH347 Batch read/write function.
Definition: ch347.c:1112
#define USB_WRITE_TIMEOUT
Definition: ch347.c:144
static int ch347_write_data(uint8_t *data, int *length)
writes data to the CH347 via libusb driver
Definition: ch347.c:387
static struct ch347_info ch347
Definition: ch347.c:274
#define CH347_SWD_CLOCK_MAX_DIVISOR
Definition: ch347.c:138
#define DEFAULT_CH347T_PRODUCT_ID
Definition: ch347.c:151
#define CH347_CMD_JTAG_DATA_SHIFT
Definition: ch347.c:119
static int ch347_read_scan(uint8_t *decoded_buf, int decoded_buf_len, int raw_read_len)
Reads data back from CH347 and decode it byte- and bitwise into the buffer.
Definition: ch347.c:537
#define CH347_CMD_SWD_REG_R
Definition: ch347.c:129
static uint8_t ch347_gpio_drive_value(bool level, enum adapter_gpio_drive_mode drive)
Translates an output level into a GPIO command byte for a drive mode.
Definition: ch347.c:1323
static uint8_t ch347_activity_led_gpio_pin
Definition: ch347.c:269
static int ch347_scratchpad_add_tms_change(const uint8_t *tms_value, int step, int skip)
Function that performs state switching by changing the value of TMS.
Definition: ch347.c:1029
static int ch347_swd_init(void)
Initialization for the swd mode.
Definition: ch347.c:1997
static int ch347_single_read_get_byte(int read_buf_idx, uint8_t *byte)
Function executes the single command and deliver one byte from the buffer that's read back from USB.
Definition: ch347.c:869
#define TCK_L
Definition: ch347.c:69
#define CH347T_MPHSI_INTERFACE
Definition: ch347.c:142
#define GPIO_CNT
Definition: ch347.c:74
#define TRST_H
Definition: ch347.c:70
#define GPIO_SET_L
Definition: ch347.c:91
static int ch347_sleep(int us)
Flushes the command buffer and sleeps for a specific timespan.
Definition: ch347.c:1447
static void ch347_read_swd_reg(uint8_t cmd)
Definition: ch347.c:2093
#define CH347_CMD_JTAG_BIT_OP
Definition: ch347.c:117
static int ch347_adapter_supports_larger_pack_mode(bool *supports_larger_pack_mode)
Sends the CH347_CMD_JTAG_INIT (D0) command to ask the JTAG interface with special clock index 9 for t...
Definition: ch347.c:1708
static int ch347_init(void)
CH347 Initialization function.
Definition: ch347.c:1955
static int ch347_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
Definition: ch347.c:2493
static int ch347_adapter_init(uint8_t clock_index, bool *supports_larger_pack_mode)
Sends the CH347_CMD_JTAG_INIT (D0) command to get the JTAG interface initialized with the speed index...
Definition: ch347.c:1671
#define LARGER_PACK_MAX_SIZE
Definition: ch347.c:101
#define CH347_CMD_HEADER
Definition: ch347.c:105
static const int ch347_standard_pack_clock_speeds[]
Definition: ch347.c:177
static uint16_t default_ch347_vids[]
Definition: ch347.c:266
static int ch347_scratchpad_add_clock_tms(bool tms)
Function used to change the TMS value at the rising edge of TCK to switch its TAP state.
Definition: ch347.c:974
static int ch347_swd_run_queue_inner(void)
Definition: ch347.c:2249
#define CH347_CMD_SWD_SEQ_W
Definition: ch347.c:128
#define CH347_CMD_SWD_REG_W
Definition: ch347.c:127
static void ch347_scratchpad_check_full(void)
checks if the scratchpad is full.
Definition: ch347.c:888
pack_size
Definition: ch347.c:170
@ STANDARD_PACK
Definition: ch347.c:172
@ LARGER_PACK
Definition: ch347.c:173
@ UNSET
Definition: ch347.c:171
static int ch347_swd_init_cmd(uint8_t clock_divisor)
swd init function
Definition: ch347.c:1732
#define CH347_CMD_JTAG_BIT_OP_RD
Definition: ch347.c:118
static int ch347_speed_set(int speed_index)
Initializes the JTAG interface and set CH347 TCK frequency.
Definition: ch347.c:1760
#define BYTEWISE_MODE_VERSION
Definition: ch347.c:147
#define USBC_PACKET_USBHS
Definition: ch347.c:104
static int ch347_reset(int trst, int srst)
Control (assert/deassert) the signals SRST and TRST on the interface.
Definition: ch347.c:1391
static int ch347_scratchpad_add_scan(struct scan_command *cmd)
Switch to SHIFT-DR or SHIFT-IR status for scanning.
Definition: ch347.c:1230
#define MAX_BITS_PER_BIT_OP
Definition: ch347.c:110
#define LED_ON
Definition: ch347.c:72
static bool ch347_activity_led_active_high
Definition: ch347.c:270
#define CH347_CMD_JTAG_DATA_SHIFT_RD
Definition: ch347.c:120
#define COMMAND_REGISTRATION_DONE
Use this as the last entry in an array of command_registration records.
Definition: command.h:256
@ COMMAND_ANY
Definition: command.h:42
int jtag_build_buffer(const struct scan_command *cmd, uint8_t **buffer)
Definition: commands.c:192
enum scan_type jtag_scan_type(const struct scan_command *cmd)
Definition: commands.c:167
scan_type
The inferred type of a scan_command structure, indicating whether the command has the host scan in fr...
Definition: commands.h:22
@ SCAN_IN
From device to host,.
Definition: commands.h:24
@ SCAN_IO
Full-duplex scan.
Definition: commands.h:28
@ JTAG_TLR_RESET
Definition: commands.h:137
@ JTAG_SCAN
Definition: commands.h:129
@ JTAG_PATHMOVE
Definition: commands.h:140
@ JTAG_STABLECLOCKS
Definition: commands.h:142
@ JTAG_RUNTEST
Definition: commands.h:138
@ JTAG_SLEEP
Definition: commands.h:141
@ JTAG_TMS
Definition: commands.h:143
uint32_t size
Size of dw_spi_transaction::buffer.
Definition: dw-spi-helper.h:4
uint8_t type
Definition: esp_usb_jtag.c:0
uint8_t length
Definition: esp_usb_jtag.c:1
enum tap_state tap_state_transition(enum tap_state cur_state, bool tms)
Function tap_state_transition takes a current TAP state and returns the next state according to the t...
Definition: interface.c:223
const char * tap_state_name(enum tap_state state)
Function tap_state_name Returns a string suitable for display representing the JTAG tap_state.
Definition: interface.c:344
int tap_get_tms_path_len(enum tap_state from, enum tap_state to)
Function int tap_get_tms_path_len returns the total number of bits that represents a TMS path transit...
Definition: interface.c:195
enum tap_state tap_get_state(void)
This function gets the state of the "state follower" which tracks the state of the TAPs connected to ...
Definition: interface.c:37
int tap_get_tms_path(enum tap_state from, enum tap_state to)
This function provides a "bit sequence" indicating what has to be done with TMS during a sequence of ...
Definition: interface.c:190
#define DEBUG_CAP_TMS_SEQ
Definition: interface.h:194
#define tap_set_state(new_state)
This function sets the state of a "state follower" which tracks the state of the TAPs connected to th...
Definition: interface.h:50
void jtag_sleep(uint32_t us)
Definition: jtag/core.c:1058
tap_state
Defines JTAG Test Access Port states.
Definition: jtag.h:37
@ TAP_RESET
Definition: jtag.h:56
@ TAP_IRSHIFT
Definition: jtag.h:51
@ TAP_IDLE
Definition: jtag.h:53
@ TAP_DRSHIFT
Definition: jtag.h:43
#define ERROR_JTAG_TRANSITION_INVALID
Definition: jtag.h:560
static struct scan_blk scan
Definition: lakemont.c:60
int jtag_libusb_open(const uint16_t vids[], const uint16_t pids[], const char *product, struct libusb_device_handle **out, adapter_get_alternate_serial_fn adapter_get_alternate_serial)
int jtag_libusb_bulk_write(struct libusb_device_handle *dev, int ep, char *bytes, int size, int timeout, int *transferred)
int jtag_libusb_control_transfer(struct libusb_device_handle *dev, uint8_t request_type, uint8_t request, uint16_t value, uint16_t index, char *bytes, uint16_t size, unsigned int timeout, int *transferred)
void jtag_libusb_close(struct libusb_device_handle *dev)
int jtag_libusb_bulk_read(struct libusb_device_handle *dev, int ep, char *bytes, int size, int timeout, int *transferred)
#define list_first_entry(ptr, type, member)
Definition: list.h:131
static void list_add_tail(struct list_head *new, struct list_head *head)
Definition: list.h:203
static int list_empty(const struct list_head *head)
Definition: list.h:61
#define list_for_each_entry_safe(p, n, h, field)
Definition: list.h:159
#define list_for_each_entry(p, h, field)
Definition: list.h:155
static void list_del(struct list_head *entry)
Definition: list.h:88
#define list_entry(ptr, type, field)
Definition: list.h:129
#define list_for_each_safe(p, n, head)
Definition: list.h:152
static void list_del_init(struct list_head *entry)
Definition: list.h:123
static void INIT_LIST_HEAD(struct list_head *list)
Definition: list.h:54
#define LOG_CUSTOM_LEVEL(level, expr ...)
Definition: log.h:132
#define LOG_DEBUG_IO(expr ...)
Definition: log.h:116
#define LOG_WARNING(expr ...)
Definition: log.h:144
#define ERROR_FAIL
Definition: log.h:188
#define LOG_ERROR(expr ...)
Definition: log.h:147
#define LOG_LEVEL_IS(FOO)
Definition: log.h:112
#define LOG_INFO(expr ...)
Definition: log.h:141
#define LOG_DEBUG(expr ...)
Definition: log.h:124
#define ERROR_OK
Definition: log.h:182
@ LOG_LVL_DEBUG
Definition: log.h:55
@ LOG_LVL_DEBUG_IO
Definition: log.h:56
const unsigned char bit_offset
Definition: mspm0.c:706
uint8_t bits[QN908X_FLASH_MAX_BLOCKS *QN908X_FLASH_PAGES_PER_BLOCK/8]
Definition: qn908x.c:0
#define MIN(a, b)
Definition: replacements.h:22
static int step(struct target *target, bool current, target_addr_t address, bool handle_breakpoints)
Definition: riscv-011.c:1466
#define BIT(nr)
Definition: stm32l4x.h:18
Represents a driver for a debugging interface.
Definition: interface.h:214
const char *const name
The name of the interface driver.
Definition: interface.h:216
Configuration options for a single GPIO.
Definition: adapter.h:68
unsigned int gpio_num
Definition: adapter.h:69
uint16_t read_len
Definition: ch347.c:202
uint8_t type
Definition: ch347.c:199
uint16_t tdo_bit_count
Definition: ch347.c:203
uint16_t write_data_len
Definition: ch347.c:201
uint8_t * write_data
Definition: ch347.c:200
int singe_read_len
Definition: ch347.c:238
struct list_head scan_queue
Definition: ch347.c:235
int max_len
Definition: ch347.c:224
bool use_bitwise_mode
Definition: ch347.c:222
struct list_head cmd_queue
Definition: ch347.c:233
int tms_pin
Definition: ch347.c:215
bool swclk_5mhz_supported
Definition: ch347.c:225
int tdi_pin
Definition: ch347.c:216
uint8_t single_read[CH347_SINGLE_CMD_MAX_READ]
Definition: ch347.c:237
int trst_pin
Definition: ch347.c:218
enum ch347_variant chip_variant
Definition: ch347.c:220
uint8_t scratchpad[UCMDPKT_DATA_MAX_BYTES_USBHS]
Definition: ch347.c:229
int scratchpad_idx
Definition: ch347.c:230
int tck_pin
Definition: ch347.c:217
enum pack_size pack_size
Definition: ch347.c:223
uint8_t scratchpad_cmd_type
Definition: ch347.c:228
int fields_len
Definition: ch347.c:209
struct scan_field * fields
Definition: ch347.c:208
int queued_retval
Definition: ch347.c:255
struct list_head free_cmd_head
Definition: ch347.c:260
struct ch347_swd_io ch347_cmd_buf[CH347_MAX_CMD_BUF]
Definition: ch347.c:261
int sent_cmd_count
Definition: ch347.c:256
unsigned int clk_divisor
Definition: ch347.c:257
int need_recv_len
Definition: ch347.c:254
uint8_t send_buf[CH347_MAX_SEND_BUF]
Definition: ch347.c:250
uint8_t recv_buf[CH347_MAX_RECV_BUF]
Definition: ch347.c:251
struct list_head send_cmd_head
Definition: ch347.c:259
unsigned int total_swd_clk
Definition: ch347.c:258
uint32_t * dst
Definition: ch347.c:244
struct list_head list_entry
Definition: ch347.c:246
uint8_t usb_cmd
Definition: ch347.c:242
uint8_t cmd
Definition: ch347.c:243
uint32_t value
Definition: ch347.c:245
const char * name
Definition: command.h:239
Represents a driver for a debugging interface.
Definition: interface.h:189
unsigned int supported
Bit vector listing capabilities exposed by this driver.
Definition: interface.h:193
Definition: list.h:41
Definition: osbdm.c:25
The scan_command provide a means of encapsulating a set of scan_field structures that should be scann...
Definition: commands.h:35
This structure defines a single scan field in the scan.
Definition: jtag.h:87
int(* init)(void)
Initialize the debug link so it can perform SWD operations.
Definition: swd.h:255
static const unsigned int swd_seq_dormant_to_swd_len
Definition: swd.h:190
static const uint8_t swd_seq_dormant_to_jtag[]
Dormant-to-JTAG sequence.
Definition: swd.h:230
#define SWD_CMD_A32
Definition: swd.h:19
static const uint8_t swd_seq_dormant_to_swd[]
Dormant-to-SWD sequence.
Definition: swd.h:171
static const uint8_t swd_seq_jtag_to_dormant[]
JTAG-to-dormant sequence.
Definition: swd.h:199
static bool swd_cmd_returns_ack(uint8_t cmd)
Test if we can rely on ACK returned by SWD command.
Definition: swd.h:58
#define SWD_CMD_PARK
Definition: swd.h:22
static int swd_ack_to_error_code(uint8_t ack)
Convert SWD ACK value returned from DP to OpenOCD error code.
Definition: swd.h:72
static uint8_t swd_cmd(bool is_read, bool is_ap, uint8_t regnum)
Construct a "cmd" byte, in lSB bit order, which swd_driver.read_reg() and swd_driver....
Definition: swd.h:35
static const unsigned int swd_seq_jtag_to_swd_len
Definition: swd.h:125
static const unsigned int swd_seq_line_reset_len
Definition: swd.h:104
static const unsigned int swd_seq_dormant_to_jtag_len
Definition: swd.h:244
#define SWD_CMD_APNDP
Definition: swd.h:17
static const unsigned int swd_seq_swd_to_dormant_len
Definition: swd.h:159
#define SWD_CMD_START
Definition: swd.h:16
#define SWD_CMD_RNW
Definition: swd.h:18
static const uint8_t swd_seq_line_reset[]
SWD Line reset.
Definition: swd.h:98
static const uint8_t swd_seq_jtag_to_swd[]
JTAG-to-SWD sequence.
Definition: swd.h:115
static const uint8_t swd_seq_swd_to_jtag[]
SWD-to-JTAG sequence.
Definition: swd.h:136
static const unsigned int swd_seq_swd_to_jtag_len
Definition: swd.h:144
static const unsigned int swd_seq_jtag_to_dormant_len
Definition: swd.h:211
static const uint8_t swd_seq_swd_to_dormant[]
SWD-to-dormant sequence.
Definition: swd.h:153
#define TRANSPORT_SWD
Definition: transport.h:20
#define TRANSPORT_JTAG
Definition: transport.h:19
static uint16_t le_to_h_u16(const uint8_t *buf)
Definition: types.h:122
static void h_u32_to_le(uint8_t *buf, uint32_t val)
Definition: types.h:178
#define ARRAY_SIZE(x)
Compute the number of elements of a variable length array.
Definition: types.h:57
#define DIV_ROUND_UP(m, n)
Rounds m up to the nearest multiple of n using division.
Definition: types.h:79
static void h_u16_to_le(uint8_t *buf, uint16_t val)
Definition: types.h:208
static int parity_u32(uint32_t x)
Calculate the (even) parity of a 32-bit datum.
Definition: types.h:265
#define NULL
Definition: usb.h:16
uint8_t cmd
Definition: vdebug.c:1
uint8_t state[4]
Definition: vdebug.c:21
uint8_t count[4]
Definition: vdebug.c:22
static unsigned int parity(unsigned int v)
Definition: xscale.c:619