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("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 {
650  LOG_DEBUG_IO("field skipped");
651  }
652  bit_offset += num_bits;
653  }
654  list_del(&scan->queue);
655  free(scan);
656  /* after one round of scan field processing the
657  next data bits are read from the next data byte
658  => round up and calculate the next start bit */
659  byte_offset = DIV_ROUND_UP(bit_offset, 8);
660  bit_offset = byte_offset * 8;
661  }
662 
663  // if not all bytes are transferred: put the rest into single_read buffer
664  if (byte_offset < decoded_buf_len) {
665  ch347.singe_read_len = decoded_buf_len - byte_offset;
666  LOG_DEBUG("single read of %d bytes", ch347.singe_read_len);
668  LOG_ERROR("Can't read more than %d bytes for a single command!", CH347_SINGLE_CMD_MAX_READ);
670  }
671  memcpy(ch347.single_read, &decoded_buf[byte_offset], ch347.singe_read_len);
672  }
673 
674  return ERROR_OK;
675 }
676 
683 static int ch347_cmd_transmit_queue(void)
684 {
685  // queue last command
686  int retval = ch347_cmd_from_scratchpad();
687  if (retval != ERROR_OK)
688  return retval;
689 
690  // nothing to do! => done here
691  if (list_empty(&ch347.cmd_queue))
692  return ERROR_OK;
693 
694  // calculate the needed buffer length for all decoded bytes
695  struct ch347_cmd *cmd;
696  int decoded_buf_len = 0;
698  if (cmd->read_len > 0)
699  decoded_buf_len += ch347_is_single_cmd_type(cmd->type) ?
700  cmd->read_len : DIV_ROUND_UP(cmd->tdo_bit_count, 8);
701 
702  // create the buffer for all decoded bytes
703  uint8_t *decoded_buf = NULL;
704  int decoded_buf_idx = 0;
705  if (decoded_buf_len > 0) {
706  decoded_buf = malloc(decoded_buf_len);
707  if (!decoded_buf) {
708  LOG_ERROR("malloc failed");
709  return ERROR_FAIL;
710  }
711  }
712 
713  while (!list_empty(&ch347.cmd_queue)) {
714  struct ch347_cmd *last_cmd = NULL;
715  int total_len = 0;
716  int total_tdo_count = 0;
717  int bytes_to_write = 0;
718 
720  total_len += CH347_CMD_HEADER + cmd->write_data_len;
721  total_tdo_count += cmd->tdo_bit_count;
722  // don't exceed max length or max TDO bit count
723  if (total_len >= ch347.max_len || total_tdo_count >= HW_TDO_BUF_SIZE)
724  break;
725  // remember the last cmd to send and bytes to send
726  last_cmd = cmd;
727  bytes_to_write = total_len;
728  }
729 
730  // sanity checks
731  if (!last_cmd || bytes_to_write == 0) {
732  LOG_ERROR("Nothing to send!");
733  free(decoded_buf);
734  return ERROR_FAIL;
735  }
736 
737  // create the write buffer
738  uint8_t *write_buf = malloc(bytes_to_write);
739  if (!write_buf) {
740  LOG_ERROR("malloc failed");
741  free(decoded_buf);
742  return ERROR_FAIL;
743  }
744 
745  int idx = 0;
746  int bytes_to_read = 0;
747  int current_decoded_buf_len = 0;
748  struct ch347_cmd *tmp;
749 
751  // copy command to buffer
752  write_buf[idx++] = cmd->type;
753  h_u16_to_le(&write_buf[idx], cmd->write_data_len);
754  idx += 2;
755  memcpy(&write_buf[idx], cmd->write_data, cmd->write_data_len);
756  idx += cmd->write_data_len;
757  // need to read something back?
758  if (cmd->read_len > 0) {
759  bytes_to_read += CH347_CMD_HEADER + cmd->read_len;
760  current_decoded_buf_len += ch347_is_single_cmd_type(cmd->type) ?
761  cmd->read_len : DIV_ROUND_UP(cmd->tdo_bit_count, 8);
762  }
763 
764  // cmd data no longer needed
765  list_del(&cmd->queue);
766  free(cmd->write_data);
767  free(cmd);
768 
769  if (cmd == last_cmd)
770  break;
771  }
772 
773  // write data to device
774  retval = ch347_write_data(write_buf, &idx);
775  free(write_buf);
776  if (retval != ERROR_OK) {
777  free(decoded_buf);
778  return retval;
779  }
780 
781  if (!bytes_to_read)
782  continue;
783 
784  // Need only to execute a read without decoding the data to make the CH347 happy?
785  if (!current_decoded_buf_len) {
786  // read but don't decode anything
787  retval = ch347_read_scan(NULL, 0, bytes_to_read);
788  } else {
789  retval = ch347_read_scan(&decoded_buf[decoded_buf_idx], current_decoded_buf_len, bytes_to_read);
790  decoded_buf_idx += current_decoded_buf_len;
791  }
792 
793  if (retval != ERROR_OK) {
794  free(decoded_buf);
795  return retval;
796  }
797  }
798 
799  // something decoded from the data read back from CH347?
800  if (decoded_buf) {
801  // put the decoded data into the scan fields or single_read buffer
802  retval = ch347_scan_data_to_fields(decoded_buf, decoded_buf_len);
803  free(decoded_buf);
804  }
805 
806  return retval;
807 }
808 
815 static int ch347_cmd_start_next(uint8_t type)
816 {
817  // different command type or non chainable command? (GPIO commands can't be concat)
818  uint8_t prev_type = ch347.scratchpad_cmd_type;
819  if (prev_type != type || ch347_is_single_cmd_type(type)) {
820  // something written in the scratchpad? => store it as command
821  if (prev_type != 0 && ch347.scratchpad_idx > 0) {
822  int retval = ch347_cmd_from_scratchpad();
823  if (retval != ERROR_OK)
824  return retval;
825 
826  /* if the last queued command is not chainable we should send it immediately
827  because e.g. the GPIO command can't be combined with any other command */
828  if (ch347_is_single_cmd_type(prev_type)) {
829  retval = ch347_cmd_transmit_queue();
830  if (retval != ERROR_OK)
831  return retval;
832  }
833  }
834 
835  /* before we can send non chainable command ("single" like GPIO command) we should send all
836  other commands because we can't send it together with other commands */
838  int retval = ch347_cmd_transmit_queue();
839  if (retval != ERROR_OK)
840  return retval;
841  }
842 
843  // store the next command type
845  }
846 
847  return ERROR_OK;
848 }
849 
857 static int ch347_scan_queue_fields(struct scan_field *scan_fields, int scan_fields_len)
858 {
859  // malloc for the scan struct
860  struct ch347_scan *scan = malloc(sizeof(struct ch347_scan));
861  if (!scan) {
862  LOG_ERROR("malloc failed");
863  return ERROR_FAIL;
864  }
865 
866  scan->fields = scan_fields;
867  scan->fields_len = scan_fields_len;
868  list_add_tail(&scan->queue, &ch347.scan_queue);
869  return ERROR_OK;
870 }
871 
880 static int ch347_single_read_get_byte(int read_buf_idx, uint8_t *byte)
881 {
882  int retval = ch347_cmd_transmit_queue();
883  if (retval != ERROR_OK)
884  return retval;
885 
886  if (read_buf_idx > CH347_SINGLE_CMD_MAX_READ || read_buf_idx < 0) {
887  LOG_ERROR("read_buf_idx out of range");
888  return ERROR_FAIL;
889  }
890 
891  *byte = ch347.single_read[read_buf_idx];
892  return ERROR_OK;
893 }
894 
900 {
901  // if full create a new command in the queue
903  uint8_t type = ch347.scratchpad_cmd_type;
906  }
907 }
908 
917 static int ch347_scratchpad_add_byte(uint8_t byte)
918 {
919  if (ch347.scratchpad_cmd_type == 0) {
920  LOG_ERROR("call ch347_next_cmd first!");
921  return ERROR_FAIL;
922  }
923 
926  return ERROR_OK;
927 }
928 
937 {
938  uint8_t pins = ch347.tms_pin | ch347.tdi_pin | ch347.tck_pin | ch347.trst_pin;
939 
941  pins |= ch347.srst_pin;
942 
943  return ch347_scratchpad_add_byte(pins);
944 }
945 
956 static int ch347_scratchpad_add_bytes(uint8_t *bytes, int count)
957 {
958  if (ch347.scratchpad_cmd_type == 0) {
959  LOG_ERROR("call ch347_next_cmd first!");
960  return ERROR_FAIL;
961  }
962 
963  int remaining = count;
964  int bytes_idx = 0;
965  while (remaining > 0) {
966  int bytes_to_store = ch347.scratchpad_idx + remaining <= UCMDPKT_DATA_MAX_BYTES_USBHS ?
968 
969  if (bytes)
970  memcpy(&ch347.scratchpad[ch347.scratchpad_idx], &bytes[bytes_idx], bytes_to_store);
971  else
972  memset(&ch347.scratchpad[ch347.scratchpad_idx], 0, bytes_to_store);
973 
974  ch347.scratchpad_idx += bytes_to_store;
975  bytes_idx += bytes_to_store;
976  remaining -= bytes_to_store;
978  }
979 
980  return ERROR_OK;
981 }
982 
983 /* Drive SRST low at init only when the target is connected under reset.
984  * srst_nogate is required as well: without it, JTAG is gated while SRST
985  * is asserted. */
987 {
988  enum reset_types cfg = jtag_get_reset_config();
989 
992 }
993 
1016 static int ch347_srst_enable(void)
1017 {
1019  if (retval != ERROR_OK)
1020  return retval;
1021 
1022  uint8_t cmd_data[] = {0x00, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1023  retval = ch347_scratchpad_add_bytes(cmd_data, ARRAY_SIZE(cmd_data));
1024  if (retval != ERROR_OK)
1025  return retval;
1026 
1027  uint8_t init_result;
1028  retval = ch347_single_read_get_byte(0, &init_result);
1029  if (retval != ERROR_OK)
1030  return retval;
1031 
1032  LOG_DEBUG("CH347F PIN_SET result %02" PRIx8, init_result);
1033 
1035  /* The pin byte merges bit 6 only while this flag is set. */
1038  if (retval == ERROR_OK)
1039  retval = ch347_scratchpad_add_pin_byte();
1040  if (retval == ERROR_OK)
1041  retval = ch347_cmd_transmit_queue();
1042  return retval;
1043 }
1044 
1053 {
1054  ch347.tms_pin = tms ? TMS_H : TMS_L;
1055  ch347.tck_pin = TCK_L;
1056  int retval = ch347_scratchpad_add_pin_byte();
1057  if (retval != ERROR_OK)
1058  return retval;
1059 
1060  ch347.tck_pin = TCK_H;
1062 }
1063 
1071 {
1072  if (ch347.scratchpad_cmd_type == 0) {
1074  if (retval != ERROR_OK)
1075  return retval;
1076  }
1077 
1078  bool tms = ch347.tms_pin == TMS_H;
1079  for (int i = 0; i < count; i++) {
1080  int retval = ch347_scratchpad_add_clock_tms(tms);
1081  if (retval != ERROR_OK)
1082  return retval;
1083  }
1084 
1085  return ERROR_OK;
1086 }
1087 
1094 {
1095  ch347.tck_pin = TCK_L;
1097 }
1098 
1107 static int ch347_scratchpad_add_tms_change(const uint8_t *tms_value, int step, int skip)
1108 {
1109  LOG_DEBUG_IO("TMS Value: %02x..., step = %d, skip = %d", tms_value[0], step, skip);
1110 
1112  if (retval != ERROR_OK)
1113  return retval;
1114 
1115  for (int i = skip; i < step; i++) {
1116  retval = ch347_scratchpad_add_clock_tms((tms_value[i / 8] >> (i % 8)) & BIT(0));
1117  if (retval != ERROR_OK)
1118  return retval;
1119  }
1120 
1122 }
1123 
1131 {
1132  LOG_DEBUG_IO("num_states=%d, last_state=%d", cmd->num_states, cmd->path[cmd->num_states - 1]);
1133 
1135  if (retval != ERROR_OK)
1136  return retval;
1137 
1138  for (unsigned int i = 0; i < cmd->num_states; i++) {
1139  if (tap_state_transition(tap_get_state(), false) == cmd->path[i]) {
1140  retval = ch347_scratchpad_add_clock_tms(0);
1141  if (retval != ERROR_OK)
1142  return retval;
1143  } else if (tap_state_transition(tap_get_state(), true) == cmd->path[i]) {
1144  retval = ch347_scratchpad_add_clock_tms(1);
1145  if (retval != ERROR_OK)
1146  return retval;
1147  } else {
1148  LOG_ERROR("No transition possible!");
1150  }
1151  tap_set_state(cmd->path[i]);
1152  }
1153 
1155 }
1156 
1165 {
1166  uint8_t tms_scan;
1167  int tms_len;
1168 
1170  // don't do anything if we are already in the right state; but do execute always the TAP_RESET
1171  if (tap_get_state() == state && state != TAP_RESET)
1172  return ERROR_OK;
1173 
1174  tms_scan = tap_get_tms_path(tap_get_state(), state);
1176  int retval = ch347_scratchpad_add_tms_change(&tms_scan, tms_len, skip);
1178  return retval;
1179 }
1180 
1190 static int ch347_scratchpad_add_write_read(struct scan_command *cmd, uint8_t *bits, int bits_len, enum scan_type scan)
1191 {
1192  // the bits and bytes to transfer
1193  int byte_count = bits_len / 8;
1194  int bit_count = bits_len % 8;
1195 
1196  // only bytes are not possible because we need to set TMS high for the last bit
1197  if (byte_count > 0 && bit_count == 0) {
1198  // make one byte to eight bits
1199  byte_count--;
1200  bit_count = 8;
1201  }
1202 
1203  // in bitwise mode only bits are allowed
1204  if (ch347.use_bitwise_mode) {
1205  byte_count = 0;
1206  bit_count = bits_len;
1207  }
1208 
1209  bool is_read = (scan == SCAN_IN || scan == SCAN_IO);
1210 
1211  // if we need to send bytes
1212  if (byte_count > 0) {
1213  // start the next cmd and copy the data out bytes to it
1215  if (retval != ERROR_OK)
1216  return retval;
1217 
1218  if (bits)
1219  retval = ch347_scratchpad_add_bytes(bits, byte_count);
1220  else
1221  retval = ch347_scratchpad_add_bytes(NULL, byte_count);
1222 
1223  if (retval != ERROR_OK)
1224  return retval;
1225  }
1226 
1227  // bits are always need to send; no possibility to not send bits
1229  if (retval != ERROR_OK)
1230  return retval;
1231 
1232  ch347.tms_pin = TMS_L;
1233  ch347.tdi_pin = TDI_L;
1234 
1235  for (int i = 0; i < bit_count; i++) {
1236  if (bits)
1237  ch347.tdi_pin = ((bits[byte_count + i / 8] >> i % 8) & BIT(0)) ? TDI_H : TDI_L;
1238 
1239  // for the last bit set TMS high to exit the shift state
1240  if (i + 1 == bit_count)
1241  ch347.tms_pin = TMS_H;
1242 
1243  ch347.tck_pin = TCK_L;
1244  retval = ch347_scratchpad_add_pin_byte();
1245  if (retval != ERROR_OK)
1246  return retval;
1247 
1248  ch347.tck_pin = TCK_H;
1249  retval = ch347_scratchpad_add_pin_byte();
1250  if (retval != ERROR_OK)
1251  return retval;
1252 
1253  /* cut the package after each MAX_BITS_PER_BIT_OP bits because it
1254  needs a dividable by 8 bits package */
1255  if (i > 0 && (i + 1) % MAX_BITS_PER_BIT_OP == 0) {
1256  retval = ch347_cmd_from_scratchpad();
1257  if (retval != ERROR_OK)
1258  return retval;
1259 
1261  if (retval != ERROR_OK)
1262  return retval;
1263  }
1264  }
1265 
1266  // one TCK_L after the last bit
1268  if (retval != ERROR_OK)
1269  return retval;
1270 
1271  // if read is involved we need to queue the scan fields
1272  if (is_read)
1273  return ch347_scan_queue_fields(cmd->fields, cmd->num_fields);
1274 
1275  return ERROR_OK;
1276 }
1277 
1285 static int ch347_scratchpad_add_run_test(int cycles, enum tap_state state)
1286 {
1287  LOG_DEBUG_IO("cycles=%d, end_state=%d", cycles, state);
1288  int retval;
1289  if (tap_get_state() != TAP_IDLE) {
1291  if (retval != ERROR_OK)
1292  return retval;
1293  }
1294 
1295  retval = ch347_scratchpad_add_stableclocks(cycles);
1296  if (retval != ERROR_OK)
1297  return retval;
1298 
1300 }
1301 
1309 {
1310  static const char *const type2str[] = {"", "SCAN_IN", "SCAN_OUT", "SCAN_IO"};
1311 
1312  enum scan_type type = jtag_scan_type(cmd);
1313  uint8_t *buf = NULL;
1314  int scan_bits = jtag_build_buffer(cmd, &buf);
1315 
1316  // add a move to IRSHIFT or DRSHIFT state
1317  int retval;
1318  if (cmd->ir_scan)
1320  else
1322 
1323  if (retval != ERROR_OK) {
1324  free(buf);
1325  return retval;
1326  }
1327 
1329  char *log_buf = buf_to_hex_str(buf, scan_bits);
1330  LOG_DEBUG_IO("scan=%s, type=%s, bits=%d, buf=[%s], end_state=%d",
1331  cmd->ir_scan ? "IRSCAN" : "DRSCAN",
1332  type2str[type],
1333  scan_bits, log_buf, cmd->end_state);
1334  free(log_buf);
1335  }
1336 
1337  retval = ch347_scratchpad_add_write_read(cmd, buf, scan_bits, type);
1338  free(buf);
1339  if (retval != ERROR_OK)
1340  return retval;
1341 
1342  // add a move to the final state
1343  return ch347_scratchpad_add_move_state(cmd->end_state, 1);
1344 }
1345 
1351 static uint8_t ch347_usable_gpios(void)
1352 {
1354 }
1355 
1369 static int ch347_gpio_cmd(unsigned int gpio, uint8_t value, uint8_t *state)
1370 {
1371  if (gpio >= GPIO_CNT) {
1372  LOG_ERROR("GPIO %u out of range", gpio);
1373  return ERROR_FAIL;
1374  }
1375 
1376  int retval = ch347_cmd_start_next(CH347_CMD_GPIO);
1377  if (retval != ERROR_OK)
1378  return retval;
1379 
1380  uint8_t gpios[GPIO_CNT];
1381  memset(gpios, 0, GPIO_CNT);
1382  gpios[gpio] = value;
1384  if (retval != ERROR_OK)
1385  return retval;
1386 
1387  return ch347_single_read_get_byte(gpio, state);
1388 }
1389 
1401 static uint8_t ch347_gpio_drive_value(bool level, enum adapter_gpio_drive_mode drive)
1402 {
1403  switch (drive) {
1405  return level ? GPIO_SET_INPUT : GPIO_SET_L;
1407  return level ? GPIO_SET_H : GPIO_SET_INPUT;
1409  break;
1410  }
1411 
1412  return level ? GPIO_SET_H : GPIO_SET_L;
1413 }
1414 
1422 static int ch347_gpio_set(int gpio, bool data)
1423 {
1424  /* always set bits 7 and 6 for GPIO enable
1425  bits 5 and 4 for pin direction output
1426  bit 3 is the data bit */
1427  uint8_t state;
1428  int retval = ch347_gpio_cmd(gpio, data ? GPIO_SET_H : GPIO_SET_L, &state);
1429  if (retval != ERROR_OK)
1430  return retval;
1431 
1432  // check in the read if the bit is set/cleared correctly
1433  if ((bool)(state & BIT(6)) != data) {
1434  LOG_ERROR("Output not set.");
1435  return ERROR_FAIL;
1436  }
1437 
1438  return ERROR_OK;
1439 }
1440 
1447 static int ch347_activity_led_set(int led_state)
1448 {
1449  if (ch347_activity_led_gpio_pin != 0xFF)
1450  return ch347_gpio_set(ch347_activity_led_gpio_pin, ch347_activity_led_active_high ? led_state : 1 - led_state);
1451 
1452  // not configured => also OK
1453  return ERROR_OK;
1454 }
1455 
1464 {
1465  static bool warned;
1466  enum adapter_gpio_drive_mode drive =
1468 
1469  if (warned || !(jtag_get_reset_config() & RESET_HAS_SRST))
1470  return;
1471  if (drive == ADAPTER_GPIO_DRIVE_MODE_PUSH_PULL)
1472  return;
1473 
1474  warned = true;
1475  LOG_WARNING("CH347F dedicated SRST is push-pull and ignores "
1476  "the reset_config drive mode; use 'reset_config srst_push_pull'");
1477 }
1478 
1497 static int ch347_reset(int trst, int srst)
1498 {
1499  int retval;
1500  LOG_DEBUG_IO("reset trst: %i srst %i", trst, srst);
1501 
1502  if (swd_mode) {
1503  if (trst)
1504  LOG_WARNING("Asserting TRST not supported in SWD mode!");
1505 
1506  if (ch347_srst_gpio_pin == 0xFF) {
1507  if (srst) {
1508  LOG_ERROR("Asserting SRST not supported: no usable GPIO configured");
1509  return ERROR_FAIL;
1510  }
1511  return ERROR_OK;
1512  }
1513 
1514  /* Honour the drive mode of 'reset_config'. It defaults to open drain,
1515  which releases the pin instead of driving the inactive level, so the
1516  target can keep the line low on its own.
1517  Don't verify the readback: it reports the pin level, and the target
1518  is free to hold the reset line low itself, e.g. while it is in a
1519  watchdog reset loop. */
1520  bool level = srst ? ch347_srst_active_high : !ch347_srst_active_high;
1521  uint8_t value = ch347_gpio_drive_value(level,
1523  uint8_t state;
1524  return ch347_gpio_cmd(ch347_srst_gpio_pin, value, &state);
1525  }
1526 
1527  if (srst && !ch347_dedicated_srst_enabled) {
1528  LOG_ERROR("Asserting SRST not supported");
1529  return ERROR_FAIL;
1530  }
1531 
1533  if (retval != ERROR_OK)
1534  return retval;
1535 
1536  ch347.trst_pin = trst ? TRST_L : TRST_H;
1539  ch347.srst_pin = srst ? SRST_L : SRST_H;
1540  }
1541  retval = ch347_scratchpad_add_pin_byte();
1542  if (retval != ERROR_OK)
1543  return retval;
1544 
1546  if (retval != ERROR_OK)
1547  return retval;
1548 
1549  return ch347_cmd_transmit_queue();
1550 }
1551 
1558 static int ch347_sleep(int us)
1559 {
1560  LOG_DEBUG_IO("us=%d", us);
1561  int retval = ch347_cmd_transmit_queue();
1562  jtag_sleep(us);
1563  return retval;
1564 }
1565 
1571 static int ch347_execute_queue(struct jtag_command *cmd_queue)
1572 {
1573  struct jtag_command *cmd = cmd_queue;
1574 
1575  int retval = ch347_activity_led_set(LED_ON);
1576  if (retval != ERROR_OK)
1577  return retval;
1578 
1579  while (retval == ERROR_OK && cmd) {
1580  switch (cmd->type) {
1581  case JTAG_RUNTEST:
1582  retval = ch347_scratchpad_add_run_test(cmd->cmd.runtest->num_cycles, cmd->cmd.runtest->end_state);
1583  break;
1584  case JTAG_STABLECLOCKS:
1585  retval = ch347_scratchpad_add_stableclocks(cmd->cmd.stableclocks->num_cycles);
1586  break;
1587  case JTAG_TLR_RESET:
1588  retval = ch347_scratchpad_add_move_state(cmd->cmd.statemove->end_state, 0);
1589  break;
1590  case JTAG_PATHMOVE:
1591  retval = ch347_scratchpad_add_move_path(cmd->cmd.pathmove);
1592  break;
1593  case JTAG_TMS:
1594  retval = ch347_scratchpad_add_tms_change(cmd->cmd.tms->bits, cmd->cmd.tms->num_bits, 0);
1595  break;
1596  case JTAG_SLEEP:
1597  retval = ch347_sleep(cmd->cmd.sleep->us);
1598  break;
1599  case JTAG_SCAN:
1600  retval = ch347_scratchpad_add_scan(cmd->cmd.scan);
1601  break;
1602  default:
1603  LOG_ERROR("BUG: unknown JTAG command type 0x%X", cmd->type);
1604  retval = ERROR_FAIL;
1605  break;
1606  }
1607 
1608  cmd = cmd->next;
1609  }
1610 
1611  if (retval != ERROR_OK)
1612  return retval;
1613 
1614  retval = ch347_cmd_transmit_queue();
1615  if (retval != ERROR_OK)
1616  return retval;
1617 
1619 }
1620 
1626 static int ch347_open_device(void)
1627 {
1628  const uint16_t *ch347_vids = default_ch347_vids;
1629  const uint16_t *ch347_pids = default_ch347_pids;
1630 
1631  if (adapter_usb_get_vids()[0] != 0) {
1632  ch347_vids = adapter_usb_get_vids();
1633  ch347_pids = adapter_usb_get_pids();
1634  }
1635 
1636  int retval = jtag_libusb_open(ch347_vids, ch347_pids,
1638  if (retval != ERROR_OK) {
1639  char error_message[256];
1640  snprintf(error_message, sizeof(error_message), "CH347 not found. Tried VID/PID pairs: ");
1641  for (int i = 0; ch347_vids[i] != 0; i++)
1642  snprintf(error_message + strlen(error_message), sizeof(error_message) - strlen(error_message),
1643  "%04x:%04x ", ch347_vids[i], ch347_pids[i]);
1644 
1645  LOG_ERROR("%s", error_message);
1646  return retval;
1647  }
1648 
1649  struct libusb_device_descriptor ch347_device_descriptor;
1650  libusb_device *device = libusb_get_device(ch347_handle);
1651  if (!device) {
1652  LOG_ERROR("CH347 error calling libusb_get_device");
1654  return ERROR_FAIL;
1655  }
1656 
1657  retval = libusb_get_device_descriptor(device, &ch347_device_descriptor);
1658  if (retval != ERROR_OK) {
1659  LOG_ERROR("CH347 error getting device descriptor: %s", libusb_error_name(retval));
1661  return retval;
1662  }
1663 
1664  // Fix for CH347F on ARM64
1665  // Force set configuration 1 (required on some ARM64 platforms)
1666  retval = libusb_set_configuration(ch347_handle, 1);
1667  if (retval != LIBUSB_SUCCESS && retval != LIBUSB_ERROR_BUSY)
1668  LOG_WARNING("CH347 set_configuration failed: %s", libusb_error_name(retval));
1669 
1670  // CH347T / CH347F detection
1671  // if we can claim interface 4 we found a CH347F chip; if we can claim interface 2 we found CH347T chip
1672  retval = libusb_claim_interface(ch347_handle, CH347F_MPHSI_INTERFACE);
1673  if (retval != ERROR_OK) {
1674  retval = libusb_claim_interface(ch347_handle, CH347T_MPHSI_INTERFACE);
1675  if (retval != ERROR_OK) {
1676  LOG_ERROR("CH347 unable to claim interface: %s", libusb_error_name(retval));
1678  return retval;
1679  }
1681  } else {
1683  }
1684 
1685  char firmware_version;
1687  LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
1688  VENDOR_VERSION, 0, 0, &firmware_version, sizeof(firmware_version),
1690  if (retval != ERROR_OK) {
1691  LOG_ERROR("CH347 unable to get firmware version");
1693  return retval;
1694  }
1695 
1696  char manufacturer[256 + 1];
1697  if (libusb_get_string_descriptor_ascii(ch347_handle, ch347_device_descriptor.iManufacturer,
1698  (unsigned char *)manufacturer, sizeof(manufacturer) - 1) < 0) {
1699  strcpy(manufacturer, "(unknown)");
1700  }
1701  char product[256 + 1];
1702  if (libusb_get_string_descriptor_ascii(ch347_handle, ch347_device_descriptor.iProduct,
1703  (unsigned char *)product, sizeof(product) - 1) < 0) {
1704  strcpy(product, "(unknown)");
1705  }
1706  char serial_number[256 + 1];
1707  if (libusb_get_string_descriptor_ascii(ch347_handle, ch347_device_descriptor.iSerialNumber,
1708  (unsigned char *)serial_number, sizeof(serial_number) - 1) < 0) {
1709  strcpy(serial_number, "(unknown)");
1710  }
1711 
1712  LOG_INFO("CH347%c %s from vendor %s with serial number %s found. (Chip version=%X.%02X, Firmware=0x%02X)",
1713  ch347.chip_variant == CH347T ? 'T' : ch347.chip_variant == CH347F ? 'F' : '?',
1714  product,
1715  manufacturer,
1716  serial_number,
1717  (ch347_device_descriptor.bcdDevice >> 8) & 0xFF,
1718  ch347_device_descriptor.bcdDevice & 0xFF,
1719  firmware_version);
1720 
1721  if (ch347.chip_variant == CH347T && ch347_device_descriptor.bcdDevice < BYTEWISE_MODE_VERSION) {
1722  LOG_INFO("CH347T old version of the chip, JTAG only working in bitwise mode. For bytewise mode at least version %X.%X is needed.",
1723  (BYTEWISE_MODE_VERSION >> 8) & 0xFF,
1724  BYTEWISE_MODE_VERSION & 0xFF);
1725  ch347.use_bitwise_mode = true;
1726  } else {
1727  ch347.use_bitwise_mode = false;
1728  }
1729 
1730  if (ch347.chip_variant == CH347T) {
1731  if (swd_mode) {
1732  ch347.swclk_5mhz_supported = ch347_device_descriptor.bcdDevice >= 0x544;
1733 
1734  if (ch347_device_descriptor.bcdDevice < 0x441)
1735  LOG_WARNING("CH347T version older than 4.41 probably does not support SWD transport");
1736 
1737  if (ch347_device_descriptor.bcdDevice == 0x441)
1738  LOG_WARNING("If CH347T version 4.41 cannot connect or SWD fails often, insert a resistor to SWDIO circuit");
1739 
1740  } else if (ch347_device_descriptor.bcdDevice == 0x241) {
1741  LOG_WARNING("CH347T version 2.41 has very weird clock timing, may not work with a slower JTAG device");
1742  }
1743 
1744  if (ch347_device_descriptor.bcdDevice < 0x544)
1745  LOG_INFO("Please upgrade CH347T firmware to a production version >= 5.44");
1746 
1747  } else if (ch347.chip_variant == CH347F) {
1748  ch347.swclk_5mhz_supported = ch347_device_descriptor.bcdDevice >= 0x101;
1749 
1750  if (ch347_device_descriptor.bcdDevice < 0x101)
1751  LOG_INFO("Please upgrade CH347F firmware to a production version >= 1.1");
1752  }
1753 
1754  return ERROR_OK;
1755 }
1756 
1762 static int ch347_quit(void)
1763 {
1764  // on close set the LED on, because the state without JTAG is on
1766  int retval = ch347_cmd_transmit_queue();
1768  LOG_DEBUG_IO("CH347 close");
1769  return retval;
1770 }
1771 
1783 static int ch347_adapter_init(uint8_t clock_index, bool *supports_larger_pack_mode)
1784 {
1786  if (retval != ERROR_OK)
1787  return retval;
1788 
1789  retval = ch347_scratchpad_add_byte(0);
1790  if (retval != ERROR_OK)
1791  return retval;
1792 
1793  retval = ch347_scratchpad_add_byte(clock_index);
1794  if (retval != ERROR_OK)
1795  return retval;
1796 
1797  for (int i = 0; i < 4; i++) {
1798  retval = ch347_scratchpad_add_pin_byte();
1799  if (retval != ERROR_OK)
1800  return retval;
1801  }
1802 
1803  uint8_t mode;
1804  retval = ch347_single_read_get_byte(0, &mode);
1805  if (retval != ERROR_OK)
1806  return retval;
1807 
1808  *supports_larger_pack_mode = mode != 0;
1809  return ERROR_OK;
1810 }
1811 
1820 static int ch347_adapter_supports_larger_pack_mode(bool *supports_larger_pack_mode)
1821 {
1822  return ch347_adapter_init(CH347_CMD_INIT_GET_MODE_CLOCK_INDEX_VALUE, supports_larger_pack_mode);
1823 }
1824 
1832 static int ch347_adapter_set_speed(uint8_t clock_index)
1833 {
1834  bool unused;
1835  return ch347_adapter_init(clock_index, &unused);
1836 }
1837 
1844 static int ch347_swd_init_cmd(uint8_t clock_divisor)
1845 {
1847  if (retval != ERROR_OK)
1848  return retval;
1849 
1850  uint8_t cmd_data[] = {0x40, 0x42, 0x0f, 0x00, clock_divisor, 0x00, 0x00, 0x00 };
1851  retval = ch347_scratchpad_add_bytes(cmd_data, ARRAY_SIZE(cmd_data));
1852  if (retval != ERROR_OK)
1853  return retval;
1854 
1855  /* TODO: CH347_CMD_SWD_INIT reads one data byte.
1856  But how can we decide if SWD init was successfully executed?
1857  Return an error code if init was failed */
1858  uint8_t init_result = 0;
1859  retval = ch347_single_read_get_byte(0, &init_result);
1860  LOG_DEBUG("SWD init clk div %" PRIu8 ", result %02" PRIx8,
1861  clock_divisor, init_result);
1862  ch347_swd_context.clk_divisor = clock_divisor;
1863  return retval;
1864 }
1865 
1872 static int ch347_speed_set(int speed_index)
1873 {
1874  if (swd_mode)
1875  return ch347_swd_init_cmd(speed_index);
1876 
1877  int retval = ch347_adapter_set_speed(speed_index);
1878  if (retval != ERROR_OK) {
1879  LOG_ERROR("Couldn't set CH347 speed");
1880  return retval;
1881  }
1882 
1883  return ERROR_OK;
1884 }
1885 
1891 static int ch347_init_pack_size(void)
1892 {
1893  // already set?
1894  if (ch347.pack_size != UNSET)
1895  return ERROR_OK;
1896 
1897  // set the lower limit for starting
1899  bool supports_larger_pack_mode;
1900  int retval = ch347_adapter_supports_larger_pack_mode(&supports_larger_pack_mode);
1901  if (retval != ERROR_OK)
1902  return retval;
1903 
1904  ch347.pack_size = supports_larger_pack_mode ? LARGER_PACK : STANDARD_PACK;
1907  return ERROR_OK;
1908 }
1909 
1917 static int ch347_speed_get(int speed_idx, int *khz)
1918 {
1919  if (swd_mode) {
1920  if (speed_idx)
1921  *khz = DIV_ROUND_UP(CH347_SWD_CLOCK_BASE, speed_idx);
1922  else
1923  *khz = CH347_SWD_CLOCK_MAX;
1924  return ERROR_OK;
1925  }
1926 
1927  int retval = ch347_init_pack_size();
1928  if (retval != ERROR_OK)
1929  return retval;
1930  const int *speeds = ch347.pack_size == STANDARD_PACK ?
1932  *khz = speeds[speed_idx];
1933  return ERROR_OK;
1934 }
1935 
1943 static int ch347_speed_get_index(int khz, int *speed_idx)
1944 {
1945  if (khz == 0) {
1946  LOG_ERROR("Adaptive clocking not supported");
1947  return ERROR_FAIL;
1948  }
1949 
1950  if (swd_mode) {
1952  *speed_idx = 0;
1953  } else {
1954  // Don't allow too low clk speeds: packet processing is limited to ~8 msec
1955  // or triggers host USB disconnect
1956  *speed_idx = MIN(DIV_ROUND_UP(CH347_SWD_CLOCK_BASE, khz),
1958  }
1959  return ERROR_OK;
1960  }
1961 
1962  // when checking with speed index 9 we can see if the device supports STANDARD_PACK or LARGER_PACK mode
1963  int retval = ch347_init_pack_size();
1964  if (retval != ERROR_OK)
1965  return retval;
1966  // depending on pack size there are different fixed clock speeds possible
1967  const int *speeds = ch347.pack_size == STANDARD_PACK ?
1969  int length = ch347.pack_size == STANDARD_PACK ?
1971  // find the suitable speed index
1972  int idx = length - 1;
1973  while (idx > 0 && speeds[idx] > khz)
1974  idx--;
1975 
1976  if (speeds[idx] > khz) {
1977  LOG_WARNING("Requested speed of %d kHz is not possible. Using %d kHz",
1978  khz, speeds[idx]);
1979  }
1980  *speed_idx = idx;
1981  return ERROR_OK;
1982 }
1983 
1984 static const struct command_registration ch347_command_handlers[] = {
1985  {
1986  .name = "ch347",
1987  .mode = COMMAND_ANY,
1988  .help = "perform ch347 management",
1989  .usage = "",
1990  },
1992 };
1993 
2003 static void ch347_configure_activity_led(const struct adapter_gpio_config *led_config)
2004 {
2005  uint8_t gpio = led_config->gpio_num;
2006  if (gpio >= GPIO_CNT || (BIT(gpio) & ch347_usable_gpios()) == 0)
2007  return;
2008 
2011 }
2012 
2024 static void ch347_configure_srst_gpio(const struct adapter_gpio_config *srst_config)
2025 {
2026  ch347_srst_active_high = !srst_config->active_low;
2027 
2028  unsigned int gpio;
2029  if (srst_config->gpio_num == ADAPTER_GPIO_NOT_SET) {
2030  // the TRST pin is free in SWD mode, so use it by default
2032  } else {
2033  gpio = srst_config->gpio_num;
2034  if (gpio >= GPIO_CNT || (BIT(gpio) & ch347_usable_gpios()) == 0) {
2035  LOG_ERROR("GPIO %u can't be used for SRST, disabling SRST", gpio);
2036  ch347_srst_gpio_pin = 0xFF;
2037  return;
2038  }
2039  }
2040 
2041  /* Driving the same pin from two functions would let the LED activity
2042  toggle the reset line, so refuse to share it. */
2043  if (gpio == ch347_activity_led_gpio_pin) {
2044  LOG_ERROR("GPIO %u is already used as the activity LED, disabling SRST", gpio);
2045  ch347_srst_gpio_pin = 0xFF;
2046  return;
2047  }
2048 
2049  ch347_srst_gpio_pin = gpio;
2050 }
2051 
2057 static int ch347_init(void)
2058 {
2059  int retval = ch347_open_device();
2060 
2061  if (retval != ERROR_OK) {
2062  LOG_ERROR("CH347 open error");
2063  return retval;
2064  }
2065 
2066  LOG_DEBUG_IO("CH347 open success");
2067 
2068  // CH347 JTAG init
2069  ch347.tck_pin = TCK_L;
2070  ch347.tms_pin = TMS_H;
2071  ch347.tdi_pin = TDI_L;
2072  ch347.trst_pin = TRST_H;
2073  ch347.srst_pin = SRST_H;
2077 
2078  /* Static initial pack_size is STANDARD_PACK (0), which would look already
2079  * probed. max_len stays 0 until the probe, and PIN_SET uses this queue. */
2080  ch347.pack_size = UNSET;
2081 
2083 
2084  if (!swd_mode) {
2085  /* Pin 8 drives strong low after adapter power-up. On CH347F, enable the
2086  * dedicated SRST output and release it, even when reset_config
2087  * does not include SRST. Leave it asserted only for connect_assert_srst
2088  * together with srst_nogate. */
2089  if (ch347.chip_variant == CH347F) {
2090  retval = ch347_init_pack_size();
2091  if (retval != ERROR_OK)
2092  return retval;
2093 
2094  retval = ch347_srst_enable();
2095  if (retval != ERROR_OK) {
2096  LOG_ERROR("CH347F dedicated SRST enable failed");
2097  return retval;
2098  }
2100  }
2102  } else {
2104 
2105  retval = ch347_init_pack_size();
2106  if (retval != ERROR_OK)
2107  return retval;
2108 
2109  retval = ch347_swd_init_cmd(1);
2110  }
2111  return retval;
2112 }
2113 
2119 static int ch347_swd_init(void)
2120 {
2121  LOG_INFO("CH347 SWD mode enabled");
2122  swd_mode = true;
2123  memset(&ch347_swd_context, 0, sizeof(ch347_swd_context));
2124 
2127 
2129  // 0XE8 + 2byte len + N byte cmds
2131  // 0XE8 + 2byte len + N byte ack + data
2133  struct ch347_swd_io *pswd_io = ch347_swd_context.ch347_cmd_buf;
2134  for (int i = 0; i < CH347_MAX_CMD_BUF; i++, pswd_io++) {
2135  INIT_LIST_HEAD(&pswd_io->list_entry);
2137  }
2138  return ERROR_OK;
2139 }
2140 
2142 {
2143  struct ch347_swd_io *pswd_io;
2145  return NULL;
2146 
2148  struct ch347_swd_io, list_entry);
2149  list_del_init(&pswd_io->list_entry);
2150  pswd_io->cmd = 0;
2151  pswd_io->usb_cmd = CH347_CMD_SWD_SEQ_W;
2152  pswd_io->dst = NULL;
2153  return pswd_io;
2154 }
2155 
2156 static int ch347_swd_queue_flush(void)
2157 {
2162  if (retval != ERROR_OK) {
2164  LOG_DEBUG("CH347WriteData error");
2165  return retval;
2166  }
2167 
2171  if (retval != ERROR_OK) {
2173  LOG_DEBUG("CH347ReadData error");
2174  return retval;
2175  }
2176 
2179  LOG_ERROR("write/read failed %d %d",
2182  retval = ERROR_FAIL;
2183  }
2184 
2185  return retval;
2186 }
2187 
2188 static void ch347_write_swd_reg(uint8_t cmd, const uint32_t out)
2189 {
2191  // 8bit + 32bit +1bit
2198  // 0xA0 + 1 byte(3bit ACK)
2199  ch347_swd_context.need_recv_len += (1 + 1);
2201 }
2202 
2203 static void ch347_write_spec_seq(const uint8_t *out, uint8_t out_len)
2204 {
2209  for (uint8_t i = 0; i < DIV_ROUND_UP(out_len, 8); i++)
2210  ch347_swd_context.send_buf[ch347_swd_context.send_len++] = out ? out[i] : 0x00;
2211  ch347_swd_context.need_recv_len += 1; // 0xA1
2212  ch347_swd_context.total_swd_clk += out_len;
2213 }
2214 
2215 static void ch347_read_swd_reg(uint8_t cmd)
2216 {
2221  // 0xA2 + 1 byte(3bit ACK) + 4 byte(data) + 1 byte(1bit parity+1bit trn)
2222  ch347_swd_context.need_recv_len += 1 + 1 + 4 + 1;
2224 }
2225 
2226 static int ch347_swd_switch_out(enum swd_special_seq seq, const uint8_t *out, unsigned int out_len)
2227 {
2228  if ((ch347_swd_context.send_len + (1 + 2 + DIV_ROUND_UP(out_len, 8))) > CH347_MAX_SEND_BUF)
2229  return ERROR_FAIL;
2231  return ERROR_FAIL;
2232 
2233  struct ch347_swd_io *pswd_io = ch347_get_one_swd_io();
2234  if (pswd_io) {
2235  ch347_write_spec_seq(out, out_len);
2237  return ERROR_OK;
2238  } else {
2239  return ERROR_FAIL;
2240  }
2241 }
2242 
2243 // check read/write REG can fill in remaining buff
2244 static bool ch347_chk_buf_size(uint8_t cmd, uint32_t ap_delay_clk)
2245 {
2246  bool flush = false;
2247  int send_len = ch347_swd_context.send_len;
2248  int recv_len = ch347_swd_context.need_recv_len;
2249  int len;
2250  do {
2251  if (cmd & SWD_CMD_RNW) {
2252  len = 1 + 1 + 1 + 1; // 0xA2 + len + rev + cmd
2253  if (send_len + len > CH347_MAX_SEND_BUF)
2254  break;
2255  send_len += len;
2256  len = 1 + 1 + 4 + 1;
2257  /* 0xA2 + 1byte(3bit ack) + 4byte(data) +
2258  1byte(1bit parity+1bit trn) */
2259  if (recv_len + len > CH347_MAX_RECV_BUF)
2260  break;
2261  recv_len += len;
2262  } else { // write reg
2263  len = 1 + 1 + 1 + 1 + 4 + 1;
2264  // 0xA0 + len + rev + cmd +data + parity
2265  if (send_len + len > CH347_MAX_SEND_BUF)
2266  break;
2267  send_len += len;
2268  len = 1 + 1; // 0xA0 + 1byte(3bit ack)
2269  if (recv_len + len > CH347_MAX_RECV_BUF)
2270  break;
2271  recv_len += len;
2272  }
2273  if (cmd & SWD_CMD_APNDP) {
2274  len = 1 + 1 + 1 + DIV_ROUND_UP(ap_delay_clk, 8);
2275  // 0xA1 + Len + rev + n byte(delay)
2276  if (send_len + len > CH347_MAX_SEND_BUF)
2277  break;
2278  len = 1; // 0xA1
2279  if ((recv_len + len) > CH347_MAX_RECV_BUF)
2280  break;
2281  }
2282  // swd packet requests
2283  flush = true;
2284  } while (false);
2285 
2286  return flush;
2287 }
2288 
2289 static int ch347_swd_run_queue_inner(void);
2290 
2291 static int ch347_swd_send_idle(uint32_t ap_delay_clk)
2292 {
2293  bool run_q = false;
2294  struct ch347_swd_io *pswd_io = NULL;
2295  unsigned int max_processing_clk = ch347_swd_context.clk_divisor
2298  bool more_q_runs =
2299  1 + 1 + 1 + DIV_ROUND_UP(ap_delay_clk, 8) > CH347_MAX_SEND_BUF
2300  && ap_delay_clk > max_processing_clk;
2301 
2303  unsigned int expected_total_clk = ch347_swd_context.total_swd_clk + ap_delay_clk;
2304  unsigned int expected_send_len = ch347_swd_context.send_len
2305  + 1 + 1 + 1 + DIV_ROUND_UP(ap_delay_clk, 8);
2306  // 0xA1 + Len + rev + n byte(delay)
2307  unsigned int expected_recv_len = ch347_swd_context.need_recv_len + 1;
2308  // 0xA1
2309  unsigned int expected_time = ch347_swd_context.clk_divisor
2310  ? expected_total_clk * ch347_swd_context.clk_divisor
2311  : expected_total_clk / 5;
2312  if (expected_time > CH347_MAX_PROCESSING_US
2313  || expected_send_len > CH347_MAX_SEND_BUF
2314  || expected_recv_len > CH347_MAX_RECV_BUF) {
2315  int send_room = CH347_MAX_SEND_BUF - ch347_swd_context.send_len - 1 - 1 - 1;
2316  if (more_q_runs
2317  && send_room > 0
2318  && expected_recv_len <= CH347_MAX_RECV_BUF
2319  && ch347_swd_context.total_swd_clk < max_processing_clk) {
2320  pswd_io = ch347_get_one_swd_io();
2321  if (pswd_io) {
2322  // fill the rest of queue/time by part of delay
2323  unsigned int this_delay_clk = MIN(ap_delay_clk, 255);
2324  if ((unsigned int)send_room * 8 < this_delay_clk)
2325  this_delay_clk = send_room * 8;
2326  if (max_processing_clk - ch347_swd_context.total_swd_clk < this_delay_clk)
2327  this_delay_clk = max_processing_clk - ch347_swd_context.total_swd_clk;
2328  LOG_DEBUG_IO("partial delay %u clk", this_delay_clk);
2329  ch347_write_spec_seq(NULL, this_delay_clk);
2331  ap_delay_clk -= this_delay_clk;
2332  }
2333  }
2334  run_q = true;
2335  }
2336  }
2337 
2338  do {
2339  if (!run_q)
2340  pswd_io = ch347_get_one_swd_io();
2341 
2342  if (!pswd_io) {
2343  int retval = ch347_swd_run_queue_inner();
2344  if (retval != ERROR_OK)
2345  return retval;
2346 
2347  pswd_io = ch347_get_one_swd_io();
2348  if (!pswd_io) {
2349  LOG_ERROR("ch347 SWD queue not empty after ch347_swd_run_queue");
2351  return ERROR_FAIL;
2352  }
2353  }
2354 
2355  unsigned int send_room = CH347_MAX_SEND_BUF - 1 - 1 - 1;
2356  unsigned int this_delay_clk = MIN(ap_delay_clk, 255);
2357  if (send_room * 8 < this_delay_clk)
2358  this_delay_clk = send_room * 8;
2359  if (max_processing_clk < this_delay_clk)
2360  this_delay_clk = max_processing_clk;
2361  LOG_DEBUG_IO("delay %u clk", this_delay_clk);
2362  ch347_write_spec_seq(NULL, this_delay_clk);
2364  ap_delay_clk -= this_delay_clk;
2365  run_q = true;
2366  pswd_io = NULL;
2367  } while (ap_delay_clk);
2368  return ERROR_OK;
2369 }
2370 
2372 {
2373  LOG_DEBUG_IO("Executing %u queued transactions", ch347_swd_context.sent_cmd_count);
2375  LOG_DEBUG_IO("Skipping due to previous errors: %d", ch347_swd_context.queued_retval);
2376  goto skip;
2377  }
2378 
2379  int retval = ch347_swd_queue_flush();
2380  if (retval != ERROR_OK)
2381  return retval;
2382 
2384  LOG_ERROR("CH347 usb write/read failed - queued_retval");
2385  goto skip;
2386  }
2387  uint8_t *recv_buf = ch347_swd_context.recv_buf;
2388  int recv_len = 0;
2389  if (recv_buf[recv_len++] != CH347_CMD_SWD) { // 0XE8
2391  LOG_ERROR("CH347 usb write/read failed - not CH347_CMD_SWD");
2392  goto skip;
2393  }
2394 
2395  int cmds_len = le_to_h_u16(&recv_buf[recv_len]);
2396  recv_len += 2; // cmds_len
2397  if ((cmds_len + CH347_CMD_HEADER) > ch347_swd_context.recv_len) {
2399  LOG_ERROR("CH347 usb write/read failed - too long");
2400  goto skip;
2401  }
2402 
2403  struct list_head *tmp;
2404  struct list_head *pos;
2405  struct ch347_swd_io *pswd_io;
2406 
2408  pswd_io = list_entry(pos, struct ch347_swd_io, list_entry);
2409  if (pswd_io->usb_cmd == CH347_CMD_SWD_SEQ_W) {
2410  if (recv_buf[recv_len++] != CH347_CMD_SWD_SEQ_W) {
2412  LOG_ERROR("CH347 usb write/read failed - not CH347_CMD_SWD_SEQ_W");
2413  goto skip;
2414  }
2415  } else { // read/write Reg
2416  uint32_t ack;
2417  bool check_ack;
2418  // read Reg
2419  if (recv_buf[recv_len] == CH347_CMD_SWD_REG_R) {
2420  recv_len++;
2421  ack = buf_get_u32(&recv_buf[recv_len++], 0, 3);
2422  /* Devices do not reply to DP_TARGETSEL write
2423  cmd, ignore received ack */
2424  check_ack = swd_cmd_returns_ack(pswd_io->cmd);
2425  if (pswd_io->cmd & SWD_CMD_RNW) {
2426  uint32_t data = buf_get_u32(&recv_buf[recv_len], 0, 32);
2427 
2428  LOG_CUSTOM_LEVEL((check_ack && ack != SWD_ACK_OK)
2430  "%s%s %s read reg %X = %08" PRIx32,
2431  check_ack ? "" : "ack ignored ",
2432  ack == SWD_ACK_OK ? "OK" :
2433  ack == SWD_ACK_WAIT ? "WAIT" :
2434  ack == SWD_ACK_FAULT ? "FAULT" : "JUNK",
2435  pswd_io->cmd & SWD_CMD_APNDP ? "AP" : "DP",
2436  (pswd_io->cmd & SWD_CMD_A32) >> 1,
2437  data);
2438 
2439  if (ack != SWD_ACK_OK && check_ack) {
2441  goto skip;
2442  }
2443 
2444  uint32_t parity = buf_get_u32(&recv_buf[recv_len], 32, 1);
2445  if (parity != (uint32_t)parity_u32(data)) {
2446  LOG_ERROR("SWD Read data parity mismatch");
2448  goto skip;
2449  }
2450 
2451  if (pswd_io->dst)
2452  *pswd_io->dst = data;
2453  } else {
2455  LOG_ERROR("CH347 usb write/read failed - not SWD_CMD_RNW");
2456  goto skip;
2457  }
2458  recv_len += 5;
2459  } else if (recv_buf[recv_len] == CH347_CMD_SWD_REG_W) {
2460  recv_len++;
2461  ack = buf_get_u32(&recv_buf[recv_len++], 0, 3);
2462  /* Devices do not reply to DP_TARGETSEL write
2463  cmd, ignore received ack */
2464  check_ack = swd_cmd_returns_ack(pswd_io->cmd);
2465 
2466  LOG_CUSTOM_LEVEL((check_ack && ack != SWD_ACK_OK)
2468  "%s%s %s write reg %X = %08" PRIx32,
2469  check_ack ? "" : "ack ignored ",
2470  ack == SWD_ACK_OK ? "OK" :
2471  ack == SWD_ACK_WAIT ? "WAIT" :
2472  ack == SWD_ACK_FAULT ? "FAULT" : "JUNK",
2473  pswd_io->cmd & SWD_CMD_APNDP ? "AP" : "DP",
2474  (pswd_io->cmd & SWD_CMD_A32) >> 1,
2475  pswd_io->value);
2476 
2477  if (ack != SWD_ACK_OK && check_ack) {
2479  goto skip;
2480  }
2481  } else {
2483  LOG_ERROR("CH347 usb write/read failed recv_len = %d", recv_len);
2484  goto skip;
2485  }
2486  }
2487  list_del_init(&pswd_io->list_entry);
2488  list_add_tail(&pswd_io->list_entry,
2490  }
2491 
2492 skip:
2495  pswd_io = list_entry(pos, struct ch347_swd_io, list_entry);
2496  list_del_init(&pswd_io->list_entry);
2497  list_add_tail(&pswd_io->list_entry,
2499  }
2500  }
2501 
2502  // 0xE8 + 2byte len
2504  // 0xE8 + 2byte len
2511  return retval;
2512 }
2513 
2514 static int ch347_swd_run_queue(void)
2515 {
2516  /* A transaction must be followed by another transaction or at least 8
2517  idle cycles to ensure that data is clocked through the AP. */
2518  int retval = ch347_swd_send_idle(8);
2519  if (retval != ERROR_OK)
2520  return retval;
2521 
2522  return ch347_swd_run_queue_inner();
2523 }
2524 
2525 static int ch347_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk)
2526 {
2527  int retval = ERROR_OK;
2528  bool run_q = false;
2530  unsigned int expected_total_clk = ch347_swd_context.total_swd_clk
2531  + 46 // SWD transaction
2532  + ap_delay_clk
2533  + 8; // 8 idle cycles at the end of queue
2534  unsigned int expected_time = ch347_swd_context.clk_divisor
2535  ? expected_total_clk * ch347_swd_context.clk_divisor
2536  : expected_total_clk / 5;
2537  if (expected_time > CH347_MAX_PROCESSING_US) {
2538  LOG_DEBUG_IO("Expected queue run %u cycles, with this cmd %u",
2539  ch347_swd_context.total_swd_clk, expected_total_clk);
2540  run_q = true;
2541  } else if (!ch347_chk_buf_size(cmd, ap_delay_clk)) {
2542  run_q = true;
2543  }
2544  }
2545 
2546  struct ch347_swd_io *pswd_io = NULL;
2547  if (!run_q)
2548  pswd_io = ch347_get_one_swd_io();
2549 
2550  if (!pswd_io) {
2551  retval = ch347_swd_run_queue_inner();
2552  if (retval != ERROR_OK)
2553  return retval;
2554 
2555  pswd_io = ch347_get_one_swd_io();
2556  if (!pswd_io) {
2557  LOG_ERROR("ch347 SWD queue not empty after ch347_swd_run_queue");
2559  return ERROR_FAIL;
2560  }
2561  }
2562 
2563  pswd_io->cmd = cmd | SWD_CMD_START | SWD_CMD_PARK;
2564 
2565  if (pswd_io->cmd & SWD_CMD_RNW) {
2566  pswd_io->usb_cmd = CH347_CMD_SWD_REG_R;
2567  pswd_io->dst = dst;
2568  ch347_read_swd_reg(pswd_io->cmd);
2569  } else {
2570  pswd_io->usb_cmd = CH347_CMD_SWD_REG_W;
2571  pswd_io->value = data;
2572  ch347_write_swd_reg(pswd_io->cmd, data);
2573  }
2574 
2577 
2578  // Insert idle cycles after AP accesses to avoid WAIT
2579  if (ap_delay_clk)
2580  retval = ch347_swd_send_idle(ap_delay_clk);
2581 
2582  return retval;
2583 }
2584 
2586 {
2587  switch (seq) {
2588  case LINE_RESET:
2589  LOG_DEBUG("SWD line reset");
2591  case JTAG_TO_SWD:
2592  LOG_DEBUG("JTAG-to-SWD");
2594  case JTAG_TO_DORMANT:
2595  LOG_DEBUG("JTAG-to-DORMANT");
2597  case SWD_TO_JTAG:
2598  LOG_DEBUG("SWD-to-JTAG");
2600  case SWD_TO_DORMANT:
2601  LOG_DEBUG("SWD-to-DORMANT");
2603  case DORMANT_TO_SWD:
2604  LOG_DEBUG("DORMANT-to-SWD");
2606  case DORMANT_TO_JTAG:
2607  LOG_DEBUG("DORMANT-to-JTAG");
2609  default:
2610  LOG_ERROR("Sequence %d not supported", seq);
2611  return ERROR_FAIL;
2612  }
2613 }
2614 
2615 static int ch347_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
2616 {
2617  assert(cmd & SWD_CMD_RNW);
2618  return ch347_swd_queue_cmd(cmd, value, 0, ap_delay_clk);
2619 }
2620 
2621 static int ch347_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
2622 {
2623  assert(!(cmd & SWD_CMD_RNW));
2624  return ch347_swd_queue_cmd(cmd, NULL, value, ap_delay_clk);
2625 }
2626 
2627 static const struct swd_driver ch347_swd = {
2628  .init = ch347_swd_init,
2629  .switch_seq = ch347_swd_switch_seq,
2630  .read_reg = ch347_swd_read_reg,
2631  .write_reg = ch347_swd_write_reg,
2632  .run = ch347_swd_run_queue,
2633 };
2634 
2635 static struct jtag_interface ch347_interface = {
2637  .execute_queue = ch347_execute_queue,
2638 };
2639 
2641  .name = "ch347",
2642  .transport_ids = TRANSPORT_JTAG | TRANSPORT_SWD,
2643  .transport_preferred_id = TRANSPORT_JTAG,
2644  .commands = ch347_command_handlers,
2645 
2646  .init = ch347_init,
2647  .quit = ch347_quit,
2648  .reset = ch347_reset,
2649  .speed = ch347_speed_set,
2650  .khz = ch347_speed_get_index,
2651  .speed_div = ch347_speed_get,
2652 
2653  .jtag_ops = &ch347_interface,
2654  .swd_ops = &ch347_swd,
2655 };
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:1016
static int ch347_scratchpad_add_idle_clock(void)
Function to ensure that the clock is in a low state.
Definition: ch347.c:1093
static int ch347_scratchpad_add_move_state(enum tap_state state, int skip)
Toggle the tap state to the target state.
Definition: ch347.c:1164
#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:2640
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:956
#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:1891
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:2226
#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:1762
#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:2141
#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:1130
#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:2003
#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:1984
#define DEFAULT_VENDOR_ID
Definition: ch347.c:153
static void ch347_write_swd_reg(uint8_t cmd, const uint32_t out)
Definition: ch347.c:2188
static uint8_t ch347_usable_gpios(void)
Mask of the GPIO's that don't collide with an interface signal.
Definition: ch347.c:1351
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:815
#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:1369
#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:2514
static const struct swd_driver ch347_swd
Definition: ch347.c:2627
#define CH347_SINGLE_CMD_MAX_READ
Definition: ch347.c:125
static int ch347_speed_get_index(int khz, int *speed_idx)
multiplies the input speed by 1000
Definition: ch347.c:1943
#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:1832
static int ch347_open_device(void)
opens the CH347 device via libusb driver
Definition: ch347.c:1626
static int ch347_scratchpad_add_stableclocks(int count)
Function adds a certain amount of TCK pulses without changing the TMS pin.
Definition: ch347.c:1070
#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:917
static int ch347_execute_queue(struct jtag_command *cmd_queue)
Executes the command queue.
Definition: ch347.c:1571
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:2024
static int ch347_swd_send_idle(uint32_t ap_delay_clk)
Definition: ch347.c:2291
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:683
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:1447
#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:1463
#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:2621
static int ch347_gpio_set(int gpio, bool data)
Sets a GPIO bit.
Definition: ch347.c:1422
static int ch347_swd_queue_flush(void)
Definition: ch347.c:2156
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:936
static void ch347_write_spec_seq(const uint8_t *out, uint8_t out_len)
Definition: ch347.c:2203
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:857
static int ch347_scratchpad_add_run_test(int cycles, enum tap_state state)
Toggle the Tap state to run test/idle.
Definition: ch347.c:1285
#define CH347_MAX_RECV_BUF
Definition: ch347.c:136
static int ch347_speed_get(int speed_idx, int *khz)
returns the speed in kHz by the give speed index
Definition: ch347.c:1917
#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:2525
static int ch347_swd_switch_seq(enum swd_special_seq seq)
Definition: ch347.c:2585
static struct jtag_interface ch347_interface
Definition: ch347.c:2635
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:2244
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:1190
#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:1401
static uint8_t ch347_activity_led_gpio_pin
Definition: ch347.c:273
static bool ch347_dedicated_srst_assert_at_init(void)
Definition: ch347.c:986
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:1107
static int ch347_swd_init(void)
Initialization for the swd mode.
Definition: ch347.c:2119
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:880
#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:1558
static void ch347_read_swd_reg(uint8_t cmd)
Definition: ch347.c:2215
#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:1820
static int ch347_init(void)
CH347 Initialization function.
Definition: ch347.c:2057
static int ch347_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
Definition: ch347.c:2615
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:1783
#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:1052
static int ch347_swd_run_queue_inner(void)
Definition: ch347.c:2371
#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:899
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:1844
#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:1872
#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:1497
static int ch347_scratchpad_add_scan(struct scan_command *cmd)
Switch to SHIFT-DR or SHIFT-IR status for scanning.
Definition: ch347.c:1308
#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