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 SRST_H BIT(6)
73 #define SRST_L 0
74 #define LED_ON 1
75 #define LED_OFF 0
76 #define GPIO_CNT 8 // the CH347 has 8 GPIO's
77 /* mask which GPIO's are available in mode 3 of the CH347T: only GPIO3 (Pin11 / SCL),
78  GPIO4 (Pin15 / ACT), GPIO5 (Pin9 / TRST) and GPIO6 (Pin2 / CTS1) are possible */
79 #define CH347T_USABLE_GPIOS 0x78
80 /* On the CH347F the GPIO's share the pins with the interface signals: GPIO0 (Pin17),
81  GPIO1 (Pin18), GPIO2 (Pin10), GPIO3 (Pin9 / TRST), GPIO4 (Pin23 / TCK + SWDCLK),
82  GPIO5 (Pin24 / TDO), GPIO6 (Pin25 / TDI), GPIO7 (Pin26 / TMS + SWDIO). GPIO4 to GPIO7
83  always carry a signal of the JTAG or SWD interface, so only GPIO0 to GPIO3 are left.
84  GPIO3 is TRST, which is not a SWD signal. */
85 #define CH347F_USABLE_GPIOS 0x0F
86 /* In SWD mode the TRST pin is unused as a JTAG signal, so it can drive SRST through the GPIO
87  command. TRST is Pin9 on both chips, but has a different GPIO number: GPIO5 on CH347T,
88  GPIO3 on CH347F. */
89 #define CH347T_TRST_GPIO 5
90 #define CH347F_TRST_GPIO 3
91 /* For GPIO command: always set bits 7 and 6 for GPIO enable
92  bits 5 and 4 for pin direction output bit 3 is the data bit */
93 #define GPIO_SET_L (BIT(4) | BIT(5) | BIT(6) | BIT(7)) // value for setting a GPIO to low
94 #define GPIO_SET_H (BIT(3) | BIT(4) | BIT(5) | BIT(6) | BIT(7)) // value for setting a GPIO to high
95 // enable the pin and set the direction to input, so the pin gets released
96 #define GPIO_SET_INPUT (BIT(6) | BIT(7))
97 
98 #define VENDOR_VERSION 0x5F // for getting the chip version
99 
100 // maybe the hardware of the CH347 chip can capture only this amount of TDO bits
101 #define HW_TDO_BUF_SIZE 4096
102 // Don't send more than this amount of bytes via libusb in one packet. Also that is the limit for LARGER_PACK mode.
103 #define LARGER_PACK_MAX_SIZE 51200
104 // The data length contained in each command packet during USB high-speed operation
105 #define UCMDPKT_DATA_MAX_BYTES_USBHS 507
106 #define USBC_PACKET_USBHS 512 // Maximum data length per packet at USB high speed
107 #define CH347_CMD_HEADER 3 // Protocol header length (1 byte command type + 2 bytes data length)
108 #define CH347_CMD_INIT_READ_LEN 1 // JTAG_INIT/SWD_INIT/PIN_SET read one data byte
109 // if we send 9 in the init command we get the STANDARD mode or LARGER_PACK mode flag
110 #define CH347_CMD_INIT_GET_MODE_CLOCK_INDEX_VALUE 9
111 // No more bits are allowed per CH347_CMD_JTAG_BIT_OP command; this should be dividable by 8
112 #define MAX_BITS_PER_BIT_OP 248
113 
114 /* Protocol transmission format: CMD (1 byte) + Length (2 bytes) + Data
115  Parameter acquisition, used to obtain firmware version, JTAG interface related parameters, etc */
116 #define CH347_CMD_INFO_RD 0xCA
117 #define CH347_CMD_GPIO 0xCC // GPIO Command
118 #define CH347_CMD_JTAG_INIT 0xD0 // JTAG Interface initialization command
119 #define CH347_CMD_JTAG_BIT_OP 0xD1 // JTAG interface pin bit control command
120 #define CH347_CMD_JTAG_BIT_OP_RD 0xD2 // JTAG interface pin bit control and read commands
121 #define CH347_CMD_JTAG_DATA_SHIFT 0xD3 // JTAG interface data shift command
122 #define CH347_CMD_JTAG_DATA_SHIFT_RD 0xD4 // JTAG interface data shift and read command
123 #define CH347_CMD_PIN_SET 0xE2 // set pin functions (CH347F)
124 // for a single command these amount of data can be read at max
125 #define CH347_SINGLE_CMD_MAX_READ MAX(GPIO_CNT, CH347_CMD_INIT_READ_LEN)
126 
127 // for SWD
128 #define CH347_CMD_SWD_INIT 0xE5 // SWD Interface Initialization Command
129 #define CH347_CMD_SWD 0xE8 // SWD Command group header
130 #define CH347_CMD_SWD_REG_W 0xA0 // SWD Interface write reg
131 #define CH347_CMD_SWD_SEQ_W 0xA1 // SWD Interface write spec seq
132 #define CH347_CMD_SWD_REG_R 0xA2 // SWD Interface read reg
133 #define CH347_MAX_PROCESSING_US 7000 // max time in us for packet processing
134  // USB hosts disconnect the adapter if SWD processing takes more!
135 #define CH347_MAX_SEND_BUF USBC_PACKET_USBHS
136 #define CH347_MAX_RECV_BUF USBC_PACKET_USBHS
137 #define CH347_MAX_CMD_BUF 128
138 #define CH347_SWD_CLOCK_MAX 5000
139 #define CH347_SWD_CLOCK_BASE 1000
140 // limited by the longest sequence processing time
141 #define CH347_SWD_CLOCK_MAX_DIVISOR (CH347_MAX_PROCESSING_US / swd_seq_dormant_to_swd_len)
142 
143 #define CH347_EPOUT 0x06u // the usb endpoint number for writing
144 #define CH347_EPIN 0x86u // the usb endpoint number for reading
145 #define CH347T_MPHSI_INTERFACE 2 // the CH347T JTAG interface is number 2
146 #define CH347F_MPHSI_INTERFACE 4 // the CH347F JTAG interface is number 4
147 #define USB_WRITE_TIMEOUT 500 // write timeout in milliseconds
148 #define USB_READ_TIMEOUT 500 // read timeout in milliseconds
149 // BCD version for devices that can use bytewise mode below this version only bitwise mode can be used
150 #define BYTEWISE_MODE_VERSION 0x241
151 /* if the configuration is not setting the vendor id / product id we search for vendor id 1a86
152  and product id's 0x55dd (CH347T chip in mode 3), 0x55de (CH347F chip) and 0x55e7 (other chip) */
153 #define DEFAULT_VENDOR_ID 0x1a86
154 #define DEFAULT_CH347T_PRODUCT_ID 0x55dd
155 #define DEFAULT_CH347F_PRODUCT_ID 0x55de
156 #define DEFAULT_OTHER_PRODUCT_ID 0x55e7
157 
158 /* There are 3 different CH347 variants. The datasheet mentions the CH347T chip which has the product id 0x55dd
159  as default when it's configured to mode 3. The CH347F chip is also mentioned in the datasheet and has the
160  default product id 0x55de. The 3rd variant is not mentioned in a datasheet but was found here
161  https://github.com/WCHSoftGroup/ch347
162  The code from WCHSoftGroup is also searching for this product id */
164  CH347T = 0, // The CH347T chip
165  CH347F = 1, // The CH347F chip
166  OTHER_PRODUCT_ID = 2, // other product id not mentioned in the datasheet
167 };
168 
169 /* STANDARD_PACK means that we can send only one USBC_PACKET_USBHS-sized USB packet
170  and then read data back. LARGER_PACK means, we can send packets as large as
171  LARGER_PACK_MAX_SIZE. libusb splits there large packets into smaller USB packets and
172  transmit the data. Then we read back the data in a bigger packet. */
173 enum pack_size {
174  UNSET = -1,
177 };
178 
179 // for STANDARD_PACK mode: these are the 6 possible speeds; values in kHz
180 static const int ch347_standard_pack_clock_speeds[] = {
181  1875, // 1.875 MHz (60000 : 32)
182  3750, // 3.75 MHz (60000 : 16)
183  7500, // 7.5 MHz (60000 : 8)
184  15000, // 15 MHz (60000 : 4)
185  30000, // 30 MHz (60000 : 2)
186  60000 // 60 MHz
187 };
188 
189 // for LARGER_PACK mode: these are the 8 possible speeds; values in kHz
190 static const int ch347_larger_pack_clock_speeds[] = {
191  469, // 468.75 kHz (60000 : 128)
192  938, // 937.5 kHz (60000 : 64)
193  1875, // 1.875 MHz (60000 : 32)
194  3750, // 3.75 MHz (60000 : 16)
195  7500, // 7.5 MHz (60000 : 8)
196  15000, // 15 MHz (60000 : 4)
197  30000, // 30 MHz (60000 : 2)
198  60000 // 60 MHz
199 };
200 
201 struct ch347_cmd {
202  uint8_t type; // the command type
203  uint8_t *write_data; // data bytes for write
204  uint16_t write_data_len; // count of data bytes in the write_data buffer
205  uint16_t read_len; // if >0 a read is needed after this command
206  uint16_t tdo_bit_count; // how many TDO bits are needed to shift in by this read
207  struct list_head queue; // for handling a queue (list)
208 };
209 
210 struct ch347_scan {
211  struct scan_field *fields; // array of scan_field's for data from the device
212  int fields_len; // scan_fields array length
213  struct list_head queue; // for handling a queue (list)
214 };
215 
216 struct ch347_info {
217  // Record the CH347 pin status
218  int tms_pin;
219  int tdi_pin;
220  int tck_pin;
221  int trst_pin;
222  int srst_pin;
223 
224  enum ch347_variant chip_variant; // ch347_variant for explanation
225  // if true then we can't us the bytewise commands due to a bug of the chip; depends on BYTEWISE_MODE_VERSION
227  enum pack_size pack_size; // see: pack_size for explanation
228  int max_len; // in STANDARD_PACK or bitwise mode we can send only one USBC_PACKET_USBHS sized package
230 
231  // a "scratchpad" where we record all bytes for one command
232  uint8_t scratchpad_cmd_type; // command type
233  uint8_t scratchpad[UCMDPKT_DATA_MAX_BYTES_USBHS]; // scratchpad buffer
234  int scratchpad_idx; // current index in scratchpad
235 
236  // after a command is complete it will be stored for later processing
237  struct list_head cmd_queue;
238  // all data input scan fields are queued here
239  struct list_head scan_queue;
240  // read buffer for the single commands like CH347_CMD_GPIO and CH347_CMD_JTAG_INIT
242  int singe_read_len; // data length in single_read
243 };
244 
245 struct ch347_swd_io {
246  uint8_t usb_cmd; // 0xA0, 0xA1, 0xA2
247  uint8_t cmd;
248  uint32_t *dst;
249  uint32_t value;
250  struct list_head list_entry;
251 };
252 
256  int send_len;
257  int recv_len;
261  unsigned int clk_divisor;
262  unsigned int total_swd_clk;
263  struct list_head send_cmd_head;
264  struct list_head free_cmd_head;
266 };
267 
269 static bool swd_mode;
273 static uint8_t ch347_activity_led_gpio_pin = 0xFF;
275 // GPIO driving SRST in SWD mode, defaults to the otherwise unused TRST pin
276 static uint8_t ch347_srst_gpio_pin = 0xFF;
278 /* Set after the CH347F dedicated SRST output is enabled and its pin byte
279  * has been transmitted. JTAG pin bytes carry bit 6 only then. SWD leaves
280  * this clear. */
282 static struct ch347_info ch347;
283 static struct libusb_device_handle *ch347_handle;
284 
285 /* there are "single" commands. These commands can't be chained together and
286  need to be send as single command and need a read after write */
287 static inline bool ch347_is_single_cmd_type(uint8_t type)
288 {
291 }
292 
293 static void log_buf_dump(const uint8_t *data, unsigned int size, bool recv)
294 {
295  unsigned int i = 0, j = 0;
296  unsigned int n = size * 3 + 1;
297  char *str = malloc(n);
298  if (!str)
299  return;
300 
301  while (i < size && j < n) {
302  uint8_t cmd = data[i++];
303  hexify(str + j, &cmd, 1, n - j);
304  j += 2;
305  str[j++] = ' ';
306 
307  unsigned int cmd_payload_size = le_to_h_u16(data + i);
308  if (i + 2 <= size && j + 4 < n) {
309  hexify(str + j, data + i, 2, n - j);
310  i += 2;
311  j += 4;
312  str[j++] = ' ';
313  }
314 
315  if (cmd == CH347_CMD_SWD) {
316  // nested SWD commands
317  str[j] = '\0';
318  if (i + cmd_payload_size > size) {
319  LOG_DEBUG_IO("%s - bad size", str);
320  cmd_payload_size = size - i;
321  } else {
322  LOG_DEBUG_IO("%s", str);
323  }
324  j = 0;
325  unsigned int swd_base_i = i;
326 
327  while (i < swd_base_i + cmd_payload_size) {
328  uint8_t swd_cmd = data[i++];
329  hexify(str + j, &swd_cmd, 1, n - j);
330  j += 2;
331  str[j++] = ' ';
332 
333  unsigned int swd_bits = 0;
334  unsigned int swd_payload_size = 0;
335  if (!recv) {
336  if (i + 2 <= size) {
337  swd_bits = le_to_h_u16(data + i);
338  hexify(str + j, data + i, 2, n - j);
339  i += 2;
340  j += 4;
341  str[j++] = ' ';
342  }
343  }
344 
345  switch (swd_cmd) {
346  case CH347_CMD_SWD_REG_W:
347  if (recv)
348  swd_payload_size = 1;
349  else
350  swd_payload_size = DIV_ROUND_UP(swd_bits, 8);
351  break;
352  case CH347_CMD_SWD_SEQ_W:
353  if (!recv)
354  swd_payload_size = DIV_ROUND_UP(swd_bits, 8);
355  break;
356  case CH347_CMD_SWD_REG_R:
357  if (recv)
358  swd_payload_size = 1 + 4 + 1;
359  else
360  swd_payload_size = 1;
361  break;
362  }
363 
364  hexify(str + j, data + i, MIN(swd_payload_size, size - i), n - j);
365  i += swd_payload_size;
366  j += 2 * swd_payload_size;
367  str[j] = '\0';
368  if (i > size)
369  LOG_DEBUG_IO(" %s - bad size", str);
370  else
371  LOG_DEBUG_IO(" %s", str);
372  j = 0;
373  }
374  } else {
375  hexify(str + j, data + i, MIN(cmd_payload_size, size - i), n - j);
376  i += cmd_payload_size;
377  j += 2 * cmd_payload_size;
378  str[j] = '\0';
379  if (i > size)
380  LOG_DEBUG_IO("%s - bad size", str);
381  else
382  LOG_DEBUG_IO("%s", str);
383  j = 0;
384  }
385  }
386  free(str);
387 }
388 
396 static int ch347_write_data(uint8_t *data, int *length)
397 {
398  int write_len = *length;
399  int i = 0;
400  int transferred = 0;
401 
402  while (true) {
403  int retval = jtag_libusb_bulk_write(ch347_handle, CH347_EPOUT, (char *)&data[i],
404  write_len, USB_WRITE_TIMEOUT, &transferred);
405  if (retval != ERROR_OK) {
406  LOG_ERROR("CH347 write fail");
407  *length = 0;
408  return retval;
409  }
410  i += transferred;
411  if (i >= *length)
412  break;
413  write_len = *length - i;
414  }
415 
417  LOG_DEBUG_IO("size=%d, buf=", i);
418  log_buf_dump(data, i, false);
419  }
420 
421  *length = i;
422  return ERROR_OK;
423 }
424 
432 static int ch347_read_data(uint8_t *data, int *length)
433 {
434  int read_len = *length;
435  int i = 0;
436  int transferred = 0;
437 
438  while (true) {
439  int retval = jtag_libusb_bulk_read(ch347_handle, CH347_EPIN, (char *)&data[i],
440  read_len, USB_READ_TIMEOUT, &transferred);
441  if (retval != ERROR_OK) {
442  LOG_ERROR("CH347 read fail");
443  *length = 0;
444  return retval;
445  }
446 
447  i += transferred;
448  if (i >= *length)
449  break;
450  read_len = *length - i;
451  }
452 
454  LOG_DEBUG_IO("size=%d, buf=", i);
455  log_buf_dump(data, i, true);
456  }
457 
458  *length = i;
459  return ERROR_OK;
460 }
461 
468 static void ch347_cmd_calc_reads(struct ch347_cmd *cmd)
469 {
470  cmd->read_len = 0;
471  cmd->tdo_bit_count = 0;
472 
473  switch (cmd->type) {
474  case CH347_CMD_GPIO:
475  // for GPIO we need to read back the same amount of data that we had send
476  cmd->read_len = cmd->write_data_len;
477  break;
478  case CH347_CMD_JTAG_INIT:
479  case CH347_CMD_SWD_INIT:
480  case CH347_CMD_PIN_SET:
481  // for JTAG_INIT/SWD_INIT/PIN_SET the amount is fixed
482  cmd->read_len = CH347_CMD_INIT_READ_LEN;
483  break;
485  // for bit operations we need to count the TCK high edges
486  for (int i = 0; i < cmd->write_data_len; i++) {
487  if ((cmd->write_data[i] & TCK_H) == TCK_H) {
488  cmd->read_len++;
489  cmd->tdo_bit_count++;
490  }
491  }
492  break;
494  // for byte operations: need to read one byte back for each data byte
495  cmd->read_len = cmd->write_data_len;
496  // we occupy 8 bits per byte in the TDO hardware buffer
497  cmd->tdo_bit_count = cmd->read_len * 8;
498  break;
499  }
500 }
501 
510 {
511  // nothing to do if no bytes are recorded
512  if (!ch347.scratchpad_idx)
513  return ERROR_OK;
514 
515  // malloc for the command and data bytes
516  struct ch347_cmd *cmd = malloc(sizeof(struct ch347_cmd));
517  if (cmd)
518  cmd->write_data = malloc(ch347.scratchpad_idx);
519  if (!cmd || !cmd->write_data) {
520  LOG_ERROR("malloc failed");
521  free(cmd);
522  return ERROR_FAIL;
523  }
524 
525  // copy data, calculate the reads and add to the command queue
526  cmd->type = ch347.scratchpad_cmd_type;
527  cmd->write_data_len = ch347.scratchpad_idx;
528  memcpy(cmd->write_data, ch347.scratchpad, ch347.scratchpad_idx);
530  list_add_tail(&cmd->queue, &ch347.cmd_queue);
531 
532  // cleanup the scratchpad for the next command
534  ch347.scratchpad_idx = 0;
535  return ERROR_OK;
536 }
537 
547 static int ch347_read_scan(uint8_t *decoded_buf, int decoded_buf_len, int raw_read_len)
548 {
549  int read_len = raw_read_len;
550  uint8_t *read_buf = malloc(read_len);
551  if (!read_buf) {
552  LOG_ERROR("malloc failed");
553  return ERROR_FAIL;
554  }
555 
556  int retval = ch347_read_data(read_buf, &read_len);
557  if (retval != ERROR_OK) {
558  free(read_buf);
559  return retval;
560  }
561 
562  int rd_idx = 0;
563  int decoded_buf_idx = 0;
564 
565  while (rd_idx < read_len) {
566  unsigned int type = read_buf[rd_idx++];
567  uint16_t data_len = le_to_h_u16(&read_buf[rd_idx]);
568  rd_idx += 2;
569  if (decoded_buf_idx > decoded_buf_len) {
570  LOG_ERROR("CH347 decoded_buf too small");
571  free(read_buf);
572  return ERROR_FAIL;
573  }
574 
575  // nothing to decode? Only read to make the CH347 happy!
576  if (!decoded_buf) {
577  rd_idx += data_len;
578  continue;
579  }
580 
581  switch (type) {
582  case CH347_CMD_GPIO:
583  case CH347_CMD_JTAG_INIT:
584  case CH347_CMD_SWD_INIT:
585  case CH347_CMD_PIN_SET:
587  // for all bytewise commands: copy the data bytes
588  memcpy(&decoded_buf[decoded_buf_idx], &read_buf[rd_idx], data_len);
589  decoded_buf_idx += data_len;
590  rd_idx += data_len;
591  break;
593  // for CH347_CMD_JTAG_BIT_OP_RD we need to copy bit by bit
594  for (int i = 0; i < data_len; i++) {
595  if (read_buf[rd_idx + i] & BIT(0))
596  decoded_buf[decoded_buf_idx + i / 8] |= BIT(i % 8);
597  else
598  decoded_buf[decoded_buf_idx + i / 8] &= ~(BIT(i % 8));
599  }
600  rd_idx += data_len;
601  decoded_buf_idx += DIV_ROUND_UP(data_len, 8);
602  break;
603  default:
604  LOG_ERROR("CH347 read command fail");
605  free(read_buf);
606  return ERROR_FAIL;
607  }
608  }
609 
610  free(read_buf);
611  return ERROR_OK;
612 }
613 
621 static int ch347_scan_data_to_fields(uint8_t *decoded_buf, int decoded_buf_len)
622 {
623  int byte_offset = 0;
624  struct ch347_scan *scan;
625  struct ch347_scan *tmp;
626  int bit_offset = 0;
628  for (int i = 0; i < scan->fields_len; i++) {
629  int num_bits = scan->fields[i].num_bits;
630  LOG_DEBUG_IO("fields[%d].in_value[%d], read from bit offset: %d", i, num_bits, bit_offset);
631  // only if we need the value
632  if (scan->fields[i].in_value) {
633  uint8_t *capture_buf = malloc(DIV_ROUND_UP(num_bits, 8));
634  if (!capture_buf) {
635  LOG_ERROR("malloc failed");
636  return ERROR_FAIL;
637  }
638  uint8_t *captured = buf_set_buf(decoded_buf, bit_offset, capture_buf, 0, num_bits);
639 
641  char *str = buf_to_hex_str(captured, num_bits);
642  LOG_DEBUG_IO("size=%d, buf=[%s]", num_bits, str);
643  free(str);
644  }
645 
646  buf_cpy(captured, scan->fields[i].in_value, num_bits);
647  free(capture_buf);
648  } else {
649  LOG_DEBUG_IO("field skipped");
650  }
651  bit_offset += num_bits;
652  }
653  list_del(&scan->queue);
654  free(scan);
655  /* after one round of scan field processing the
656  next data bits are read from the next data byte
657  => round up and calculate the next start bit */
658  byte_offset = DIV_ROUND_UP(bit_offset, 8);
659  bit_offset = byte_offset * 8;
660  }
661 
662  // if not all bytes are transferred: put the rest into single_read buffer
663  if (byte_offset < decoded_buf_len) {
664  ch347.singe_read_len = decoded_buf_len - byte_offset;
665  LOG_DEBUG_IO("single read of %d bytes", ch347.singe_read_len);
667  LOG_ERROR("Can't read more than %d bytes for a single command!", CH347_SINGLE_CMD_MAX_READ);
669  }
670  memcpy(ch347.single_read, &decoded_buf[byte_offset], ch347.singe_read_len);
671  }
672 
673  return ERROR_OK;
674 }
675 
676 static void ch347_scan_queue_free(void)
677 {
678  while (!list_empty(&ch347.scan_queue)) {
680  list_del(&scan->queue);
681  free(scan);
682  }
683 }
684 
691 static int ch347_cmd_transmit_queue(void)
692 {
693  // queue last command
694  int retval = ch347_cmd_from_scratchpad();
695  if (retval != ERROR_OK) {
697  return retval;
698  }
699 
700  // nothing to do! => done here
701  if (list_empty(&ch347.cmd_queue))
702  return ERROR_OK;
703 
704  // calculate the needed buffer length for all decoded bytes
705  struct ch347_cmd *cmd;
706  int decoded_buf_len = 0;
708  if (cmd->read_len > 0)
709  decoded_buf_len += ch347_is_single_cmd_type(cmd->type) ?
710  cmd->read_len : DIV_ROUND_UP(cmd->tdo_bit_count, 8);
711 
712  // create the buffer for all decoded bytes
713  uint8_t *decoded_buf = NULL;
714  int decoded_buf_idx = 0;
715  if (decoded_buf_len > 0) {
716  decoded_buf = malloc(decoded_buf_len);
717  if (!decoded_buf) {
718  LOG_ERROR("malloc failed");
720  return ERROR_FAIL;
721  }
722  }
723 
724  while (!list_empty(&ch347.cmd_queue)) {
725  struct ch347_cmd *last_cmd = NULL;
726  int total_len = 0;
727  int total_tdo_count = 0;
728  int bytes_to_write = 0;
729 
731  total_len += CH347_CMD_HEADER + cmd->write_data_len;
732  total_tdo_count += cmd->tdo_bit_count;
733  // don't exceed max length or max TDO bit count
734  if (total_len >= ch347.max_len || total_tdo_count >= HW_TDO_BUF_SIZE)
735  break;
736  // remember the last cmd to send and bytes to send
737  last_cmd = cmd;
738  bytes_to_write = total_len;
739  }
740 
741  // sanity checks
742  if (!last_cmd || bytes_to_write == 0) {
743  LOG_ERROR("Nothing to send!");
744  free(decoded_buf);
746  return ERROR_FAIL;
747  }
748 
749  // create the write buffer
750  uint8_t *write_buf = malloc(bytes_to_write);
751  if (!write_buf) {
752  LOG_ERROR("malloc failed");
753  free(decoded_buf);
755  return ERROR_FAIL;
756  }
757 
758  int idx = 0;
759  int bytes_to_read = 0;
760  int current_decoded_buf_len = 0;
761  struct ch347_cmd *tmp;
762 
764  // copy command to buffer
765  write_buf[idx++] = cmd->type;
766  h_u16_to_le(&write_buf[idx], cmd->write_data_len);
767  idx += 2;
768  memcpy(&write_buf[idx], cmd->write_data, cmd->write_data_len);
769  idx += cmd->write_data_len;
770  // need to read something back?
771  if (cmd->read_len > 0) {
772  bytes_to_read += CH347_CMD_HEADER + cmd->read_len;
773  current_decoded_buf_len += ch347_is_single_cmd_type(cmd->type) ?
774  cmd->read_len : DIV_ROUND_UP(cmd->tdo_bit_count, 8);
775  }
776 
777  // cmd data no longer needed
778  list_del(&cmd->queue);
779  free(cmd->write_data);
780  free(cmd);
781 
782  if (cmd == last_cmd)
783  break;
784  }
785 
786  // write data to device
787  retval = ch347_write_data(write_buf, &idx);
788  free(write_buf);
789  if (retval != ERROR_OK) {
790  free(decoded_buf);
792  return retval;
793  }
794 
795  if (!bytes_to_read)
796  continue;
797 
798  // Need only to execute a read without decoding the data to make the CH347 happy?
799  if (!current_decoded_buf_len) {
800  // read but don't decode anything
801  retval = ch347_read_scan(NULL, 0, bytes_to_read);
802  } else {
803  retval = ch347_read_scan(&decoded_buf[decoded_buf_idx], current_decoded_buf_len, bytes_to_read);
804  decoded_buf_idx += current_decoded_buf_len;
805  }
806 
807  if (retval != ERROR_OK) {
808  free(decoded_buf);
810  return retval;
811  }
812  }
813 
814  // something decoded from the data read back from CH347?
815  if (decoded_buf) {
816  // put the decoded data into the scan fields or single_read buffer
817  retval = ch347_scan_data_to_fields(decoded_buf, decoded_buf_len);
818  free(decoded_buf);
819  }
820 
821  return retval;
822 }
823 
830 static int ch347_cmd_start_next(uint8_t type)
831 {
832  // different command type or non chainable command? (GPIO commands can't be concat)
833  uint8_t prev_type = ch347.scratchpad_cmd_type;
834  if (prev_type != type || ch347_is_single_cmd_type(type)) {
835  // something written in the scratchpad? => store it as command
836  if (prev_type != 0 && ch347.scratchpad_idx > 0) {
837  int retval = ch347_cmd_from_scratchpad();
838  if (retval != ERROR_OK)
839  return retval;
840 
841  /* if the last queued command is not chainable we should send it immediately
842  because e.g. the GPIO command can't be combined with any other command */
843  if (ch347_is_single_cmd_type(prev_type)) {
844  retval = ch347_cmd_transmit_queue();
845  if (retval != ERROR_OK)
846  return retval;
847  }
848  }
849 
850  /* before we can send non chainable command ("single" like GPIO command) we should send all
851  other commands because we can't send it together with other commands */
853  int retval = ch347_cmd_transmit_queue();
854  if (retval != ERROR_OK)
855  return retval;
856  }
857 
858  // store the next command type
860  }
861 
862  return ERROR_OK;
863 }
864 
872 static int ch347_scan_queue_fields(struct scan_field *scan_fields, int scan_fields_len)
873 {
874  // malloc for the scan struct
875  struct ch347_scan *scan = malloc(sizeof(struct ch347_scan));
876  if (!scan) {
877  LOG_ERROR("malloc failed");
878  return ERROR_FAIL;
879  }
880 
881  scan->fields = scan_fields;
882  scan->fields_len = scan_fields_len;
883  list_add_tail(&scan->queue, &ch347.scan_queue);
884  return ERROR_OK;
885 }
886 
895 static int ch347_single_read_get_byte(int read_buf_idx, uint8_t *byte)
896 {
897  int retval = ch347_cmd_transmit_queue();
898  if (retval != ERROR_OK)
899  return retval;
900 
901  if (read_buf_idx > CH347_SINGLE_CMD_MAX_READ || read_buf_idx < 0) {
902  LOG_ERROR("read_buf_idx out of range");
903  return ERROR_FAIL;
904  }
905 
906  *byte = ch347.single_read[read_buf_idx];
907  return ERROR_OK;
908 }
909 
915 {
916  // if full create a new command in the queue
918  uint8_t type = ch347.scratchpad_cmd_type;
921  }
922 }
923 
932 static int ch347_scratchpad_add_byte(uint8_t byte)
933 {
934  if (ch347.scratchpad_cmd_type == 0) {
935  LOG_ERROR("call ch347_next_cmd first!");
936  return ERROR_FAIL;
937  }
938 
941  return ERROR_OK;
942 }
943 
952 {
953  uint8_t pins = ch347.tms_pin | ch347.tdi_pin | ch347.tck_pin | ch347.trst_pin;
954 
956  pins |= ch347.srst_pin;
957 
958  return ch347_scratchpad_add_byte(pins);
959 }
960 
971 static int ch347_scratchpad_add_bytes(uint8_t *bytes, int count)
972 {
973  if (ch347.scratchpad_cmd_type == 0) {
974  LOG_ERROR("call ch347_next_cmd first!");
975  return ERROR_FAIL;
976  }
977 
978  int remaining = count;
979  int bytes_idx = 0;
980  while (remaining > 0) {
981  int bytes_to_store = ch347.scratchpad_idx + remaining <= UCMDPKT_DATA_MAX_BYTES_USBHS ?
983 
984  if (bytes)
985  memcpy(&ch347.scratchpad[ch347.scratchpad_idx], &bytes[bytes_idx], bytes_to_store);
986  else
987  memset(&ch347.scratchpad[ch347.scratchpad_idx], 0, bytes_to_store);
988 
989  ch347.scratchpad_idx += bytes_to_store;
990  bytes_idx += bytes_to_store;
991  remaining -= bytes_to_store;
993  }
994 
995  return ERROR_OK;
996 }
997 
998 /* Drive SRST low at init only when the target is connected under reset.
999  * srst_nogate is required as well: without it, JTAG is gated while SRST
1000  * is asserted. */
1002 {
1003  enum reset_types cfg = jtag_get_reset_config();
1004 
1005  return (cfg & (RESET_CNCT_UNDER_SRST | RESET_SRST_NO_GATING))
1007 }
1008 
1031 static int ch347_srst_enable(void)
1032 {
1034  if (retval != ERROR_OK)
1035  return retval;
1036 
1037  uint8_t cmd_data[] = {0x00, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1038  retval = ch347_scratchpad_add_bytes(cmd_data, ARRAY_SIZE(cmd_data));
1039  if (retval != ERROR_OK)
1040  return retval;
1041 
1042  uint8_t init_result;
1043  retval = ch347_single_read_get_byte(0, &init_result);
1044  if (retval != ERROR_OK)
1045  return retval;
1046 
1047  LOG_DEBUG("CH347F PIN_SET result %02" PRIx8, init_result);
1048 
1050  /* The pin byte merges bit 6 only while this flag is set. */
1053  if (retval == ERROR_OK)
1054  retval = ch347_scratchpad_add_pin_byte();
1055  if (retval == ERROR_OK)
1056  retval = ch347_cmd_transmit_queue();
1057  return retval;
1058 }
1059 
1068 {
1069  ch347.tms_pin = tms ? TMS_H : TMS_L;
1070  ch347.tck_pin = TCK_L;
1071  int retval = ch347_scratchpad_add_pin_byte();
1072  if (retval != ERROR_OK)
1073  return retval;
1074 
1075  ch347.tck_pin = TCK_H;
1077 }
1078 
1086 {
1088  if (retval != ERROR_OK)
1089  return retval;
1090 
1091  bool tms = ch347.tms_pin == TMS_H;
1092  for (int i = 0; i < count; i++) {
1093  retval = ch347_scratchpad_add_clock_tms(tms);
1094  if (retval != ERROR_OK)
1095  return retval;
1096  }
1097 
1098  return ERROR_OK;
1099 }
1100 
1107 {
1108  ch347.tck_pin = TCK_L;
1110 }
1111 
1120 static int ch347_scratchpad_add_tms_change(const uint8_t *tms_value, int step, int skip)
1121 {
1122  LOG_DEBUG_IO("TMS Value: %02x..., step = %d, skip = %d", tms_value[0], step, skip);
1123 
1125  if (retval != ERROR_OK)
1126  return retval;
1127 
1128  for (int i = skip; i < step; i++) {
1129  retval = ch347_scratchpad_add_clock_tms((tms_value[i / 8] >> (i % 8)) & BIT(0));
1130  if (retval != ERROR_OK)
1131  return retval;
1132  }
1133 
1135 }
1136 
1144 {
1145  LOG_DEBUG_IO("num_states=%d, last_state=%d", cmd->num_states, cmd->path[cmd->num_states - 1]);
1146 
1148  if (retval != ERROR_OK)
1149  return retval;
1150 
1151  for (unsigned int i = 0; i < cmd->num_states; i++) {
1152  if (tap_state_transition(tap_get_state(), false) == cmd->path[i]) {
1153  retval = ch347_scratchpad_add_clock_tms(0);
1154  if (retval != ERROR_OK)
1155  return retval;
1156  } else if (tap_state_transition(tap_get_state(), true) == cmd->path[i]) {
1157  retval = ch347_scratchpad_add_clock_tms(1);
1158  if (retval != ERROR_OK)
1159  return retval;
1160  } else {
1161  LOG_ERROR("No transition possible!");
1163  }
1164  tap_set_state(cmd->path[i]);
1165  }
1166 
1168 }
1169 
1178 {
1179  uint8_t tms_scan;
1180  int tms_len;
1181 
1183  // don't do anything if we are already in the right state; but do execute always the TAP_RESET
1184  if (tap_get_state() == state && state != TAP_RESET)
1185  return ERROR_OK;
1186 
1187  tms_scan = tap_get_tms_path(tap_get_state(), state);
1189  int retval = ch347_scratchpad_add_tms_change(&tms_scan, tms_len, skip);
1191  return retval;
1192 }
1193 
1203 static int ch347_scratchpad_add_write_read(struct scan_command *cmd, uint8_t *bits, int bits_len, enum scan_type scan)
1204 {
1205  // the bits and bytes to transfer
1206  int byte_count = bits_len / 8;
1207  int bit_count = bits_len % 8;
1208 
1209  // only bytes are not possible because we need to set TMS high for the last bit
1210  if (byte_count > 0 && bit_count == 0) {
1211  // make one byte to eight bits
1212  byte_count--;
1213  bit_count = 8;
1214  }
1215 
1216  // in bitwise mode only bits are allowed
1217  if (ch347.use_bitwise_mode) {
1218  byte_count = 0;
1219  bit_count = bits_len;
1220  }
1221 
1222  bool is_read = (scan == SCAN_IN || scan == SCAN_IO);
1223 
1224  // if we need to send bytes
1225  if (byte_count > 0) {
1226  // start the next cmd and copy the data out bytes to it
1228  if (retval != ERROR_OK)
1229  return retval;
1230 
1231  if (bits)
1232  retval = ch347_scratchpad_add_bytes(bits, byte_count);
1233  else
1234  retval = ch347_scratchpad_add_bytes(NULL, byte_count);
1235 
1236  if (retval != ERROR_OK)
1237  return retval;
1238  }
1239 
1240  // bits are always need to send; no possibility to not send bits
1242  if (retval != ERROR_OK)
1243  return retval;
1244 
1245  ch347.tms_pin = TMS_L;
1246  ch347.tdi_pin = TDI_L;
1247 
1248  for (int i = 0; i < bit_count; i++) {
1249  if (bits)
1250  ch347.tdi_pin = ((bits[byte_count + i / 8] >> i % 8) & BIT(0)) ? TDI_H : TDI_L;
1251 
1252  // for the last bit set TMS high to exit the shift state
1253  if (i + 1 == bit_count)
1254  ch347.tms_pin = TMS_H;
1255 
1256  ch347.tck_pin = TCK_L;
1257  retval = ch347_scratchpad_add_pin_byte();
1258  if (retval != ERROR_OK)
1259  return retval;
1260 
1261  ch347.tck_pin = TCK_H;
1262  retval = ch347_scratchpad_add_pin_byte();
1263  if (retval != ERROR_OK)
1264  return retval;
1265 
1266  /* cut the package after each MAX_BITS_PER_BIT_OP bits because it
1267  needs a dividable by 8 bits package */
1268  if (i > 0 && (i + 1) % MAX_BITS_PER_BIT_OP == 0) {
1269  retval = ch347_cmd_from_scratchpad();
1270  if (retval != ERROR_OK)
1271  return retval;
1272 
1274  if (retval != ERROR_OK)
1275  return retval;
1276  }
1277  }
1278 
1279  // one TCK_L after the last bit
1281  if (retval != ERROR_OK)
1282  return retval;
1283 
1284  // if read is involved we need to queue the scan fields
1285  if (is_read)
1286  return ch347_scan_queue_fields(cmd->fields, cmd->num_fields);
1287 
1288  return ERROR_OK;
1289 }
1290 
1298 static int ch347_scratchpad_add_run_test(int cycles, enum tap_state state)
1299 {
1300  LOG_DEBUG_IO("cycles=%d, end_state=%d", cycles, state);
1301  int retval;
1302  if (tap_get_state() != TAP_IDLE) {
1304  if (retval != ERROR_OK)
1305  return retval;
1306  }
1307 
1308  retval = ch347_scratchpad_add_stableclocks(cycles);
1309  if (retval != ERROR_OK)
1310  return retval;
1311 
1313 }
1314 
1322 {
1323  static const char *const type2str[] = {"", "SCAN_IN", "SCAN_OUT", "SCAN_IO"};
1324 
1325  enum scan_type type = jtag_scan_type(cmd);
1326  uint8_t *buf = NULL;
1327  int scan_bits = jtag_build_buffer(cmd, &buf);
1328 
1329  // add a move to IRSHIFT or DRSHIFT state
1330  int retval;
1331  if (cmd->ir_scan)
1333  else
1335 
1336  if (retval != ERROR_OK) {
1337  free(buf);
1338  return retval;
1339  }
1340 
1342  char *log_buf = buf_to_hex_str(buf, scan_bits);
1343  LOG_DEBUG_IO("scan=%s, type=%s, bits=%d, buf=[%s], end_state=%d",
1344  cmd->ir_scan ? "IRSCAN" : "DRSCAN",
1345  type2str[type],
1346  scan_bits, log_buf, cmd->end_state);
1347  free(log_buf);
1348  }
1349 
1350  retval = ch347_scratchpad_add_write_read(cmd, buf, scan_bits, type);
1351  free(buf);
1352  if (retval != ERROR_OK)
1353  return retval;
1354 
1355  // add a move to the final state
1356  return ch347_scratchpad_add_move_state(cmd->end_state, 1);
1357 }
1358 
1364 static uint8_t ch347_usable_gpios(void)
1365 {
1367 }
1368 
1382 static int ch347_gpio_cmd(unsigned int gpio, uint8_t value, uint8_t *state)
1383 {
1384  if (gpio >= GPIO_CNT) {
1385  LOG_ERROR("GPIO %u out of range", gpio);
1386  return ERROR_FAIL;
1387  }
1388 
1389  int retval = ch347_cmd_start_next(CH347_CMD_GPIO);
1390  if (retval != ERROR_OK)
1391  return retval;
1392 
1393  uint8_t gpios[GPIO_CNT];
1394  memset(gpios, 0, GPIO_CNT);
1395  gpios[gpio] = value;
1397  if (retval != ERROR_OK)
1398  return retval;
1399 
1400  return ch347_single_read_get_byte(gpio, state);
1401 }
1402 
1414 static uint8_t ch347_gpio_drive_value(bool level, enum adapter_gpio_drive_mode drive)
1415 {
1416  switch (drive) {
1418  return level ? GPIO_SET_INPUT : GPIO_SET_L;
1420  return level ? GPIO_SET_H : GPIO_SET_INPUT;
1422  break;
1423  }
1424 
1425  return level ? GPIO_SET_H : GPIO_SET_L;
1426 }
1427 
1435 static int ch347_gpio_set(int gpio, bool data)
1436 {
1437  /* always set bits 7 and 6 for GPIO enable
1438  bits 5 and 4 for pin direction output
1439  bit 3 is the data bit */
1440  uint8_t state;
1441  int retval = ch347_gpio_cmd(gpio, data ? GPIO_SET_H : GPIO_SET_L, &state);
1442  if (retval != ERROR_OK)
1443  return retval;
1444 
1445  // check in the read if the bit is set/cleared correctly
1446  if ((bool)(state & BIT(6)) != data) {
1447  LOG_ERROR("Output not set.");
1448  return ERROR_FAIL;
1449  }
1450 
1451  return ERROR_OK;
1452 }
1453 
1460 static int ch347_activity_led_set(int led_state)
1461 {
1462  if (ch347_activity_led_gpio_pin != 0xFF)
1463  return ch347_gpio_set(ch347_activity_led_gpio_pin, ch347_activity_led_active_high ? led_state : 1 - led_state);
1464 
1465  // not configured => also OK
1466  return ERROR_OK;
1467 }
1468 
1477 {
1478  static bool warned;
1479  enum adapter_gpio_drive_mode drive =
1481 
1482  if (warned || !(jtag_get_reset_config() & RESET_HAS_SRST))
1483  return;
1484  if (drive == ADAPTER_GPIO_DRIVE_MODE_PUSH_PULL)
1485  return;
1486 
1487  warned = true;
1488  LOG_WARNING("CH347F dedicated SRST is push-pull and ignores "
1489  "the reset_config drive mode; use 'reset_config srst_push_pull'");
1490 }
1491 
1510 static int ch347_reset(int trst, int srst)
1511 {
1512  int retval;
1513  LOG_DEBUG_IO("reset trst: %i srst %i", trst, srst);
1514 
1515  if (swd_mode) {
1516  if (trst)
1517  LOG_WARNING("Asserting TRST not supported in SWD mode!");
1518 
1519  if (ch347_srst_gpio_pin == 0xFF) {
1520  if (srst) {
1521  LOG_ERROR("Asserting SRST not supported: no usable GPIO configured");
1522  return ERROR_FAIL;
1523  }
1524  return ERROR_OK;
1525  }
1526 
1527  /* Honour the drive mode of 'reset_config'. It defaults to open drain,
1528  which releases the pin instead of driving the inactive level, so the
1529  target can keep the line low on its own.
1530  Don't verify the readback: it reports the pin level, and the target
1531  is free to hold the reset line low itself, e.g. while it is in a
1532  watchdog reset loop. */
1533  bool level = srst ? ch347_srst_active_high : !ch347_srst_active_high;
1534  uint8_t value = ch347_gpio_drive_value(level,
1536  uint8_t state;
1537  return ch347_gpio_cmd(ch347_srst_gpio_pin, value, &state);
1538  }
1539 
1540  if (srst && !ch347_dedicated_srst_enabled) {
1541  LOG_ERROR("Asserting SRST not supported");
1542  return ERROR_FAIL;
1543  }
1544 
1546  if (retval != ERROR_OK)
1547  return retval;
1548 
1549  ch347.trst_pin = trst ? TRST_L : TRST_H;
1552  ch347.srst_pin = srst ? SRST_L : SRST_H;
1553  }
1554  retval = ch347_scratchpad_add_pin_byte();
1555  if (retval != ERROR_OK)
1556  return retval;
1557 
1559  if (retval != ERROR_OK)
1560  return retval;
1561 
1562  return ch347_cmd_transmit_queue();
1563 }
1564 
1571 static int ch347_sleep(int us)
1572 {
1573  LOG_DEBUG_IO("us=%d", us);
1574  int retval = ch347_cmd_transmit_queue();
1575  jtag_sleep(us);
1576  return retval;
1577 }
1578 
1584 static int ch347_execute_queue(struct jtag_command *cmd_queue)
1585 {
1586  struct jtag_command *cmd = cmd_queue;
1587 
1588  int retval = ch347_activity_led_set(LED_ON);
1589  if (retval != ERROR_OK)
1590  return retval;
1591 
1592  while (retval == ERROR_OK && cmd) {
1593  switch (cmd->type) {
1594  case JTAG_RUNTEST:
1595  retval = ch347_scratchpad_add_run_test(cmd->cmd.runtest->num_cycles, cmd->cmd.runtest->end_state);
1596  break;
1597  case JTAG_STABLECLOCKS:
1598  retval = ch347_scratchpad_add_stableclocks(cmd->cmd.stableclocks->num_cycles);
1599  break;
1600  case JTAG_TLR_RESET:
1601  retval = ch347_scratchpad_add_move_state(cmd->cmd.statemove->end_state, 0);
1602  break;
1603  case JTAG_PATHMOVE:
1604  retval = ch347_scratchpad_add_move_path(cmd->cmd.pathmove);
1605  break;
1606  case JTAG_TMS:
1607  retval = ch347_scratchpad_add_tms_change(cmd->cmd.tms->bits, cmd->cmd.tms->num_bits, 0);
1608  break;
1609  case JTAG_SLEEP:
1610  retval = ch347_sleep(cmd->cmd.sleep->us);
1611  break;
1612  case JTAG_SCAN:
1613  retval = ch347_scratchpad_add_scan(cmd->cmd.scan);
1614  break;
1615  default:
1616  LOG_ERROR("BUG: unknown JTAG command type 0x%X", cmd->type);
1617  retval = ERROR_FAIL;
1618  break;
1619  }
1620 
1621  cmd = cmd->next;
1622  }
1623 
1624  if (retval != ERROR_OK)
1625  return retval;
1626 
1627  retval = ch347_cmd_transmit_queue();
1628  if (retval != ERROR_OK)
1629  return retval;
1630 
1632 }
1633 
1639 static int ch347_open_device(void)
1640 {
1641  const uint16_t *ch347_vids = default_ch347_vids;
1642  const uint16_t *ch347_pids = default_ch347_pids;
1643 
1644  if (adapter_usb_get_vids()[0] != 0) {
1645  ch347_vids = adapter_usb_get_vids();
1646  ch347_pids = adapter_usb_get_pids();
1647  }
1648 
1649  int retval = jtag_libusb_open(ch347_vids, ch347_pids,
1651  if (retval != ERROR_OK) {
1652  char error_message[256];
1653  snprintf(error_message, sizeof(error_message), "CH347 not found. Tried VID/PID pairs: ");
1654  for (int i = 0; ch347_vids[i] != 0; i++)
1655  snprintf(error_message + strlen(error_message), sizeof(error_message) - strlen(error_message),
1656  "%04x:%04x ", ch347_vids[i], ch347_pids[i]);
1657 
1658  LOG_ERROR("%s", error_message);
1659  return retval;
1660  }
1661 
1662  struct libusb_device_descriptor ch347_device_descriptor;
1663  libusb_device *device = libusb_get_device(ch347_handle);
1664  if (!device) {
1665  LOG_ERROR("CH347 error calling libusb_get_device");
1667  return ERROR_FAIL;
1668  }
1669 
1670  retval = libusb_get_device_descriptor(device, &ch347_device_descriptor);
1671  if (retval != ERROR_OK) {
1672  LOG_ERROR("CH347 error getting device descriptor: %s", libusb_error_name(retval));
1674  return retval;
1675  }
1676 
1677  // Fix for CH347F on ARM64
1678  // Force set configuration 1 (required on some ARM64 platforms)
1679  retval = libusb_set_configuration(ch347_handle, 1);
1680  if (retval != LIBUSB_SUCCESS && retval != LIBUSB_ERROR_BUSY)
1681  LOG_WARNING("CH347 set_configuration failed: %s", libusb_error_name(retval));
1682 
1683  // CH347T / CH347F detection
1684  // if we can claim interface 4 we found a CH347F chip; if we can claim interface 2 we found CH347T chip
1685  retval = libusb_claim_interface(ch347_handle, CH347F_MPHSI_INTERFACE);
1686  if (retval != ERROR_OK) {
1687  retval = libusb_claim_interface(ch347_handle, CH347T_MPHSI_INTERFACE);
1688  if (retval != ERROR_OK) {
1689  LOG_ERROR("CH347 unable to claim interface: %s", libusb_error_name(retval));
1691  return retval;
1692  }
1694  } else {
1696  }
1697 
1698  char firmware_version;
1700  LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
1701  VENDOR_VERSION, 0, 0, &firmware_version, sizeof(firmware_version),
1703  if (retval != ERROR_OK) {
1704  LOG_ERROR("CH347 unable to get firmware version");
1706  return retval;
1707  }
1708 
1709  char manufacturer[256 + 1];
1710  if (libusb_get_string_descriptor_ascii(ch347_handle, ch347_device_descriptor.iManufacturer,
1711  (unsigned char *)manufacturer, sizeof(manufacturer) - 1) < 0) {
1712  strcpy(manufacturer, "(unknown)");
1713  }
1714  char product[256 + 1];
1715  if (libusb_get_string_descriptor_ascii(ch347_handle, ch347_device_descriptor.iProduct,
1716  (unsigned char *)product, sizeof(product) - 1) < 0) {
1717  strcpy(product, "(unknown)");
1718  }
1719  char serial_number[256 + 1];
1720  if (libusb_get_string_descriptor_ascii(ch347_handle, ch347_device_descriptor.iSerialNumber,
1721  (unsigned char *)serial_number, sizeof(serial_number) - 1) < 0) {
1722  strcpy(serial_number, "(unknown)");
1723  }
1724 
1725  LOG_INFO("CH347%c %s from vendor %s with serial number %s found. (Chip version=%X.%02X, Firmware=0x%02X)",
1726  ch347.chip_variant == CH347T ? 'T' : ch347.chip_variant == CH347F ? 'F' : '?',
1727  product,
1728  manufacturer,
1729  serial_number,
1730  (ch347_device_descriptor.bcdDevice >> 8) & 0xFF,
1731  ch347_device_descriptor.bcdDevice & 0xFF,
1732  firmware_version);
1733 
1734  if (ch347.chip_variant == CH347T && ch347_device_descriptor.bcdDevice < BYTEWISE_MODE_VERSION) {
1735  LOG_INFO("CH347T old version of the chip, JTAG only working in bitwise mode. For bytewise mode at least version %X.%X is needed.",
1736  (BYTEWISE_MODE_VERSION >> 8) & 0xFF,
1737  BYTEWISE_MODE_VERSION & 0xFF);
1738  ch347.use_bitwise_mode = true;
1739  } else {
1740  ch347.use_bitwise_mode = false;
1741  }
1742 
1743  if (ch347.chip_variant == CH347T) {
1744  if (swd_mode) {
1745  ch347.swclk_5mhz_supported = ch347_device_descriptor.bcdDevice >= 0x544;
1746 
1747  if (ch347_device_descriptor.bcdDevice < 0x441)
1748  LOG_WARNING("CH347T version older than 4.41 probably does not support SWD transport");
1749 
1750  if (ch347_device_descriptor.bcdDevice == 0x441)
1751  LOG_WARNING("If CH347T version 4.41 cannot connect or SWD fails often, insert a resistor to SWDIO circuit");
1752 
1753  } else if (ch347_device_descriptor.bcdDevice == 0x241) {
1754  LOG_WARNING("CH347T version 2.41 has very weird clock timing, may not work with a slower JTAG device");
1755  }
1756 
1757  if (ch347_device_descriptor.bcdDevice < 0x544)
1758  LOG_INFO("Please upgrade CH347T firmware to a production version >= 5.44");
1759 
1760  } else if (ch347.chip_variant == CH347F) {
1761  ch347.swclk_5mhz_supported = ch347_device_descriptor.bcdDevice >= 0x101;
1762 
1763  if (ch347_device_descriptor.bcdDevice < 0x101)
1764  LOG_INFO("Please upgrade CH347F firmware to a production version >= 1.1");
1765  }
1766 
1767  return ERROR_OK;
1768 }
1769 
1775 static int ch347_quit(void)
1776 {
1777  // on close set the LED on, because the state without JTAG is on
1779  int retval = ch347_cmd_transmit_queue();
1781  LOG_DEBUG_IO("CH347 close");
1782  return retval;
1783 }
1784 
1796 static int ch347_adapter_init(uint8_t clock_index, bool *supports_larger_pack_mode)
1797 {
1799  if (retval != ERROR_OK)
1800  return retval;
1801 
1802  retval = ch347_scratchpad_add_byte(0);
1803  if (retval != ERROR_OK)
1804  return retval;
1805 
1806  retval = ch347_scratchpad_add_byte(clock_index);
1807  if (retval != ERROR_OK)
1808  return retval;
1809 
1810  for (int i = 0; i < 4; i++) {
1811  retval = ch347_scratchpad_add_pin_byte();
1812  if (retval != ERROR_OK)
1813  return retval;
1814  }
1815 
1816  uint8_t mode;
1817  retval = ch347_single_read_get_byte(0, &mode);
1818  if (retval != ERROR_OK)
1819  return retval;
1820 
1821  *supports_larger_pack_mode = mode != 0;
1822  return ERROR_OK;
1823 }
1824 
1833 static int ch347_adapter_supports_larger_pack_mode(bool *supports_larger_pack_mode)
1834 {
1835  return ch347_adapter_init(CH347_CMD_INIT_GET_MODE_CLOCK_INDEX_VALUE, supports_larger_pack_mode);
1836 }
1837 
1845 static int ch347_adapter_set_speed(uint8_t clock_index)
1846 {
1847  bool unused;
1848  return ch347_adapter_init(clock_index, &unused);
1849 }
1850 
1857 static int ch347_swd_init_cmd(uint8_t clock_divisor)
1858 {
1860  if (retval != ERROR_OK)
1861  return retval;
1862 
1863  uint8_t cmd_data[] = {0x40, 0x42, 0x0f, 0x00, clock_divisor, 0x00, 0x00, 0x00 };
1864  retval = ch347_scratchpad_add_bytes(cmd_data, ARRAY_SIZE(cmd_data));
1865  if (retval != ERROR_OK)
1866  return retval;
1867 
1868  /* TODO: CH347_CMD_SWD_INIT reads one data byte.
1869  But how can we decide if SWD init was successfully executed?
1870  Return an error code if init was failed */
1871  uint8_t init_result = 0;
1872  retval = ch347_single_read_get_byte(0, &init_result);
1873  LOG_DEBUG("SWD init clk div %" PRIu8 ", result %02" PRIx8,
1874  clock_divisor, init_result);
1875  ch347_swd_context.clk_divisor = clock_divisor;
1876  return retval;
1877 }
1878 
1885 static int ch347_speed_set(int speed_index)
1886 {
1887  if (swd_mode)
1888  return ch347_swd_init_cmd(speed_index);
1889 
1890  int retval = ch347_adapter_set_speed(speed_index);
1891  if (retval != ERROR_OK) {
1892  LOG_ERROR("Couldn't set CH347 speed");
1893  return retval;
1894  }
1895 
1896  return ERROR_OK;
1897 }
1898 
1904 static int ch347_init_pack_size(void)
1905 {
1906  // already set?
1907  if (ch347.pack_size != UNSET)
1908  return ERROR_OK;
1909 
1910  // set the lower limit for starting
1912  bool supports_larger_pack_mode;
1913  int retval = ch347_adapter_supports_larger_pack_mode(&supports_larger_pack_mode);
1914  if (retval != ERROR_OK)
1915  return retval;
1916 
1917  ch347.pack_size = supports_larger_pack_mode ? LARGER_PACK : STANDARD_PACK;
1920  return ERROR_OK;
1921 }
1922 
1930 static int ch347_speed_get(int speed_idx, int *khz)
1931 {
1932  if (swd_mode) {
1933  if (speed_idx)
1934  *khz = DIV_ROUND_UP(CH347_SWD_CLOCK_BASE, speed_idx);
1935  else
1936  *khz = CH347_SWD_CLOCK_MAX;
1937  return ERROR_OK;
1938  }
1939 
1940  int retval = ch347_init_pack_size();
1941  if (retval != ERROR_OK)
1942  return retval;
1943  const int *speeds = ch347.pack_size == STANDARD_PACK ?
1945  *khz = speeds[speed_idx];
1946  return ERROR_OK;
1947 }
1948 
1958 static int ch347_speed_get_index(int khz, int *speed_idx)
1959 {
1960  if (khz == 0) {
1961  LOG_ERROR("Adaptive clocking not supported");
1962  return ERROR_FAIL;
1963  }
1964 
1965  if (swd_mode) {
1967  *speed_idx = 0;
1968  } else {
1969  // Don't allow too low clk speeds: packet processing is limited to ~8 msec
1970  // or triggers host USB disconnect
1971  *speed_idx = MIN(DIV_ROUND_UP(CH347_SWD_CLOCK_BASE, khz),
1973  }
1974  return ERROR_OK;
1975  }
1976 
1977  // the available clock speeds depend on STANDARD_PACK or LARGER_PACK mode support
1978  int retval = ch347_init_pack_size();
1979  if (retval != ERROR_OK)
1980  return retval;
1981  // depending on pack size there are different fixed clock speeds possible
1982  const int *speeds = ch347.pack_size == STANDARD_PACK ?
1984  int length = ch347.pack_size == STANDARD_PACK ?
1986  // find the suitable speed index
1987  int idx = length - 1;
1988  while (idx > 0 && speeds[idx] > khz)
1989  idx--;
1990 
1991  if (speeds[idx] > khz) {
1992  LOG_WARNING("Requested speed of %d kHz is not possible. Using %d kHz",
1993  khz, speeds[idx]);
1994  }
1995  *speed_idx = idx;
1996  return ERROR_OK;
1997 }
1998 
1999 static const struct command_registration ch347_command_handlers[] = {
2000  {
2001  .name = "ch347",
2002  .mode = COMMAND_ANY,
2003  .help = "perform ch347 management",
2004  .usage = "",
2005  },
2007 };
2008 
2018 static void ch347_configure_activity_led(const struct adapter_gpio_config *led_config)
2019 {
2020  uint8_t gpio = led_config->gpio_num;
2021  if (gpio >= GPIO_CNT || (BIT(gpio) & ch347_usable_gpios()) == 0)
2022  return;
2023 
2026 }
2027 
2039 static void ch347_configure_srst_gpio(const struct adapter_gpio_config *srst_config)
2040 {
2041  ch347_srst_active_high = !srst_config->active_low;
2042 
2043  unsigned int gpio;
2044  if (srst_config->gpio_num == ADAPTER_GPIO_NOT_SET) {
2045  // the TRST pin is free in SWD mode, so use it by default
2047  } else {
2048  gpio = srst_config->gpio_num;
2049  if (gpio >= GPIO_CNT || (BIT(gpio) & ch347_usable_gpios()) == 0) {
2050  LOG_ERROR("GPIO %u can't be used for SRST, disabling SRST", gpio);
2051  ch347_srst_gpio_pin = 0xFF;
2052  return;
2053  }
2054  }
2055 
2056  /* Driving the same pin from two functions would let the LED activity
2057  toggle the reset line, so refuse to share it. */
2058  if (gpio == ch347_activity_led_gpio_pin) {
2059  LOG_ERROR("GPIO %u is already used as the activity LED, disabling SRST", gpio);
2060  ch347_srst_gpio_pin = 0xFF;
2061  return;
2062  }
2063 
2064  ch347_srst_gpio_pin = gpio;
2065 }
2066 
2072 static int ch347_init(void)
2073 {
2074  int retval = ch347_open_device();
2075 
2076  if (retval != ERROR_OK) {
2077  LOG_ERROR("CH347 open error");
2078  return retval;
2079  }
2080 
2081  LOG_DEBUG_IO("CH347 open success");
2082 
2083  // CH347 JTAG init
2084  ch347.tck_pin = TCK_L;
2085  ch347.tms_pin = TMS_H;
2086  ch347.tdi_pin = TDI_L;
2087  ch347.trst_pin = TRST_H;
2088  ch347.srst_pin = SRST_H;
2092 
2093  /* Static initial pack_size is STANDARD_PACK (0), which would look already
2094  * probed. max_len stays 0 until the probe, and PIN_SET uses this queue. */
2095  ch347.pack_size = UNSET;
2096 
2098 
2099  if (!swd_mode) {
2100  /* Pin 8 drives strong low after adapter power-up. On CH347F, enable the
2101  * dedicated SRST output and release it, even when reset_config
2102  * does not include SRST. Leave it asserted only for connect_assert_srst
2103  * together with srst_nogate. */
2104  if (ch347.chip_variant == CH347F) {
2105  retval = ch347_init_pack_size();
2106  if (retval != ERROR_OK)
2107  return retval;
2108 
2109  retval = ch347_srst_enable();
2110  if (retval != ERROR_OK) {
2111  LOG_ERROR("CH347F dedicated SRST enable failed");
2112  return retval;
2113  }
2115  }
2117  } else {
2119 
2120  retval = ch347_init_pack_size();
2121  if (retval != ERROR_OK)
2122  return retval;
2123 
2124  retval = ch347_swd_init_cmd(1);
2125  }
2126  return retval;
2127 }
2128 
2134 static int ch347_swd_init(void)
2135 {
2136  LOG_INFO("CH347 SWD mode enabled");
2137  swd_mode = true;
2138  memset(&ch347_swd_context, 0, sizeof(ch347_swd_context));
2139 
2142 
2144  // 0XE8 + 2byte len + N byte cmds
2146  // 0XE8 + 2byte len + N byte ack + data
2148  struct ch347_swd_io *pswd_io = ch347_swd_context.ch347_cmd_buf;
2149  for (int i = 0; i < CH347_MAX_CMD_BUF; i++, pswd_io++) {
2150  INIT_LIST_HEAD(&pswd_io->list_entry);
2152  }
2153  return ERROR_OK;
2154 }
2155 
2157 {
2158  struct ch347_swd_io *pswd_io;
2160  return NULL;
2161 
2163  struct ch347_swd_io, list_entry);
2164  list_del_init(&pswd_io->list_entry);
2165  pswd_io->cmd = 0;
2166  pswd_io->usb_cmd = CH347_CMD_SWD_SEQ_W;
2167  pswd_io->dst = NULL;
2168  return pswd_io;
2169 }
2170 
2171 static int ch347_swd_queue_flush(void)
2172 {
2177  if (retval != ERROR_OK) {
2179  LOG_DEBUG("CH347WriteData error");
2180  return retval;
2181  }
2182 
2186  if (retval != ERROR_OK) {
2188  LOG_DEBUG("CH347ReadData error");
2189  return retval;
2190  }
2191 
2194  LOG_ERROR("write/read failed %d %d",
2197  retval = ERROR_FAIL;
2198  }
2199 
2200  return retval;
2201 }
2202 
2203 static void ch347_write_swd_reg(uint8_t cmd, const uint32_t out)
2204 {
2206  // 8bit + 32bit +1bit
2213  // 0xA0 + 1 byte(3bit ACK)
2214  ch347_swd_context.need_recv_len += (1 + 1);
2216 }
2217 
2218 static void ch347_write_spec_seq(const uint8_t *out, uint8_t out_len)
2219 {
2224  for (uint8_t i = 0; i < DIV_ROUND_UP(out_len, 8); i++)
2225  ch347_swd_context.send_buf[ch347_swd_context.send_len++] = out ? out[i] : 0x00;
2226  ch347_swd_context.need_recv_len += 1; // 0xA1
2227  ch347_swd_context.total_swd_clk += out_len;
2228 }
2229 
2230 static void ch347_read_swd_reg(uint8_t cmd)
2231 {
2236  // 0xA2 + 1 byte(3bit ACK) + 4 byte(data) + 1 byte(1bit parity+1bit trn)
2237  ch347_swd_context.need_recv_len += 1 + 1 + 4 + 1;
2239 }
2240 
2241 static int ch347_swd_switch_out(enum swd_special_seq seq, const uint8_t *out, unsigned int out_len)
2242 {
2243  if ((ch347_swd_context.send_len + (1 + 2 + DIV_ROUND_UP(out_len, 8))) > CH347_MAX_SEND_BUF)
2244  return ERROR_FAIL;
2246  return ERROR_FAIL;
2247 
2248  struct ch347_swd_io *pswd_io = ch347_get_one_swd_io();
2249  if (pswd_io) {
2250  ch347_write_spec_seq(out, out_len);
2252  return ERROR_OK;
2253  } else {
2254  return ERROR_FAIL;
2255  }
2256 }
2257 
2258 // check read/write REG can fill in remaining buff
2259 static bool ch347_chk_buf_size(uint8_t cmd, uint32_t ap_delay_clk)
2260 {
2261  bool flush = false;
2262  int send_len = ch347_swd_context.send_len;
2263  int recv_len = ch347_swd_context.need_recv_len;
2264  int len;
2265  do {
2266  if (cmd & SWD_CMD_RNW) {
2267  len = 1 + 1 + 1 + 1; // 0xA2 + len + rev + cmd
2268  if (send_len + len > CH347_MAX_SEND_BUF)
2269  break;
2270  send_len += len;
2271  len = 1 + 1 + 4 + 1;
2272  /* 0xA2 + 1byte(3bit ack) + 4byte(data) +
2273  1byte(1bit parity+1bit trn) */
2274  if (recv_len + len > CH347_MAX_RECV_BUF)
2275  break;
2276  recv_len += len;
2277  } else { // write reg
2278  len = 1 + 1 + 1 + 1 + 4 + 1;
2279  // 0xA0 + len + rev + cmd +data + parity
2280  if (send_len + len > CH347_MAX_SEND_BUF)
2281  break;
2282  send_len += len;
2283  len = 1 + 1; // 0xA0 + 1byte(3bit ack)
2284  if (recv_len + len > CH347_MAX_RECV_BUF)
2285  break;
2286  recv_len += len;
2287  }
2288  if (cmd & SWD_CMD_APNDP) {
2289  len = 1 + 1 + 1 + DIV_ROUND_UP(ap_delay_clk, 8);
2290  // 0xA1 + Len + rev + n byte(delay)
2291  if (send_len + len > CH347_MAX_SEND_BUF)
2292  break;
2293  len = 1; // 0xA1
2294  if ((recv_len + len) > CH347_MAX_RECV_BUF)
2295  break;
2296  }
2297  // swd packet requests
2298  flush = true;
2299  } while (false);
2300 
2301  return flush;
2302 }
2303 
2304 static int ch347_swd_run_queue_inner(void);
2305 
2306 static int ch347_swd_send_idle(uint32_t ap_delay_clk)
2307 {
2308  bool run_q = false;
2309  struct ch347_swd_io *pswd_io = NULL;
2310  unsigned int max_processing_clk = ch347_swd_context.clk_divisor
2313  bool more_q_runs =
2314  1 + 1 + 1 + DIV_ROUND_UP(ap_delay_clk, 8) > CH347_MAX_SEND_BUF
2315  && ap_delay_clk > max_processing_clk;
2316 
2318  unsigned int expected_total_clk = ch347_swd_context.total_swd_clk + ap_delay_clk;
2319  unsigned int expected_send_len = ch347_swd_context.send_len
2320  + 1 + 1 + 1 + DIV_ROUND_UP(ap_delay_clk, 8);
2321  // 0xA1 + Len + rev + n byte(delay)
2322  unsigned int expected_recv_len = ch347_swd_context.need_recv_len + 1;
2323  // 0xA1
2324  unsigned int expected_time = ch347_swd_context.clk_divisor
2325  ? expected_total_clk * ch347_swd_context.clk_divisor
2326  : expected_total_clk / 5;
2327  if (expected_time > CH347_MAX_PROCESSING_US
2328  || expected_send_len > CH347_MAX_SEND_BUF
2329  || expected_recv_len > CH347_MAX_RECV_BUF) {
2330  int send_room = CH347_MAX_SEND_BUF - ch347_swd_context.send_len - 1 - 1 - 1;
2331  if (more_q_runs
2332  && send_room > 0
2333  && expected_recv_len <= CH347_MAX_RECV_BUF
2334  && ch347_swd_context.total_swd_clk < max_processing_clk) {
2335  pswd_io = ch347_get_one_swd_io();
2336  if (pswd_io) {
2337  // fill the rest of queue/time by part of delay
2338  unsigned int this_delay_clk = MIN(ap_delay_clk, 255);
2339  if ((unsigned int)send_room * 8 < this_delay_clk)
2340  this_delay_clk = send_room * 8;
2341  if (max_processing_clk - ch347_swd_context.total_swd_clk < this_delay_clk)
2342  this_delay_clk = max_processing_clk - ch347_swd_context.total_swd_clk;
2343  LOG_DEBUG_IO("partial delay %u clk", this_delay_clk);
2344  ch347_write_spec_seq(NULL, this_delay_clk);
2346  ap_delay_clk -= this_delay_clk;
2347  }
2348  }
2349  run_q = true;
2350  }
2351  }
2352 
2353  do {
2354  if (!run_q)
2355  pswd_io = ch347_get_one_swd_io();
2356 
2357  if (!pswd_io) {
2358  int retval = ch347_swd_run_queue_inner();
2359  if (retval != ERROR_OK)
2360  return retval;
2361 
2362  pswd_io = ch347_get_one_swd_io();
2363  if (!pswd_io) {
2364  LOG_ERROR("ch347 SWD queue not empty after ch347_swd_run_queue");
2366  return ERROR_FAIL;
2367  }
2368  }
2369 
2370  unsigned int send_room = CH347_MAX_SEND_BUF - 1 - 1 - 1;
2371  unsigned int this_delay_clk = MIN(ap_delay_clk, 255);
2372  if (send_room * 8 < this_delay_clk)
2373  this_delay_clk = send_room * 8;
2374  if (max_processing_clk < this_delay_clk)
2375  this_delay_clk = max_processing_clk;
2376  LOG_DEBUG_IO("delay %u clk", this_delay_clk);
2377  ch347_write_spec_seq(NULL, this_delay_clk);
2379  ap_delay_clk -= this_delay_clk;
2380  run_q = true;
2381  pswd_io = NULL;
2382  } while (ap_delay_clk);
2383  return ERROR_OK;
2384 }
2385 
2387 {
2388  LOG_DEBUG_IO("Executing %u queued transactions", ch347_swd_context.sent_cmd_count);
2390  LOG_DEBUG_IO("Skipping due to previous errors: %d", ch347_swd_context.queued_retval);
2391  goto skip;
2392  }
2393 
2394  int retval = ch347_swd_queue_flush();
2395  if (retval != ERROR_OK)
2396  return retval;
2397 
2399  LOG_ERROR("CH347 usb write/read failed - queued_retval");
2400  goto skip;
2401  }
2402  uint8_t *recv_buf = ch347_swd_context.recv_buf;
2403  int recv_len = 0;
2404  if (recv_buf[recv_len++] != CH347_CMD_SWD) { // 0XE8
2406  LOG_ERROR("CH347 usb write/read failed - not CH347_CMD_SWD");
2407  goto skip;
2408  }
2409 
2410  int cmds_len = le_to_h_u16(&recv_buf[recv_len]);
2411  recv_len += 2; // cmds_len
2412  if ((cmds_len + CH347_CMD_HEADER) > ch347_swd_context.recv_len) {
2414  LOG_ERROR("CH347 usb write/read failed - too long");
2415  goto skip;
2416  }
2417 
2418  struct list_head *tmp;
2419  struct list_head *pos;
2420  struct ch347_swd_io *pswd_io;
2421 
2423  pswd_io = list_entry(pos, struct ch347_swd_io, list_entry);
2424  if (pswd_io->usb_cmd == CH347_CMD_SWD_SEQ_W) {
2425  if (recv_buf[recv_len++] != CH347_CMD_SWD_SEQ_W) {
2427  LOG_ERROR("CH347 usb write/read failed - not CH347_CMD_SWD_SEQ_W");
2428  goto skip;
2429  }
2430  } else { // read/write Reg
2431  uint32_t ack;
2432  bool check_ack;
2433  // read Reg
2434  if (recv_buf[recv_len] == CH347_CMD_SWD_REG_R) {
2435  recv_len++;
2436  ack = buf_get_u32(&recv_buf[recv_len++], 0, 3);
2437  /* Devices do not reply to DP_TARGETSEL write
2438  cmd, ignore received ack */
2439  check_ack = swd_cmd_returns_ack(pswd_io->cmd);
2440  if (pswd_io->cmd & SWD_CMD_RNW) {
2441  uint32_t data = buf_get_u32(&recv_buf[recv_len], 0, 32);
2442 
2443  LOG_CUSTOM_LEVEL((check_ack && ack != SWD_ACK_OK)
2445  "%s%s %s read reg %X = %08" PRIx32,
2446  check_ack ? "" : "ack ignored ",
2447  ack == SWD_ACK_OK ? "OK" :
2448  ack == SWD_ACK_WAIT ? "WAIT" :
2449  ack == SWD_ACK_FAULT ? "FAULT" : "JUNK",
2450  pswd_io->cmd & SWD_CMD_APNDP ? "AP" : "DP",
2451  (pswd_io->cmd & SWD_CMD_A32) >> 1,
2452  data);
2453 
2454  if (ack != SWD_ACK_OK && check_ack) {
2456  goto skip;
2457  }
2458 
2459  uint32_t parity = buf_get_u32(&recv_buf[recv_len], 32, 1);
2460  if (parity != (uint32_t)parity_u32(data)) {
2461  LOG_ERROR("SWD Read data parity mismatch");
2463  goto skip;
2464  }
2465 
2466  if (pswd_io->dst)
2467  *pswd_io->dst = data;
2468  } else {
2470  LOG_ERROR("CH347 usb write/read failed - not SWD_CMD_RNW");
2471  goto skip;
2472  }
2473  recv_len += 5;
2474  } else if (recv_buf[recv_len] == CH347_CMD_SWD_REG_W) {
2475  recv_len++;
2476  ack = buf_get_u32(&recv_buf[recv_len++], 0, 3);
2477  /* Devices do not reply to DP_TARGETSEL write
2478  cmd, ignore received ack */
2479  check_ack = swd_cmd_returns_ack(pswd_io->cmd);
2480 
2481  LOG_CUSTOM_LEVEL((check_ack && ack != SWD_ACK_OK)
2483  "%s%s %s write reg %X = %08" PRIx32,
2484  check_ack ? "" : "ack ignored ",
2485  ack == SWD_ACK_OK ? "OK" :
2486  ack == SWD_ACK_WAIT ? "WAIT" :
2487  ack == SWD_ACK_FAULT ? "FAULT" : "JUNK",
2488  pswd_io->cmd & SWD_CMD_APNDP ? "AP" : "DP",
2489  (pswd_io->cmd & SWD_CMD_A32) >> 1,
2490  pswd_io->value);
2491 
2492  if (ack != SWD_ACK_OK && check_ack) {
2494  goto skip;
2495  }
2496  } else {
2498  LOG_ERROR("CH347 usb write/read failed recv_len = %d", recv_len);
2499  goto skip;
2500  }
2501  }
2502  list_del_init(&pswd_io->list_entry);
2503  list_add_tail(&pswd_io->list_entry,
2505  }
2506 
2507 skip:
2510  pswd_io = list_entry(pos, struct ch347_swd_io, list_entry);
2511  list_del_init(&pswd_io->list_entry);
2512  list_add_tail(&pswd_io->list_entry,
2514  }
2515  }
2516 
2517  // 0xE8 + 2byte len
2519  // 0xE8 + 2byte len
2526  return retval;
2527 }
2528 
2529 static int ch347_swd_run_queue(void)
2530 {
2531  /* A transaction must be followed by another transaction or at least 8
2532  idle cycles to ensure that data is clocked through the AP. */
2533  int retval = ch347_swd_send_idle(8);
2534  if (retval != ERROR_OK)
2535  return retval;
2536 
2537  return ch347_swd_run_queue_inner();
2538 }
2539 
2540 static int ch347_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk)
2541 {
2542  int retval = ERROR_OK;
2543  bool run_q = false;
2545  unsigned int expected_total_clk = ch347_swd_context.total_swd_clk
2546  + 46 // SWD transaction
2547  + ap_delay_clk
2548  + 8; // 8 idle cycles at the end of queue
2549  unsigned int expected_time = ch347_swd_context.clk_divisor
2550  ? expected_total_clk * ch347_swd_context.clk_divisor
2551  : expected_total_clk / 5;
2552  if (expected_time > CH347_MAX_PROCESSING_US) {
2553  LOG_DEBUG_IO("Expected queue run %u cycles, with this cmd %u",
2554  ch347_swd_context.total_swd_clk, expected_total_clk);
2555  run_q = true;
2556  } else if (!ch347_chk_buf_size(cmd, ap_delay_clk)) {
2557  run_q = true;
2558  }
2559  }
2560 
2561  struct ch347_swd_io *pswd_io = NULL;
2562  if (!run_q)
2563  pswd_io = ch347_get_one_swd_io();
2564 
2565  if (!pswd_io) {
2566  retval = ch347_swd_run_queue_inner();
2567  if (retval != ERROR_OK)
2568  return retval;
2569 
2570  pswd_io = ch347_get_one_swd_io();
2571  if (!pswd_io) {
2572  LOG_ERROR("ch347 SWD queue not empty after ch347_swd_run_queue");
2574  return ERROR_FAIL;
2575  }
2576  }
2577 
2578  pswd_io->cmd = cmd | SWD_CMD_START | SWD_CMD_PARK;
2579 
2580  if (pswd_io->cmd & SWD_CMD_RNW) {
2581  pswd_io->usb_cmd = CH347_CMD_SWD_REG_R;
2582  pswd_io->dst = dst;
2583  ch347_read_swd_reg(pswd_io->cmd);
2584  } else {
2585  pswd_io->usb_cmd = CH347_CMD_SWD_REG_W;
2586  pswd_io->value = data;
2587  ch347_write_swd_reg(pswd_io->cmd, data);
2588  }
2589 
2592 
2593  // Insert idle cycles after AP accesses to avoid WAIT
2594  if (ap_delay_clk)
2595  retval = ch347_swd_send_idle(ap_delay_clk);
2596 
2597  return retval;
2598 }
2599 
2601 {
2602  switch (seq) {
2603  case LINE_RESET:
2604  LOG_DEBUG("SWD line reset");
2606  case JTAG_TO_SWD:
2607  LOG_DEBUG("JTAG-to-SWD");
2609  case JTAG_TO_DORMANT:
2610  LOG_DEBUG("JTAG-to-DORMANT");
2612  case SWD_TO_JTAG:
2613  LOG_DEBUG("SWD-to-JTAG");
2615  case SWD_TO_DORMANT:
2616  LOG_DEBUG("SWD-to-DORMANT");
2618  case DORMANT_TO_SWD:
2619  LOG_DEBUG("DORMANT-to-SWD");
2621  case DORMANT_TO_JTAG:
2622  LOG_DEBUG("DORMANT-to-JTAG");
2624  default:
2625  LOG_ERROR("Sequence %d not supported", seq);
2626  return ERROR_FAIL;
2627  }
2628 }
2629 
2630 static int ch347_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
2631 {
2632  assert(cmd & SWD_CMD_RNW);
2633  return ch347_swd_queue_cmd(cmd, value, 0, ap_delay_clk);
2634 }
2635 
2636 static int ch347_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
2637 {
2638  assert(!(cmd & SWD_CMD_RNW));
2639  return ch347_swd_queue_cmd(cmd, NULL, value, ap_delay_clk);
2640 }
2641 
2642 static const struct swd_driver ch347_swd = {
2643  .init = ch347_swd_init,
2644  .switch_seq = ch347_swd_switch_seq,
2645  .read_reg = ch347_swd_read_reg,
2646  .write_reg = ch347_swd_write_reg,
2647  .run = ch347_swd_run_queue,
2648 };
2649 
2650 static struct jtag_interface ch347_interface = {
2652  .execute_queue = ch347_execute_queue,
2653 };
2654 
2656  .name = "ch347",
2657  .transport_ids = TRANSPORT_JTAG | TRANSPORT_SWD,
2658  .transport_preferred_id = TRANSPORT_JTAG,
2659  .commands = ch347_command_handlers,
2660 
2661  .init = ch347_init,
2662  .quit = ch347_quit,
2663  .reset = ch347_reset,
2664  .speed = ch347_speed_set,
2665  .khz = ch347_speed_get_index,
2666  .speed_div = ch347_speed_get,
2667 
2668  .jtag_ops = &ch347_interface,
2669  .swd_ops = &ch347_swd,
2670 };
const struct adapter_gpio_config * adapter_gpio_get_config(void)
Retrieves gpio configuration set with command "adapter gpio <signal_name>".
Definition: adapter.c:1343
const uint16_t * adapter_usb_get_pids(void)
Definition: adapter.c:344
const char * adapter_usb_get_product_name(void)
Definition: adapter.c:354
const uint16_t * adapter_usb_get_vids(void)
Definition: adapter.c:339
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_srst_enable(void)
Enable the dedicated SRST output on CH347F devices.
Definition: ch347.c:1031
static int ch347_scratchpad_add_idle_clock(void)
Function to ensure that the clock is in a low state.
Definition: ch347.c:1106
static int ch347_scratchpad_add_move_state(enum tap_state state, int skip)
Toggle the tap state to the target state.
Definition: ch347.c:1177
#define SRST_L
Definition: ch347.c:73
static int ch347_cmd_from_scratchpad(void)
copy the scratchpad content into a new command in the command queue
Definition: ch347.c:509
struct adapter_driver ch347_adapter_driver
Definition: ch347.c:2655
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:971
#define CH347_MAX_CMD_BUF
Definition: ch347.c:137
static int ch347_init_pack_size(void)
inits ch347.pack_size and ch347.max_len
Definition: ch347.c:1904
static bool ch347_srst_active_high
Definition: ch347.c:277
#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:2241
#define HW_TDO_BUF_SIZE
Definition: ch347.c:101
static int ch347_read_data(uint8_t *data, int *length)
reads data from the CH347 via libusb driver
Definition: ch347.c:432
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:621
#define CH347_CMD_SWD
Definition: ch347.c:129
static const int ch347_larger_pack_clock_speeds[]
Definition: ch347.c:190
#define CH347_EPOUT
Definition: ch347.c:143
static int ch347_quit(void)
CH347 Device Release Function.
Definition: ch347.c:1775
#define CH347F_MPHSI_INTERFACE
Definition: ch347.c:146
#define DEFAULT_CH347F_PRODUCT_ID
Definition: ch347.c:155
static struct ch347_swd_io * ch347_get_one_swd_io(void)
Definition: ch347.c:2156
#define CH347_MAX_PROCESSING_US
Definition: ch347.c:133
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:1143
#define CH347_SWD_CLOCK_MAX
Definition: ch347.c:138
#define DEFAULT_OTHER_PRODUCT_ID
Definition: ch347.c:156
#define CH347_CMD_INIT_GET_MODE_CLOCK_INDEX_VALUE
Definition: ch347.c:110
#define CH347_EPIN
Definition: ch347.c:144
#define CH347T_USABLE_GPIOS
Definition: ch347.c:79
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:468
#define CH347T_TRST_GPIO
Definition: ch347.c:89
#define VENDOR_VERSION
Definition: ch347.c:98
#define GPIO_SET_INPUT
Definition: ch347.c:96
#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:2018
#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:1999
#define DEFAULT_VENDOR_ID
Definition: ch347.c:153
static void ch347_write_swd_reg(uint8_t cmd, const uint32_t out)
Definition: ch347.c:2203
static uint8_t ch347_usable_gpios(void)
Mask of the GPIO's that don't collide with an interface signal.
Definition: ch347.c:1364
static bool ch347_dedicated_srst_enabled
Definition: ch347.c:281
#define CH347_CMD_JTAG_INIT
Definition: ch347.c:118
static int ch347_cmd_start_next(uint8_t type)
starts the next command in the scratchpad.
Definition: ch347.c:830
#define CH347_SWD_CLOCK_BASE
Definition: ch347.c:139
#define USB_READ_TIMEOUT
Definition: ch347.c:148
#define CH347_MAX_SEND_BUF
Definition: ch347.c:135
static bool ch347_is_single_cmd_type(uint8_t type)
Definition: ch347.c:287
static bool swd_mode
Definition: ch347.c:269
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:1382
#define SRST_H
Definition: ch347.c:72
#define CH347_CMD_INIT_READ_LEN
Definition: ch347.c:108
static int ch347_swd_run_queue(void)
Definition: ch347.c:2529
static const struct swd_driver ch347_swd
Definition: ch347.c:2642
#define CH347_SINGLE_CMD_MAX_READ
Definition: ch347.c:125
static int ch347_speed_get_index(int khz, int *speed_idx)
converts the requested speed to a CH347 speed index
Definition: ch347.c:1958
#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:1845
static void ch347_scan_queue_free(void)
Definition: ch347.c:676
static int ch347_open_device(void)
opens the CH347 device via libusb driver
Definition: ch347.c:1639
static int ch347_scratchpad_add_stableclocks(int count)
Function adds a certain amount of TCK pulses without changing the TMS pin.
Definition: ch347.c:1085
#define GPIO_SET_H
Definition: ch347.c:94
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:932
static int ch347_execute_queue(struct jtag_command *cmd_queue)
Executes the command queue.
Definition: ch347.c:1584
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:2039
static int ch347_swd_send_idle(uint32_t ap_delay_clk)
Definition: ch347.c:2306
static uint8_t ch347_srst_gpio_pin
Definition: ch347.c:276
#define TRST_L
Definition: ch347.c:71
#define LED_OFF
Definition: ch347.c:75
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:691
static void log_buf_dump(const uint8_t *data, unsigned int size, bool recv)
Definition: ch347.c:293
static int ch347_activity_led_set(int led_state)
Turn the activity LED on or off.
Definition: ch347.c:1460
#define CH347_CMD_SWD_INIT
Definition: ch347.c:128
static void ch347_warn_dedicated_srst_drive(void)
Warn once when the dedicated CH347F SRST cannot follow reset_config.
Definition: ch347.c:1476
#define CH347F_TRST_GPIO
Definition: ch347.c:90
static int ch347_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
Definition: ch347.c:2636
static int ch347_gpio_set(int gpio, bool data)
Sets a GPIO bit.
Definition: ch347.c:1435
static int ch347_swd_queue_flush(void)
Definition: ch347.c:2171
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:951
static void ch347_write_spec_seq(const uint8_t *out, uint8_t out_len)
Definition: ch347.c:2218
static struct libusb_device_handle * ch347_handle
Definition: ch347.c:283
#define UCMDPKT_DATA_MAX_BYTES_USBHS
Definition: ch347.c:105
static uint16_t default_ch347_pids[]
Definition: ch347.c:271
#define CH347F_USABLE_GPIOS
Definition: ch347.c:85
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:872
static int ch347_scratchpad_add_run_test(int cycles, enum tap_state state)
Toggle the Tap state to run test/idle.
Definition: ch347.c:1298
#define CH347_MAX_RECV_BUF
Definition: ch347.c:136
static int ch347_speed_get(int speed_idx, int *khz)
returns the speed in kHz for the given speed index
Definition: ch347.c:1930
#define CH347_CMD_GPIO
Definition: ch347.c:117
#define CH347_CMD_PIN_SET
Definition: ch347.c:123
static int ch347_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk)
Definition: ch347.c:2540
static int ch347_swd_switch_seq(enum swd_special_seq seq)
Definition: ch347.c:2600
static struct jtag_interface ch347_interface
Definition: ch347.c:2650
ch347_variant
Definition: ch347.c:163
@ CH347F
Definition: ch347.c:165
@ OTHER_PRODUCT_ID
Definition: ch347.c:166
@ CH347T
Definition: ch347.c:164
static bool ch347_chk_buf_size(uint8_t cmd, uint32_t ap_delay_clk)
Definition: ch347.c:2259
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:1203
#define USB_WRITE_TIMEOUT
Definition: ch347.c:147
static int ch347_write_data(uint8_t *data, int *length)
writes data to the CH347 via libusb driver
Definition: ch347.c:396
static struct ch347_info ch347
Definition: ch347.c:282
#define CH347_SWD_CLOCK_MAX_DIVISOR
Definition: ch347.c:141
#define DEFAULT_CH347T_PRODUCT_ID
Definition: ch347.c:154
#define CH347_CMD_JTAG_DATA_SHIFT
Definition: ch347.c:121
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:547
#define CH347_CMD_SWD_REG_R
Definition: ch347.c:132
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:1414
static uint8_t ch347_activity_led_gpio_pin
Definition: ch347.c:273
static bool ch347_dedicated_srst_assert_at_init(void)
Definition: ch347.c:1001
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:1120
static int ch347_swd_init(void)
Initialization for the swd mode.
Definition: ch347.c:2134
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:895
#define TCK_L
Definition: ch347.c:69
#define CH347T_MPHSI_INTERFACE
Definition: ch347.c:145
#define GPIO_CNT
Definition: ch347.c:76
#define TRST_H
Definition: ch347.c:70
#define GPIO_SET_L
Definition: ch347.c:93
static int ch347_sleep(int us)
Flushes the command buffer and sleeps for a specific timespan.
Definition: ch347.c:1571
static void ch347_read_swd_reg(uint8_t cmd)
Definition: ch347.c:2230
#define CH347_CMD_JTAG_BIT_OP
Definition: ch347.c:119
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:1833
static int ch347_init(void)
CH347 Initialization function.
Definition: ch347.c:2072
static int ch347_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
Definition: ch347.c:2630
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:1796
#define LARGER_PACK_MAX_SIZE
Definition: ch347.c:103
#define CH347_CMD_HEADER
Definition: ch347.c:107
static const int ch347_standard_pack_clock_speeds[]
Definition: ch347.c:180
static uint16_t default_ch347_vids[]
Definition: ch347.c:270
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:1067
static int ch347_swd_run_queue_inner(void)
Definition: ch347.c:2386
#define CH347_CMD_SWD_SEQ_W
Definition: ch347.c:131
#define CH347_CMD_SWD_REG_W
Definition: ch347.c:130
static void ch347_scratchpad_check_full(void)
checks if the scratchpad is full.
Definition: ch347.c:914
pack_size
Definition: ch347.c:173
@ STANDARD_PACK
Definition: ch347.c:175
@ LARGER_PACK
Definition: ch347.c:176
@ UNSET
Definition: ch347.c:174
static int ch347_swd_init_cmd(uint8_t clock_divisor)
swd init function
Definition: ch347.c:1857
#define CH347_CMD_JTAG_BIT_OP_RD
Definition: ch347.c:120
static int ch347_speed_set(int speed_index)
Initializes the JTAG interface and set CH347 TCK frequency.
Definition: ch347.c:1885
#define BYTEWISE_MODE_VERSION
Definition: ch347.c:150
#define USBC_PACKET_USBHS
Definition: ch347.c:106
static int ch347_reset(int trst, int srst)
Control (assert/deassert) the signals SRST and TRST on the interface.
Definition: ch347.c:1510
static int ch347_scratchpad_add_scan(struct scan_command *cmd)
Switch to SHIFT-DR or SHIFT-IR status for scanning.
Definition: ch347.c:1321
#define MAX_BITS_PER_BIT_OP
Definition: ch347.c:112
#define LED_ON
Definition: ch347.c:74
static bool ch347_activity_led_active_high
Definition: ch347.c:274
#define CH347_CMD_JTAG_DATA_SHIFT_RD
Definition: ch347.c:122
#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:234
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:355
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:206
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:201
#define DEBUG_CAP_TMS_SEQ
Definition: interface.h:199
#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
enum reset_types jtag_get_reset_config(void)
Definition: jtag/core.c:1730
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
reset_types
Definition: jtag.h:215
@ RESET_SRST_NO_GATING
Definition: jtag.h:224
@ RESET_HAS_SRST
Definition: jtag.h:218
@ RESET_CNCT_UNDER_SRST
Definition: jtag.h:225
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:219
const char *const name
The name of the interface driver.
Definition: interface.h:221
Configuration options for a single GPIO.
Definition: adapter.h:68
unsigned int gpio_num
Definition: adapter.h:69
enum adapter_gpio_drive_mode drive
Definition: adapter.h:71
uint16_t read_len
Definition: ch347.c:205
uint8_t type
Definition: ch347.c:202
uint16_t tdo_bit_count
Definition: ch347.c:206
uint16_t write_data_len
Definition: ch347.c:204
uint8_t * write_data
Definition: ch347.c:203
int singe_read_len
Definition: ch347.c:242
struct list_head scan_queue
Definition: ch347.c:239
int max_len
Definition: ch347.c:228
bool use_bitwise_mode
Definition: ch347.c:226
struct list_head cmd_queue
Definition: ch347.c:237
int tms_pin
Definition: ch347.c:218
bool swclk_5mhz_supported
Definition: ch347.c:229
int tdi_pin
Definition: ch347.c:219
uint8_t single_read[CH347_SINGLE_CMD_MAX_READ]
Definition: ch347.c:241
int trst_pin
Definition: ch347.c:221
enum ch347_variant chip_variant
Definition: ch347.c:224
uint8_t scratchpad[UCMDPKT_DATA_MAX_BYTES_USBHS]
Definition: ch347.c:233
int scratchpad_idx
Definition: ch347.c:234
int tck_pin
Definition: ch347.c:220
enum pack_size pack_size
Definition: ch347.c:227
uint8_t scratchpad_cmd_type
Definition: ch347.c:232
int srst_pin
Definition: ch347.c:222
int fields_len
Definition: ch347.c:212
struct scan_field * fields
Definition: ch347.c:211
int queued_retval
Definition: ch347.c:259
struct list_head free_cmd_head
Definition: ch347.c:264
struct ch347_swd_io ch347_cmd_buf[CH347_MAX_CMD_BUF]
Definition: ch347.c:265
int sent_cmd_count
Definition: ch347.c:260
unsigned int clk_divisor
Definition: ch347.c:261
int need_recv_len
Definition: ch347.c:258
uint8_t send_buf[CH347_MAX_SEND_BUF]
Definition: ch347.c:254
uint8_t recv_buf[CH347_MAX_RECV_BUF]
Definition: ch347.c:255
struct list_head send_cmd_head
Definition: ch347.c:263
unsigned int total_swd_clk
Definition: ch347.c:262
uint32_t * dst
Definition: ch347.c:248
struct list_head list_entry
Definition: ch347.c:250
uint8_t usb_cmd
Definition: ch347.c:246
uint8_t cmd
Definition: ch347.c:247
uint32_t value
Definition: ch347.c:249
const char * name
Definition: command.h:239
Represents a driver for a debugging interface.
Definition: interface.h:194
unsigned int supported
Bit vector listing capabilities exposed by this driver.
Definition: interface.h:198
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