1 /***************************************************************************
2 * Copyright (C) 2021 by Adrian Negreanu *
5 * Copyright (C) 2018 by Mickaƫl Thomas *
8 * Copyright (C) 2016 by Maksym Hilliaka *
9 * oter@frozen-team.com *
11 * Copyright (C) 2016 by Phillip Pearson *
14 * Copyright (C) 2014 by Paul Fertser *
15 * fercerpav@gmail.com *
17 * Copyright (C) 2013 by mike brown *
18 * mike@theshedworks.org.uk *
20 * Copyright (C) 2013 by Spencer Oliver *
21 * spen@spen-soft.co.uk *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
35 ***************************************************************************/
41 #include <transport/transport.h>
42 #include "helper/replacements.h"
43 #include <jtag/adapter.h>
45 #include <jtag/interface.h>
46 #include <jtag/commands.h>
48 #include <target/cortex_m.h>
50 #include "cmsis_dap.h"
52 static const struct cmsis_dap_backend *const cmsis_dap_backends[] = {
53 #if BUILD_CMSIS_DAP_USB == 1
54 &cmsis_dap_usb_backend,
57 #if BUILD_CMSIS_DAP_HID == 1
58 &cmsis_dap_hid_backend,
64 /* Known vid/pid pairs:
65 * VID 0xc251: Keil Software
66 * PID 0xf001: LPC-Link-II CMSIS_DAP
67 * PID 0xf002: OPEN-SDA CMSIS_DAP (Freedom Board)
68 * PID 0x2722: Keil ULINK2 CMSIS-DAP
69 * PID 0x2750: Keil ULINKplus CMSIS-DAP
71 * VID 0x0d28: mbed Software
72 * PID 0x0204: MBED CMSIS-DAP
76 /* vid = pid = 0 marks the end of the list */
77 static uint16_t cmsis_dap_vid[MAX_USB_IDS + 1] = { 0 };
78 static uint16_t cmsis_dap_pid[MAX_USB_IDS + 1] = { 0 };
79 static int cmsis_dap_backend = -1;
82 #define USB_TIMEOUT 1000
84 /* CMSIS-DAP General Commands */
85 #define CMD_DAP_INFO 0x00
86 #define CMD_DAP_LED 0x01
87 #define CMD_DAP_CONNECT 0x02
88 #define CMD_DAP_DISCONNECT 0x03
89 #define CMD_DAP_WRITE_ABORT 0x08
90 #define CMD_DAP_DELAY 0x09
91 #define CMD_DAP_RESET_TARGET 0x0A
94 #define INFO_ID_VENDOR 0x01 /* string */
95 #define INFO_ID_PRODUCT 0x02 /* string */
96 #define INFO_ID_SERNUM 0x03 /* string */
97 #define INFO_ID_FW_VER 0x04 /* string */
98 #define INFO_ID_TD_VEND 0x05 /* string */
99 #define INFO_ID_TD_NAME 0x06 /* string */
100 #define INFO_ID_CAPS 0xf0 /* byte */
101 #define INFO_ID_PKT_CNT 0xfe /* byte */
102 #define INFO_ID_PKT_SZ 0xff /* short */
103 #define INFO_ID_SWO_BUF_SZ 0xfd /* word */
105 #define INFO_CAPS_SWD BIT(0)
106 #define INFO_CAPS_JTAG BIT(1)
107 #define INFO_CAPS_SWO_UART BIT(2)
108 #define INFO_CAPS_SWO_MANCHESTER BIT(3)
109 #define INFO_CAPS_ATOMIC_CMDS BIT(4)
110 #define INFO_CAPS_TEST_DOMAIN_TIMER BIT(5)
111 #define INFO_CAPS_SWO_STREAMING_TRACE BIT(6)
112 #define INFO_CAPS_UART_PORT BIT(7)
113 #define INFO_CAPS_USB_COM_PORT BIT(8)
114 #define INFO_CAPS__NUM_CAPS 9
117 #define LED_ID_CONNECT 0x00
118 #define LED_ID_RUN 0x01
124 #define CONNECT_DEFAULT 0x00
125 #define CONNECT_SWD 0x01
126 #define CONNECT_JTAG 0x02
128 /* CMSIS-DAP Common SWD/JTAG Commands */
129 #define CMD_DAP_DELAY 0x09
130 #define CMD_DAP_SWJ_PINS 0x10
131 #define CMD_DAP_SWJ_CLOCK 0x11
132 #define CMD_DAP_SWJ_SEQ 0x12
144 #define SWJ_PIN_TCK (1<<0)
145 #define SWJ_PIN_TMS (1<<1)
146 #define SWJ_PIN_TDI (1<<2)
147 #define SWJ_PIN_TDO (1<<3)
148 #define SWJ_PIN_TRST (1<<5)
149 #define SWJ_PIN_SRST (1<<7)
151 /* CMSIS-DAP SWD Commands */
152 #define CMD_DAP_SWD_CONFIGURE 0x13
153 #define CMD_DAP_SWD_SEQUENCE 0x1D
155 /* CMSIS-DAP JTAG Commands */
156 #define CMD_DAP_JTAG_SEQ 0x14
157 #define CMD_DAP_JTAG_CONFIGURE 0x15
158 #define CMD_DAP_JTAG_IDCODE 0x16
160 /* CMSIS-DAP JTAG sequence info masks */
161 /* Number of bits to clock through (0 means 64) */
162 #define DAP_JTAG_SEQ_TCK 0x3F
163 /* TMS will be set during the sequence if this bit is set */
164 #define DAP_JTAG_SEQ_TMS 0x40
165 /* TDO output will be captured if this bit is set */
166 #define DAP_JTAG_SEQ_TDO 0x80
169 /* CMSIS-DAP Transfer Commands */
170 #define CMD_DAP_TFER_CONFIGURE 0x04
171 #define CMD_DAP_TFER 0x05
172 #define CMD_DAP_TFER_BLOCK 0x06
173 #define CMD_DAP_TFER_ABORT 0x07
175 /* DAP Status Code */
177 #define DAP_ERROR 0xFF
179 /* CMSIS-DAP SWO Commands */
180 #define CMD_DAP_SWO_TRANSPORT 0x17
181 #define CMD_DAP_SWO_MODE 0x18
182 #define CMD_DAP_SWO_BAUDRATE 0x19
183 #define CMD_DAP_SWO_CONTROL 0x1A
184 #define CMD_DAP_SWO_STATUS 0x1B
185 #define CMD_DAP_SWO_DATA 0x1C
186 #define CMD_DAP_SWO_EX_STATUS 0x1E
188 /* SWO transport mode for reading trace data */
189 #define DAP_SWO_TRANSPORT_NONE 0
190 #define DAP_SWO_TRANSPORT_DATA 1
191 #define DAP_SWO_TRANSPORT_WINUSB 2
193 /* SWO trace capture mode */
194 #define DAP_SWO_MODE_OFF 0
195 #define DAP_SWO_MODE_UART 1
196 #define DAP_SWO_MODE_MANCHESTER 2
198 /* SWO trace data capture */
199 #define DAP_SWO_CONTROL_STOP 0
200 #define DAP_SWO_CONTROL_START 1
202 /* SWO trace status */
203 #define DAP_SWO_STATUS_CAPTURE_INACTIVE 0
204 #define DAP_SWO_STATUS_CAPTURE_ACTIVE 1
205 #define DAP_SWO_STATUS_CAPTURE_MASK BIT(0)
206 #define DAP_SWO_STATUS_STREAM_ERROR_MASK BIT(6)
207 #define DAP_SWO_STATUS_BUFFER_OVERRUN_MASK BIT(7)
209 /* CMSIS-DAP Vendor Commands
212 static const char * const info_caps_str[INFO_CAPS__NUM_CAPS] = {
215 "SWO-UART supported",
216 "SWO-MANCHESTER supported",
217 "Atomic commands supported",
218 "Test domain timer supported",
219 "SWO streaming trace supported",
220 "UART communication port supported",
221 "UART via USB COM port supported",
224 struct pending_transfer_result {
230 struct pending_request_block {
231 struct pending_transfer_result *transfers;
235 struct pending_scan_result {
236 /** Offset in bytes in the CMD_DAP_JTAG_SEQ response buffer. */
238 /** Number of bits to read. */
240 /** Location to store the result */
242 /** Offset in the destination buffer */
243 unsigned buffer_offset;
246 /* Up to MIN(packet_count, MAX_PENDING_REQUESTS) requests may be issued
247 * until the first response arrives */
248 #define MAX_PENDING_REQUESTS 3
250 /* Pending requests are organized as a FIFO - circular buffer */
251 /* Each block in FIFO can contain up to pending_queue_len transfers */
252 static int pending_queue_len;
253 static struct pending_request_block pending_fifo[MAX_PENDING_REQUESTS];
254 static int pending_fifo_put_idx, pending_fifo_get_idx;
255 static int pending_fifo_block_count;
257 /* pointers to buffers that will receive jtag scan results on the next flush */
258 #define MAX_PENDING_SCAN_RESULTS 256
259 static int pending_scan_result_count;
260 static struct pending_scan_result pending_scan_results[MAX_PENDING_SCAN_RESULTS];
262 /* queued JTAG sequences that will be executed on the next flush */
263 #define QUEUED_SEQ_BUF_LEN (cmsis_dap_handle->packet_size - 3)
264 static int queued_seq_count;
265 static int queued_seq_buf_end;
266 static int queued_seq_tdo_ptr;
267 static uint8_t queued_seq_buf[1024]; /* TODO: make dynamic / move into cmsis object */
269 static int queued_retval;
271 static uint8_t output_pins = SWJ_PIN_SRST | SWJ_PIN_TRST;
273 static struct cmsis_dap *cmsis_dap_handle;
276 static int cmsis_dap_quit(void);
278 static int cmsis_dap_open(void)
280 const struct cmsis_dap_backend *backend = NULL;
282 struct cmsis_dap *dap = calloc(1, sizeof(struct cmsis_dap));
284 LOG_ERROR("unable to allocate memory");
288 if (cmsis_dap_backend >= 0) {
289 /* Use forced backend */
290 backend = cmsis_dap_backends[cmsis_dap_backend];
291 if (backend->open(dap, cmsis_dap_vid, cmsis_dap_pid, adapter_get_required_serial()) != ERROR_OK)
294 /* Try all backends */
295 for (unsigned int i = 0; i < ARRAY_SIZE(cmsis_dap_backends); i++) {
296 backend = cmsis_dap_backends[i];
297 if (backend->open(dap, cmsis_dap_vid, cmsis_dap_pid, adapter_get_required_serial()) == ERROR_OK)
305 LOG_ERROR("unable to find a matching CMSIS-DAP device");
310 dap->backend = backend;
312 cmsis_dap_handle = dap;
317 static void cmsis_dap_close(struct cmsis_dap *dap)
320 dap->backend->close(dap);
324 free(cmsis_dap_handle->packet_buffer);
325 free(cmsis_dap_handle);
326 cmsis_dap_handle = NULL;
328 for (int i = 0; i < MAX_PENDING_REQUESTS; i++) {
329 free(pending_fifo[i].transfers);
330 pending_fifo[i].transfers = NULL;
334 static void cmsis_dap_flush_read(struct cmsis_dap *dap)
337 /* Some CMSIS-DAP adapters keep buffered packets over
338 * USB close/open so we need to flush up to 64 old packets
339 * to be sure all buffers are empty */
340 for (i = 0; i < 64; i++) {
341 int retval = dap->backend->read(dap, 10);
342 if (retval == ERROR_TIMEOUT_REACHED)
346 LOG_DEBUG("Flushed %u packets", i);
349 /* Send a message and receive the reply */
350 static int cmsis_dap_xfer(struct cmsis_dap *dap, int txlen)
352 if (pending_fifo_block_count) {
353 LOG_ERROR("pending %d blocks, flushing", pending_fifo_block_count);
354 while (pending_fifo_block_count) {
355 dap->backend->read(dap, 10);
356 pending_fifo_block_count--;
358 pending_fifo_put_idx = 0;
359 pending_fifo_get_idx = 0;
362 uint8_t current_cmd = cmsis_dap_handle->command[0];
363 int retval = dap->backend->write(dap, txlen, USB_TIMEOUT);
368 retval = dap->backend->read(dap, USB_TIMEOUT);
372 uint8_t *resp = cmsis_dap_handle->response;
373 if (resp[0] == DAP_ERROR) {
374 LOG_ERROR("CMSIS-DAP command 0x%" PRIx8 " not implemented", current_cmd);
375 return ERROR_NOT_IMPLEMENTED;
378 if (resp[0] != current_cmd) {
379 LOG_ERROR("CMSIS-DAP command mismatch. Sent 0x%" PRIx8
380 " received 0x%" PRIx8, current_cmd, resp[0]);
382 cmsis_dap_flush_read(dap);
389 static int cmsis_dap_cmd_dap_swj_pins(uint8_t pins, uint8_t mask, uint32_t delay, uint8_t *input)
391 uint8_t *command = cmsis_dap_handle->command;
393 command[0] = CMD_DAP_SWJ_PINS;
396 h_u32_to_le(&command[3], delay);
398 int retval = cmsis_dap_xfer(cmsis_dap_handle, 7);
399 if (retval != ERROR_OK) {
400 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_PINS failed.");
401 return ERROR_JTAG_DEVICE_ERROR;
405 *input = cmsis_dap_handle->response[1];
410 static int cmsis_dap_cmd_dap_swj_clock(uint32_t swj_clock)
412 uint8_t *command = cmsis_dap_handle->command;
414 /* set clock in Hz */
417 command[0] = CMD_DAP_SWJ_CLOCK;
418 h_u32_to_le(&command[1], swj_clock);
420 int retval = cmsis_dap_xfer(cmsis_dap_handle, 5);
421 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
422 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_CLOCK failed.");
423 return ERROR_JTAG_DEVICE_ERROR;
429 /* clock a sequence of bits out on TMS, to change JTAG states */
430 static int cmsis_dap_cmd_dap_swj_sequence(uint8_t s_len, const uint8_t *sequence)
432 uint8_t *command = cmsis_dap_handle->command;
434 #ifdef CMSIS_DAP_JTAG_DEBUG
435 LOG_DEBUG("cmsis-dap TMS sequence: len=%d", s_len);
436 for (int i = 0; i < DIV_ROUND_UP(s_len, 8); ++i)
437 printf("%02X ", sequence[i]);
442 command[0] = CMD_DAP_SWJ_SEQ;
444 bit_copy(&command[2], 0, sequence, 0, s_len);
446 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2 + DIV_ROUND_UP(s_len, 8));
447 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK)
453 static int cmsis_dap_cmd_dap_info(uint8_t info, uint8_t **data)
455 uint8_t *command = cmsis_dap_handle->command;
457 command[0] = CMD_DAP_INFO;
460 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
461 if (retval != ERROR_OK) {
462 LOG_ERROR("CMSIS-DAP command CMD_INFO failed.");
463 return ERROR_JTAG_DEVICE_ERROR;
466 *data = &cmsis_dap_handle->response[1];
471 static int cmsis_dap_cmd_dap_led(uint8_t led, uint8_t state)
473 uint8_t *command = cmsis_dap_handle->command;
475 command[0] = CMD_DAP_LED;
479 int retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
480 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
481 LOG_ERROR("CMSIS-DAP command CMD_LED failed.");
482 return ERROR_JTAG_DEVICE_ERROR;
488 static int cmsis_dap_cmd_dap_connect(uint8_t mode)
490 uint8_t *command = cmsis_dap_handle->command;
492 command[0] = CMD_DAP_CONNECT;
495 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
496 if (retval != ERROR_OK) {
497 LOG_ERROR("CMSIS-DAP command CMD_CONNECT failed.");
498 return ERROR_JTAG_DEVICE_ERROR;
501 if (cmsis_dap_handle->response[1] != mode) {
502 LOG_ERROR("CMSIS-DAP failed to connect in mode (%d)", mode);
503 return ERROR_JTAG_DEVICE_ERROR;
509 static int cmsis_dap_cmd_dap_disconnect(void)
511 uint8_t *command = cmsis_dap_handle->command;
513 command[0] = CMD_DAP_DISCONNECT;
515 int retval = cmsis_dap_xfer(cmsis_dap_handle, 1);
516 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
517 LOG_ERROR("CMSIS-DAP command CMD_DISCONNECT failed.");
518 return ERROR_JTAG_DEVICE_ERROR;
524 static int cmsis_dap_cmd_dap_tfer_configure(uint8_t idle, uint16_t retry_count, uint16_t match_retry)
526 uint8_t *command = cmsis_dap_handle->command;
528 command[0] = CMD_DAP_TFER_CONFIGURE;
530 h_u16_to_le(&command[2], retry_count);
531 h_u16_to_le(&command[4], match_retry);
533 int retval = cmsis_dap_xfer(cmsis_dap_handle, 6);
534 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
535 LOG_ERROR("CMSIS-DAP command CMD_TFER_Configure failed.");
536 return ERROR_JTAG_DEVICE_ERROR;
542 static int cmsis_dap_cmd_dap_swd_configure(uint8_t cfg)
544 uint8_t *command = cmsis_dap_handle->command;
546 command[0] = CMD_DAP_SWD_CONFIGURE;
549 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
550 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
551 LOG_ERROR("CMSIS-DAP command CMD_SWD_Configure failed.");
552 return ERROR_JTAG_DEVICE_ERROR;
559 static int cmsis_dap_cmd_dap_delay(uint16_t delay_us)
561 uint8_t *command = cmsis_dap_handle->command;
563 command[0] = CMD_DAP_DELAY;
564 h_u16_to_le(&command[1], delay_us);
566 int retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
567 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
568 LOG_ERROR("CMSIS-DAP command CMD_Delay failed.");
569 return ERROR_JTAG_DEVICE_ERROR;
576 static int cmsis_dap_metacmd_targetsel(uint32_t instance_id)
578 uint8_t *command = cmsis_dap_handle->command;
579 const uint32_t SEQ_RD = 0x80, SEQ_WR = 0x00;
581 /* SWD multi-drop requires a transfer ala CMD_DAP_TFER,
582 but with no expectation of an SWD ACK response. In
583 CMSIS-DAP v1.20 and v2.00, CMD_DAP_SWD_SEQUENCE was
584 added to allow this special sequence to be generated.
585 The purpose of this operation is to select the target
586 corresponding to the instance_id that is written */
589 command[idx++] = CMD_DAP_SWD_SEQUENCE;
590 command[idx++] = 3; /* sequence count */
592 /* sequence 0: packet request for TARGETSEL */
593 command[idx++] = SEQ_WR | 8;
594 command[idx++] = SWD_CMD_START | swd_cmd(false, false, DP_TARGETSEL) | SWD_CMD_STOP | SWD_CMD_PARK;
596 /* sequence 1: read Trn ACK Trn, no expectation for target to ACK */
597 command[idx++] = SEQ_RD | 5;
599 /* sequence 2: WDATA plus parity */
600 command[idx++] = SEQ_WR | (32 + 1);
601 h_u32_to_le(command + idx, instance_id);
603 command[idx++] = parity_u32(instance_id);
605 int retval = cmsis_dap_xfer(cmsis_dap_handle, idx);
606 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
607 LOG_ERROR("CMSIS-DAP command SWD_Sequence failed.");
608 return ERROR_JTAG_DEVICE_ERROR;
615 * Sets the SWO transport mode.
616 * @param[in] transport The transport mode. Can be None, SWO_Data or
617 * WinUSB (requires CMSIS-DAP v2).
619 static int cmsis_dap_cmd_dap_swo_transport(uint8_t transport)
621 uint8_t *command = cmsis_dap_handle->command;
623 command[0] = CMD_DAP_SWO_TRANSPORT;
624 command[1] = transport;
626 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
627 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
628 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Transport(%d) failed.", transport);
629 return ERROR_JTAG_DEVICE_ERROR;
636 * Sets the SWO trace capture mode.
637 * @param[in] mode Trace capture mode. Can be UART or MANCHESTER.
639 static int cmsis_dap_cmd_dap_swo_mode(uint8_t mode)
641 uint8_t *command = cmsis_dap_handle->command;
643 command[0] = CMD_DAP_SWO_MODE;
646 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
647 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
648 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Mode(%d) failed.", mode);
649 return ERROR_JTAG_DEVICE_ERROR;
656 * Sets the baudrate for capturing SWO trace data.
657 * Can be called iteratively to determine supported baudrates.
658 * @param[in] in_baudrate Requested baudrate.
659 * @param[out] dev_baudrate Actual baudrate or 0 (baudrate not configured).
660 * When requested baudrate is not achievable the
661 * closest configured baudrate can be returned or
662 * 0 which indicates that baudrate was not configured.
664 static int cmsis_dap_cmd_dap_swo_baudrate(
665 uint32_t in_baudrate,
666 uint32_t *dev_baudrate)
668 uint8_t *command = cmsis_dap_handle->command;
670 command[0] = CMD_DAP_SWO_BAUDRATE;
671 h_u32_to_le(&command[1], in_baudrate);
673 int retval = cmsis_dap_xfer(cmsis_dap_handle, 4);
674 uint32_t rvbr = le_to_h_u32(&cmsis_dap_handle->response[1]);
675 if (retval != ERROR_OK || rvbr == 0) {
676 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Baudrate(%u) -> %u failed.", in_baudrate, rvbr);
679 return ERROR_JTAG_DEVICE_ERROR;
683 *dev_baudrate = rvbr;
689 * Controls the SWO trace data capture.
690 * @param[in] control Start or stop a trace. Starting capture automatically
691 * flushes any existing trace data in buffers which has
694 static int cmsis_dap_cmd_dap_swo_control(uint8_t control)
696 uint8_t *command = cmsis_dap_handle->command;
698 command[0] = CMD_DAP_SWO_CONTROL;
699 command[1] = control;
701 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
702 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
703 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Control(%d) failed.", control);
704 return ERROR_JTAG_DEVICE_ERROR;
711 * Reads the SWO trace status.
712 * @param[out] trace_status The trace's status.
713 * Bit0: Trace Capture (1 - active, 0 - inactive).
714 * Bit6: Trace Stream Error.
715 * Bit7: Trace Buffer Overrun.
716 * @param[out] trace_count Number of bytes in Trace Buffer (not yet read).
718 static int cmsis_dap_cmd_dap_swo_status(
719 uint8_t *trace_status,
722 uint8_t *command = cmsis_dap_handle->command;
724 command[0] = CMD_DAP_SWO_STATUS;
726 int retval = cmsis_dap_xfer(cmsis_dap_handle, 1);
727 if (retval != ERROR_OK) {
728 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Status failed.");
729 return ERROR_JTAG_DEVICE_ERROR;
733 *trace_status = cmsis_dap_handle->response[1];
735 *trace_count = le_to_h_u32(&cmsis_dap_handle->response[2]);
741 * Reads the captured SWO trace data from Trace Buffer.
742 * @param[in] max_trace_count Maximum number of Trace Data bytes to read.
743 * @param[out] trace_status The trace's status.
744 * @param[out] trace_count Number of Trace Data bytes read.
745 * @param[out] data Trace Data bytes read.
747 static int cmsis_dap_cmd_dap_swo_data(
748 size_t max_trace_count,
749 uint8_t *trace_status,
753 uint8_t *command = cmsis_dap_handle->command;
755 command[0] = CMD_DAP_SWO_DATA;
756 h_u16_to_le(&command[1], max_trace_count);
758 int retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
759 if (retval != ERROR_OK) {
760 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Data failed.");
761 return ERROR_JTAG_DEVICE_ERROR;
764 *trace_status = cmsis_dap_handle->response[1];
765 *trace_count = le_to_h_u16(&cmsis_dap_handle->response[2]);
767 if (*trace_count > 0)
768 memcpy(data, &cmsis_dap_handle->response[4], *trace_count);
773 static void cmsis_dap_swd_write_from_queue(struct cmsis_dap *dap)
775 uint8_t *command = cmsis_dap_handle->command;
776 struct pending_request_block *block = &pending_fifo[pending_fifo_put_idx];
778 LOG_DEBUG_IO("Executing %d queued transactions from FIFO index %d", block->transfer_count, pending_fifo_put_idx);
780 if (queued_retval != ERROR_OK) {
781 LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
785 if (block->transfer_count == 0)
788 command[0] = CMD_DAP_TFER;
789 command[1] = 0x00; /* DAP Index */
790 command[2] = block->transfer_count;
793 for (int i = 0; i < block->transfer_count; i++) {
794 struct pending_transfer_result *transfer = &(block->transfers[i]);
795 uint8_t cmd = transfer->cmd;
796 uint32_t data = transfer->data;
798 LOG_DEBUG_IO("%s %s reg %x %"PRIx32,
799 cmd & SWD_CMD_APNDP ? "AP" : "DP",
800 cmd & SWD_CMD_RNW ? "read" : "write",
801 (cmd & SWD_CMD_A32) >> 1, data);
803 /* When proper WAIT handling is implemented in the
804 * common SWD framework, this kludge can be
805 * removed. However, this might lead to minor
806 * performance degradation as the adapter wouldn't be
807 * able to automatically retry anything (because ARM
808 * has forgotten to implement sticky error flags
809 * clearing). See also comments regarding
810 * cmsis_dap_cmd_dap_tfer_configure() and
811 * cmsis_dap_cmd_dap_swd_configure() in
814 if (!(cmd & SWD_CMD_RNW) &&
815 !(cmd & SWD_CMD_APNDP) &&
816 (cmd & SWD_CMD_A32) >> 1 == DP_CTRL_STAT &&
817 (data & CORUNDETECT)) {
818 LOG_DEBUG("refusing to enable sticky overrun detection");
819 data &= ~CORUNDETECT;
822 command[idx++] = (cmd >> 1) & 0x0f;
823 if (!(cmd & SWD_CMD_RNW)) {
824 h_u32_to_le(&command[idx], data);
829 int retval = dap->backend->write(dap, idx, USB_TIMEOUT);
831 queued_retval = retval;
834 queued_retval = ERROR_OK;
837 pending_fifo_put_idx = (pending_fifo_put_idx + 1) % dap->packet_count;
838 pending_fifo_block_count++;
839 if (pending_fifo_block_count > dap->packet_count)
840 LOG_ERROR("too much pending writes %d", pending_fifo_block_count);
845 block->transfer_count = 0;
848 static void cmsis_dap_swd_read_process(struct cmsis_dap *dap, int timeout_ms)
850 struct pending_request_block *block = &pending_fifo[pending_fifo_get_idx];
852 if (pending_fifo_block_count == 0)
853 LOG_ERROR("no pending write");
856 int retval = dap->backend->read(dap, timeout_ms);
857 if (retval == ERROR_TIMEOUT_REACHED && timeout_ms < USB_TIMEOUT)
861 LOG_DEBUG("error reading data");
862 queued_retval = ERROR_FAIL;
866 uint8_t *resp = dap->response;
867 if (resp[0] != CMD_DAP_TFER) {
868 LOG_ERROR("CMSIS-DAP command mismatch. Expected 0x%x received 0x%" PRIx8,
869 CMD_DAP_TFER, resp[0]);
870 queued_retval = ERROR_FAIL;
874 uint8_t transfer_count = resp[1];
875 uint8_t ack = resp[2] & 0x07;
876 if (resp[2] & 0x08) {
877 LOG_DEBUG("CMSIS-DAP Protocol Error @ %d (wrong parity)", transfer_count);
878 queued_retval = ERROR_FAIL;
881 if (ack != SWD_ACK_OK) {
882 LOG_DEBUG("SWD ack not OK @ %d %s", transfer_count,
883 ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
884 queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
885 /* TODO: use results of transfers completed before the error occurred? */
889 if (block->transfer_count != transfer_count)
890 LOG_ERROR("CMSIS-DAP transfer count mismatch: expected %d, got %d",
891 block->transfer_count, transfer_count);
893 LOG_DEBUG_IO("Received results of %d queued transactions FIFO index %d",
894 transfer_count, pending_fifo_get_idx);
896 for (int i = 0; i < transfer_count; i++) {
897 struct pending_transfer_result *transfer = &(block->transfers[i]);
898 if (transfer->cmd & SWD_CMD_RNW) {
899 static uint32_t last_read;
900 uint32_t data = le_to_h_u32(&resp[idx]);
904 LOG_DEBUG_IO("Read result: %"PRIx32, data);
906 /* Imitate posted AP reads */
907 if ((transfer->cmd & SWD_CMD_APNDP) ||
908 ((transfer->cmd & SWD_CMD_A32) >> 1 == DP_RDBUFF)) {
913 if (transfer->buffer)
914 *(uint32_t *)(transfer->buffer) = tmp;
919 block->transfer_count = 0;
920 pending_fifo_get_idx = (pending_fifo_get_idx + 1) % dap->packet_count;
921 pending_fifo_block_count--;
924 static int cmsis_dap_swd_run_queue(void)
926 if (pending_fifo_block_count)
927 cmsis_dap_swd_read_process(cmsis_dap_handle, 0);
929 cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
931 while (pending_fifo_block_count)
932 cmsis_dap_swd_read_process(cmsis_dap_handle, USB_TIMEOUT);
934 pending_fifo_put_idx = 0;
935 pending_fifo_get_idx = 0;
937 int retval = queued_retval;
938 queued_retval = ERROR_OK;
943 static void cmsis_dap_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data)
945 bool targetsel_cmd = swd_cmd(false, false, DP_TARGETSEL) == cmd;
947 if (pending_fifo[pending_fifo_put_idx].transfer_count == pending_queue_len
949 if (pending_fifo_block_count)
950 cmsis_dap_swd_read_process(cmsis_dap_handle, 0);
952 /* Not enough room in the queue. Run the queue. */
953 cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
955 if (pending_fifo_block_count >= cmsis_dap_handle->packet_count)
956 cmsis_dap_swd_read_process(cmsis_dap_handle, USB_TIMEOUT);
959 if (queued_retval != ERROR_OK)
963 cmsis_dap_metacmd_targetsel(data);
967 struct pending_request_block *block = &pending_fifo[pending_fifo_put_idx];
968 struct pending_transfer_result *transfer = &(block->transfers[block->transfer_count]);
969 transfer->data = data;
971 if (cmd & SWD_CMD_RNW) {
972 /* Queue a read transaction */
973 transfer->buffer = dst;
975 block->transfer_count++;
978 static void cmsis_dap_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
980 assert(!(cmd & SWD_CMD_RNW));
981 cmsis_dap_swd_queue_cmd(cmd, NULL, value);
984 static void cmsis_dap_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
986 assert(cmd & SWD_CMD_RNW);
987 cmsis_dap_swd_queue_cmd(cmd, value, 0);
990 static int cmsis_dap_get_serial_info(void)
994 int retval = cmsis_dap_cmd_dap_info(INFO_ID_SERNUM, &data);
995 if (retval != ERROR_OK)
998 if (data[0]) /* strlen */
999 LOG_INFO("CMSIS-DAP: Serial# = %s", &data[1]);
1004 static int cmsis_dap_get_version_info(void)
1008 /* INFO_ID_FW_VER - string */
1009 int retval = cmsis_dap_cmd_dap_info(INFO_ID_FW_VER, &data);
1010 if (retval != ERROR_OK)
1013 if (data[0]) /* strlen */
1014 LOG_INFO("CMSIS-DAP: FW Version = %s", &data[1]);
1019 static int cmsis_dap_get_caps_info(void)
1023 /* INFO_ID_CAPS - byte */
1024 int retval = cmsis_dap_cmd_dap_info(INFO_ID_CAPS, &data);
1025 if (retval != ERROR_OK)
1028 if (data[0] == 1 || data[0] == 2) {
1029 uint16_t caps = data[1];
1031 caps |= (uint16_t)data[2] << 8;
1033 cmsis_dap_handle->caps = caps;
1035 for (int i = 0; i < INFO_CAPS__NUM_CAPS; ++i) {
1037 LOG_INFO("CMSIS-DAP: %s", info_caps_str[i]);
1044 static int cmsis_dap_get_swo_buf_sz(uint32_t *swo_buf_sz)
1048 /* INFO_ID_SWO_BUF_SZ - word */
1049 int retval = cmsis_dap_cmd_dap_info(INFO_ID_SWO_BUF_SZ, &data);
1050 if (retval != ERROR_OK)
1056 *swo_buf_sz = le_to_h_u32(&data[1]);
1058 LOG_INFO("CMSIS-DAP: SWO Trace Buffer Size = %u bytes", *swo_buf_sz);
1063 static int cmsis_dap_get_status(void)
1067 int retval = cmsis_dap_cmd_dap_swj_pins(0, 0, 0, &d);
1069 if (retval == ERROR_OK) {
1070 LOG_INFO("SWCLK/TCK = %d SWDIO/TMS = %d TDI = %d TDO = %d nTRST = %d nRESET = %d",
1071 (d & SWJ_PIN_TCK) ? 1 : 0,
1072 (d & SWJ_PIN_TMS) ? 1 : 0,
1073 (d & SWJ_PIN_TDI) ? 1 : 0,
1074 (d & SWJ_PIN_TDO) ? 1 : 0,
1075 (d & SWJ_PIN_TRST) ? 1 : 0,
1076 (d & SWJ_PIN_SRST) ? 1 : 0);
1082 static int cmsis_dap_swd_switch_seq(enum swd_special_seq seq)
1088 if ((output_pins & (SWJ_PIN_SRST | SWJ_PIN_TRST)) == (SWJ_PIN_SRST | SWJ_PIN_TRST)) {
1089 /* Following workaround deasserts reset on most adapters.
1090 * Do not reconnect if a reset line is active!
1091 * Reconnecting would break connecting under reset. */
1093 /* First disconnect before connecting, Atmel EDBG needs it for SAMD/R/L/C */
1094 cmsis_dap_cmd_dap_disconnect();
1096 /* When we are reconnecting, DAP_Connect needs to be rerun, at
1097 * least on Keil ULINK-ME */
1098 retval = cmsis_dap_cmd_dap_connect(CONNECT_SWD);
1099 if (retval != ERROR_OK)
1105 LOG_DEBUG_IO("SWD line reset");
1106 s = swd_seq_line_reset;
1107 s_len = swd_seq_line_reset_len;
1110 LOG_DEBUG("JTAG-to-SWD");
1111 s = swd_seq_jtag_to_swd;
1112 s_len = swd_seq_jtag_to_swd_len;
1114 case JTAG_TO_DORMANT:
1115 LOG_DEBUG("JTAG-to-DORMANT");
1116 s = swd_seq_jtag_to_dormant;
1117 s_len = swd_seq_jtag_to_dormant_len;
1120 LOG_DEBUG("SWD-to-JTAG");
1121 s = swd_seq_swd_to_jtag;
1122 s_len = swd_seq_swd_to_jtag_len;
1124 case SWD_TO_DORMANT:
1125 LOG_DEBUG("SWD-to-DORMANT");
1126 s = swd_seq_swd_to_dormant;
1127 s_len = swd_seq_swd_to_dormant_len;
1129 case DORMANT_TO_SWD:
1130 LOG_DEBUG("DORMANT-to-SWD");
1131 s = swd_seq_dormant_to_swd;
1132 s_len = swd_seq_dormant_to_swd_len;
1134 case DORMANT_TO_JTAG:
1135 LOG_DEBUG("DORMANT-to-JTAG");
1136 s = swd_seq_dormant_to_jtag;
1137 s_len = swd_seq_dormant_to_jtag_len;
1140 LOG_ERROR("Sequence %d not supported", seq);
1144 retval = cmsis_dap_cmd_dap_swj_sequence(s_len, s);
1145 if (retval != ERROR_OK)
1148 /* Atmel EDBG needs renew clock setting after SWJ_Sequence
1149 * otherwise default frequency is used */
1150 return cmsis_dap_cmd_dap_swj_clock(adapter_get_speed_khz());
1153 static int cmsis_dap_swd_open(void)
1155 if (!(cmsis_dap_handle->caps & INFO_CAPS_SWD)) {
1156 LOG_ERROR("CMSIS-DAP: SWD not supported");
1157 return ERROR_JTAG_DEVICE_ERROR;
1160 int retval = cmsis_dap_cmd_dap_connect(CONNECT_SWD);
1161 if (retval != ERROR_OK)
1164 /* Add more setup here.??... */
1166 LOG_INFO("CMSIS-DAP: Interface Initialised (SWD)");
1170 static int cmsis_dap_init(void)
1174 int retval = cmsis_dap_open();
1175 if (retval != ERROR_OK)
1178 cmsis_dap_flush_read(cmsis_dap_handle);
1180 retval = cmsis_dap_get_caps_info();
1181 if (retval != ERROR_OK)
1184 retval = cmsis_dap_get_version_info();
1185 if (retval != ERROR_OK)
1188 retval = cmsis_dap_get_serial_info();
1189 if (retval != ERROR_OK)
1193 retval = cmsis_dap_swd_open();
1194 if (retval != ERROR_OK)
1197 /* Connect in JTAG mode */
1198 if (!(cmsis_dap_handle->caps & INFO_CAPS_JTAG)) {
1199 LOG_ERROR("CMSIS-DAP: JTAG not supported");
1200 return ERROR_JTAG_DEVICE_ERROR;
1203 retval = cmsis_dap_cmd_dap_connect(CONNECT_JTAG);
1204 if (retval != ERROR_OK)
1207 LOG_INFO("CMSIS-DAP: Interface Initialised (JTAG)");
1210 /* Be conservative and suppress submitting multiple HID requests
1211 * until we get packet count info from the adaptor */
1212 cmsis_dap_handle->packet_count = 1;
1213 pending_queue_len = 12;
1215 /* INFO_ID_PKT_SZ - short */
1216 retval = cmsis_dap_cmd_dap_info(INFO_ID_PKT_SZ, &data);
1217 if (retval != ERROR_OK)
1220 if (data[0] == 2) { /* short */
1221 uint16_t pkt_sz = data[1] + (data[2] << 8);
1222 if (pkt_sz != cmsis_dap_handle->packet_size) {
1224 /* 4 bytes of command header + 5 bytes per register
1225 * write. For bulk read sequences just 4 bytes are
1226 * needed per transfer, so this is suboptimal. */
1227 pending_queue_len = (pkt_sz - 4) / 5;
1229 free(cmsis_dap_handle->packet_buffer);
1230 retval = cmsis_dap_handle->backend->packet_buffer_alloc(cmsis_dap_handle, pkt_sz);
1231 if (retval != ERROR_OK)
1234 LOG_DEBUG("CMSIS-DAP: Packet Size = %" PRIu16, pkt_sz);
1238 /* INFO_ID_PKT_CNT - byte */
1239 retval = cmsis_dap_cmd_dap_info(INFO_ID_PKT_CNT, &data);
1240 if (retval != ERROR_OK)
1243 if (data[0] == 1) { /* byte */
1244 int pkt_cnt = data[1];
1246 cmsis_dap_handle->packet_count = MIN(MAX_PENDING_REQUESTS, pkt_cnt);
1248 LOG_DEBUG("CMSIS-DAP: Packet Count = %d", pkt_cnt);
1251 LOG_DEBUG("Allocating FIFO for %d pending packets", cmsis_dap_handle->packet_count);
1252 for (int i = 0; i < cmsis_dap_handle->packet_count; i++) {
1253 pending_fifo[i].transfers = malloc(pending_queue_len * sizeof(struct pending_transfer_result));
1254 if (!pending_fifo[i].transfers) {
1255 LOG_ERROR("Unable to allocate memory for CMSIS-DAP queue");
1256 retval = ERROR_FAIL;
1261 /* Intentionally not checked for error, just logs an info message
1262 * not vital for further debugging */
1263 (void)cmsis_dap_get_status();
1265 /* Now try to connect to the target
1266 * TODO: This is all SWD only @ present */
1267 retval = cmsis_dap_cmd_dap_swj_clock(adapter_get_speed_khz());
1268 if (retval != ERROR_OK)
1271 /* Ask CMSIS-DAP to automatically retry on receiving WAIT for
1272 * up to 64 times. This must be changed to 0 if sticky
1273 * overrun detection is enabled. */
1274 retval = cmsis_dap_cmd_dap_tfer_configure(0, 64, 0);
1275 if (retval != ERROR_OK)
1279 /* Data Phase (bit 2) must be set to 1 if sticky overrun
1280 * detection is enabled */
1281 retval = cmsis_dap_cmd_dap_swd_configure(0); /* 1 TRN, no Data Phase */
1282 if (retval != ERROR_OK)
1286 /* Intentionally not checked for error, debugging will work
1288 (void)cmsis_dap_cmd_dap_led(LED_ID_CONNECT, LED_ON);
1289 (void)cmsis_dap_cmd_dap_led(LED_ID_RUN, LED_ON);
1291 /* support connecting with srst asserted */
1292 enum reset_types jtag_reset_config = jtag_get_reset_config();
1294 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
1295 if (jtag_reset_config & RESET_SRST_NO_GATING) {
1296 retval = cmsis_dap_cmd_dap_swj_pins(0, SWJ_PIN_SRST, 0, NULL);
1297 if (retval != ERROR_OK)
1299 LOG_INFO("Connecting under reset");
1302 LOG_INFO("CMSIS-DAP: Interface ready");
1310 static int cmsis_dap_swd_init(void)
1316 static int cmsis_dap_quit(void)
1318 cmsis_dap_cmd_dap_disconnect();
1321 cmsis_dap_cmd_dap_led(LED_ID_RUN, LED_OFF);
1322 cmsis_dap_cmd_dap_led(LED_ID_CONNECT, LED_OFF);
1324 cmsis_dap_close(cmsis_dap_handle);
1329 static int cmsis_dap_reset(int trst, int srst)
1331 /* Set both TRST and SRST even if they're not enabled as
1332 * there's no way to tristate them */
1336 output_pins |= SWJ_PIN_SRST;
1338 output_pins |= SWJ_PIN_TRST;
1340 int retval = cmsis_dap_cmd_dap_swj_pins(output_pins,
1341 SWJ_PIN_TRST | SWJ_PIN_SRST, 0, NULL);
1342 if (retval != ERROR_OK)
1343 LOG_ERROR("CMSIS-DAP: Interface reset failed");
1347 static void cmsis_dap_execute_sleep(struct jtag_command *cmd)
1350 int retval = cmsis_dap_cmd_dap_delay(cmd->cmd.sleep->us);
1351 if (retval != ERROR_OK)
1353 jtag_sleep(cmd->cmd.sleep->us);
1356 /* Set TMS high for five TCK clocks, to move the TAP to the Test-Logic-Reset state */
1357 static int cmsis_dap_execute_tlr_reset(struct jtag_command *cmd)
1359 LOG_INFO("cmsis-dap JTAG TLR_RESET");
1362 int retval = cmsis_dap_cmd_dap_swj_sequence(8, &seq);
1363 if (retval == ERROR_OK)
1364 tap_set_state(TAP_RESET);
1368 /* Set new end state */
1369 static void cmsis_dap_end_state(tap_state_t state)
1371 if (tap_is_state_stable(state))
1372 tap_set_end_state(state);
1374 LOG_ERROR("BUG: %i is not a valid end state", state);
1379 #ifdef SPRINT_BINARY
1380 static void sprint_binary(char *s, const uint8_t *buf, int offset, int len)
1386 buf = { 0x18 } len=5 should result in: 11000
1387 buf = { 0xff 0x18 } len=13 should result in: 11111111 11000
1388 buf = { 0xc0 0x18 } offset=3 len=10 should result in: 11000 11000
1389 i=3 there means i/8 = 0 so c = 0xFF, and
1391 for (int i = offset; i < offset + len; ++i) {
1392 uint8_t c = buf[i / 8], mask = 1 << (i % 8);
1393 if ((i != offset) && !(i % 8))
1395 *s++ = (c & mask) ? '1' : '0';
1401 #ifdef CMSIS_DAP_JTAG_DEBUG
1402 static void debug_parse_cmsis_buf(const uint8_t *cmd, int cmdlen)
1404 /* cmd is a usb packet to go to the cmsis-dap interface */
1405 printf("cmsis-dap buffer (%d b): ", cmdlen);
1406 for (int i = 0; i < cmdlen; ++i)
1407 printf(" %02x", cmd[i]);
1410 case CMD_DAP_JTAG_SEQ: {
1411 printf("cmsis-dap jtag sequence command %02x (n=%d)\n", cmd[1], cmd[2]);
1413 * #2 = number of sequences
1414 * #3 = sequence info 1
1415 * #4...4+n_bytes-1 = sequence 1
1416 * #4+n_bytes = sequence info 2
1417 * #5+n_bytes = sequence 2 (single bit)
1420 for (int seq = 0; seq < cmd[2]; ++seq) {
1421 uint8_t info = cmd[pos++];
1422 int len = info & DAP_JTAG_SEQ_TCK;
1425 printf(" sequence %d starting %d: info %02x (len=%d tms=%d read_tdo=%d): ",
1426 seq, pos, info, len, info & DAP_JTAG_SEQ_TMS, info & DAP_JTAG_SEQ_TDO);
1427 for (int i = 0; i < DIV_ROUND_UP(len, 8); ++i)
1428 printf(" %02x", cmd[pos+i]);
1429 pos += DIV_ROUND_UP(len, 8);
1432 if (pos != cmdlen) {
1433 printf("BUFFER LENGTH MISMATCH looks like %d but %d specified", pos, cmdlen);
1440 LOG_DEBUG("unknown cmsis-dap command %02x", cmd[1]);
1446 static void cmsis_dap_flush(void)
1448 if (!queued_seq_count)
1451 LOG_DEBUG_IO("Flushing %d queued sequences (%d bytes) with %d pending scan results to capture",
1452 queued_seq_count, queued_seq_buf_end, pending_scan_result_count);
1454 /* prepare CMSIS-DAP packet */
1455 uint8_t *command = cmsis_dap_handle->command;
1456 command[0] = CMD_DAP_JTAG_SEQ;
1457 command[1] = queued_seq_count;
1458 memcpy(&command[2], queued_seq_buf, queued_seq_buf_end);
1460 #ifdef CMSIS_DAP_JTAG_DEBUG
1461 debug_parse_cmsis_buf(command, queued_seq_buf_end + 2);
1464 /* send command to USB device */
1465 int retval = cmsis_dap_xfer(cmsis_dap_handle, queued_seq_buf_end + 2);
1467 uint8_t *resp = cmsis_dap_handle->response;
1468 if (retval != ERROR_OK || resp[1] != DAP_OK) {
1469 LOG_ERROR("CMSIS-DAP command CMD_DAP_JTAG_SEQ failed.");
1473 #ifdef CMSIS_DAP_JTAG_DEBUG
1474 LOG_DEBUG_IO("USB response buf:");
1475 for (int c = 0; c < queued_seq_buf_end + 3; ++c)
1476 printf("%02X ", resp[c]);
1480 /* copy scan results into client buffers */
1481 for (int i = 0; i < pending_scan_result_count; ++i) {
1482 struct pending_scan_result *scan = &pending_scan_results[i];
1483 LOG_DEBUG_IO("Copying pending_scan_result %d/%d: %d bits from byte %d -> buffer + %d bits",
1484 i, pending_scan_result_count, scan->length, scan->first + 2, scan->buffer_offset);
1485 #ifdef CMSIS_DAP_JTAG_DEBUG
1486 for (uint32_t b = 0; b < DIV_ROUND_UP(scan->length, 8); ++b)
1487 printf("%02X ", resp[2+scan->first+b]);
1490 bit_copy(scan->buffer, scan->buffer_offset, &resp[2 + scan->first], 0, scan->length);
1494 queued_seq_count = 0;
1495 queued_seq_buf_end = 0;
1496 queued_seq_tdo_ptr = 0;
1497 pending_scan_result_count = 0;
1500 /* queue a sequence of bits to clock out TDI / in TDO, executing if the buffer is full.
1502 * sequence=NULL means clock out zeros on TDI
1503 * tdo_buffer=NULL means don't capture TDO
1505 static void cmsis_dap_add_jtag_sequence(int s_len, const uint8_t *sequence, int s_offset,
1506 bool tms, uint8_t *tdo_buffer, int tdo_buffer_offset)
1508 LOG_DEBUG_IO("[at %d] %d bits, tms %s, seq offset %d, tdo buf %p, tdo offset %d",
1510 s_len, tms ? "HIGH" : "LOW", s_offset, tdo_buffer, tdo_buffer_offset);
1516 LOG_DEBUG_IO("START JTAG SEQ SPLIT");
1517 for (int offset = 0; offset < s_len; offset += 64) {
1518 int len = s_len - offset;
1521 LOG_DEBUG_IO("Splitting long jtag sequence: %d-bit chunk starting at offset %d", len, offset);
1522 cmsis_dap_add_jtag_sequence(
1528 !tdo_buffer ? 0 : (tdo_buffer_offset + offset)
1531 LOG_DEBUG_IO("END JTAG SEQ SPLIT");
1535 int cmd_len = 1 + DIV_ROUND_UP(s_len, 8);
1536 if (queued_seq_count >= 255 || queued_seq_buf_end + cmd_len > QUEUED_SEQ_BUF_LEN)
1537 /* empty out the buffer */
1543 queued_seq_buf[queued_seq_buf_end] =
1544 (tms ? DAP_JTAG_SEQ_TMS : 0) |
1545 (tdo_buffer ? DAP_JTAG_SEQ_TDO : 0) |
1546 (s_len == 64 ? 0 : s_len);
1549 bit_copy(&queued_seq_buf[queued_seq_buf_end + 1], 0, sequence, s_offset, s_len);
1551 memset(&queued_seq_buf[queued_seq_buf_end + 1], 0, DIV_ROUND_UP(s_len, 8));
1553 queued_seq_buf_end += cmd_len;
1556 struct pending_scan_result *scan = &pending_scan_results[pending_scan_result_count++];
1557 scan->first = queued_seq_tdo_ptr;
1558 queued_seq_tdo_ptr += DIV_ROUND_UP(s_len, 8);
1559 scan->length = s_len;
1560 scan->buffer = tdo_buffer;
1561 scan->buffer_offset = tdo_buffer_offset;
1565 /* queue a sequence of bits to clock out TMS, executing if the buffer is full */
1566 static void cmsis_dap_add_tms_sequence(const uint8_t *sequence, int s_len)
1568 LOG_DEBUG_IO("%d bits: %02X", s_len, *sequence);
1569 /* we use a series of CMD_DAP_JTAG_SEQ commands to toggle TMS,
1570 because even though it seems ridiculously inefficient, it
1571 allows us to combine TMS and scan sequences into the same
1573 /* TODO: combine runs of the same tms value */
1574 for (int i = 0; i < s_len; ++i) {
1575 bool bit = (sequence[i / 8] & (1 << (i % 8))) != 0;
1576 cmsis_dap_add_jtag_sequence(1, NULL, 0, bit, NULL, 0);
1580 /* Move to the end state by queuing a sequence to clock into TMS */
1581 static void cmsis_dap_state_move(void)
1583 uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1584 uint8_t tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1586 LOG_DEBUG_IO("state move from %s to %s: %d clocks, %02X on tms",
1587 tap_state_name(tap_get_state()), tap_state_name(tap_get_end_state()),
1588 tms_scan_bits, tms_scan);
1589 cmsis_dap_add_tms_sequence(&tms_scan, tms_scan_bits);
1591 tap_set_state(tap_get_end_state());
1595 /* Execute a JTAG scan operation by queueing TMS and TDI/TDO sequences */
1596 static void cmsis_dap_execute_scan(struct jtag_command *cmd)
1598 LOG_DEBUG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
1599 jtag_scan_type(cmd->cmd.scan));
1601 /* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
1602 while (cmd->cmd.scan->num_fields > 0
1603 && cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
1604 cmd->cmd.scan->num_fields--;
1605 LOG_DEBUG("discarding trailing empty field");
1608 if (cmd->cmd.scan->num_fields == 0) {
1609 LOG_DEBUG("empty scan, doing nothing");
1613 if (cmd->cmd.scan->ir_scan) {
1614 if (tap_get_state() != TAP_IRSHIFT) {
1615 cmsis_dap_end_state(TAP_IRSHIFT);
1616 cmsis_dap_state_move();
1619 if (tap_get_state() != TAP_DRSHIFT) {
1620 cmsis_dap_end_state(TAP_DRSHIFT);
1621 cmsis_dap_state_move();
1625 cmsis_dap_end_state(cmd->cmd.scan->end_state);
1627 struct scan_field *field = cmd->cmd.scan->fields;
1628 unsigned scan_size = 0;
1630 for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
1631 scan_size += field->num_bits;
1632 LOG_DEBUG_IO("%s%s field %d/%d %d bits",
1633 field->in_value ? "in" : "",
1634 field->out_value ? "out" : "",
1636 cmd->cmd.scan->num_fields,
1639 if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
1640 LOG_DEBUG_IO("Last field and have to move out of SHIFT state");
1641 /* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
1642 * movement. This last field can't have length zero, it was checked above. */
1643 cmsis_dap_add_jtag_sequence(
1644 field->num_bits - 1, /* number of bits to clock */
1645 field->out_value, /* output sequence */
1646 0, /* output offset */
1647 false, /* TMS low */
1651 /* Clock the last bit out, with TMS high */
1652 uint8_t last_bit = 0;
1653 if (field->out_value)
1654 bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
1655 cmsis_dap_add_jtag_sequence(
1661 field->num_bits - 1);
1662 tap_set_state(tap_state_transition(tap_get_state(), 1));
1664 /* Now clock one more cycle, with TMS low, to get us into a PAUSE state */
1665 cmsis_dap_add_jtag_sequence(
1672 tap_set_state(tap_state_transition(tap_get_state(), 0));
1674 LOG_DEBUG_IO("Internal field, staying in SHIFT state afterwards");
1675 /* Clocking part of a sequence into DR or IR with TMS=0,
1676 leaving TMS=0 at the end so we can continue later */
1677 cmsis_dap_add_jtag_sequence(
1687 if (tap_get_state() != tap_get_end_state()) {
1688 cmsis_dap_end_state(tap_get_end_state());
1689 cmsis_dap_state_move();
1692 LOG_DEBUG_IO("%s scan, %i bits, end in %s",
1693 (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1694 tap_state_name(tap_get_end_state()));
1697 static void cmsis_dap_pathmove(int num_states, tap_state_t *path)
1699 uint8_t tms0 = 0x00;
1700 uint8_t tms1 = 0xff;
1702 for (int i = 0; i < num_states; i++) {
1703 if (path[i] == tap_state_transition(tap_get_state(), false))
1704 cmsis_dap_add_tms_sequence(&tms0, 1);
1705 else if (path[i] == tap_state_transition(tap_get_state(), true))
1706 cmsis_dap_add_tms_sequence(&tms1, 1);
1708 LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
1709 tap_state_name(tap_get_state()), tap_state_name(path[i]));
1713 tap_set_state(path[i]);
1716 cmsis_dap_end_state(tap_get_state());
1719 static void cmsis_dap_execute_pathmove(struct jtag_command *cmd)
1721 LOG_DEBUG_IO("pathmove: %i states, end in %i",
1722 cmd->cmd.pathmove->num_states,
1723 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
1725 cmsis_dap_pathmove(cmd->cmd.pathmove->num_states, cmd->cmd.pathmove->path);
1728 static void cmsis_dap_stableclocks(int num_cycles)
1730 uint8_t tms = tap_get_state() == TAP_RESET;
1731 /* TODO: Perform optimizations? */
1732 /* Execute num_cycles. */
1733 for (int i = 0; i < num_cycles; i++)
1734 cmsis_dap_add_tms_sequence(&tms, 1);
1737 static void cmsis_dap_runtest(int num_cycles)
1739 tap_state_t saved_end_state = tap_get_end_state();
1741 /* Only do a state_move when we're not already in IDLE. */
1742 if (tap_get_state() != TAP_IDLE) {
1743 cmsis_dap_end_state(TAP_IDLE);
1744 cmsis_dap_state_move();
1746 cmsis_dap_stableclocks(num_cycles);
1748 /* Finish in end_state. */
1749 cmsis_dap_end_state(saved_end_state);
1751 if (tap_get_state() != tap_get_end_state())
1752 cmsis_dap_state_move();
1755 static void cmsis_dap_execute_runtest(struct jtag_command *cmd)
1757 LOG_DEBUG_IO("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles,
1758 cmd->cmd.runtest->end_state);
1760 cmsis_dap_end_state(cmd->cmd.runtest->end_state);
1761 cmsis_dap_runtest(cmd->cmd.runtest->num_cycles);
1764 static void cmsis_dap_execute_stableclocks(struct jtag_command *cmd)
1766 LOG_DEBUG_IO("stableclocks %i cycles", cmd->cmd.runtest->num_cycles);
1767 cmsis_dap_stableclocks(cmd->cmd.runtest->num_cycles);
1770 static void cmsis_dap_execute_tms(struct jtag_command *cmd)
1772 LOG_DEBUG_IO("TMS: %d bits", cmd->cmd.tms->num_bits);
1773 cmsis_dap_cmd_dap_swj_sequence(cmd->cmd.tms->num_bits, cmd->cmd.tms->bits);
1776 /* TODO: Is there need to call cmsis_dap_flush() for the JTAG_PATHMOVE,
1777 * JTAG_RUNTEST, JTAG_STABLECLOCKS? */
1778 static void cmsis_dap_execute_command(struct jtag_command *cmd)
1780 switch (cmd->type) {
1783 cmsis_dap_execute_sleep(cmd);
1785 case JTAG_TLR_RESET:
1787 cmsis_dap_execute_tlr_reset(cmd);
1790 cmsis_dap_execute_scan(cmd);
1793 cmsis_dap_execute_pathmove(cmd);
1796 cmsis_dap_execute_runtest(cmd);
1798 case JTAG_STABLECLOCKS:
1799 cmsis_dap_execute_stableclocks(cmd);
1802 cmsis_dap_execute_tms(cmd);
1805 LOG_ERROR("BUG: unknown JTAG command type 0x%X encountered", cmd->type);
1810 static int cmsis_dap_execute_queue(void)
1812 struct jtag_command *cmd = jtag_command_queue;
1815 cmsis_dap_execute_command(cmd);
1824 static int cmsis_dap_speed(int speed)
1827 LOG_ERROR("RTCK not supported. Set nonzero \"adapter speed\".");
1828 return ERROR_JTAG_NOT_IMPLEMENTED;
1831 return cmsis_dap_cmd_dap_swj_clock(speed);
1834 static int cmsis_dap_speed_div(int speed, int *khz)
1840 static int cmsis_dap_khz(int khz, int *jtag_speed)
1846 static bool calculate_swo_prescaler(unsigned int traceclkin_freq,
1847 uint32_t trace_freq, uint16_t *prescaler)
1849 unsigned int presc = (traceclkin_freq + trace_freq / 2) / trace_freq;
1850 if (presc == 0 || presc > TPIU_ACPR_MAX_SWOSCALER + 1)
1853 /* Probe's UART speed must be within 3% of the TPIU's SWO baud rate. */
1854 unsigned int max_deviation = (traceclkin_freq * 3) / 100;
1855 if (presc * trace_freq < traceclkin_freq - max_deviation ||
1856 presc * trace_freq > traceclkin_freq + max_deviation)
1865 * @see adapter_driver::config_trace
1867 static int cmsis_dap_config_trace(
1869 enum tpiu_pin_protocol pin_protocol,
1871 unsigned int *swo_freq,
1872 unsigned int traceclkin_hz,
1873 uint16_t *swo_prescaler)
1877 if (!trace_enabled) {
1878 if (cmsis_dap_handle->trace_enabled) {
1879 retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_STOP);
1880 if (retval != ERROR_OK) {
1881 LOG_ERROR("Failed to disable the SWO-trace.");
1885 cmsis_dap_handle->trace_enabled = false;
1886 LOG_INFO("SWO-trace disabled.");
1890 if (!(cmsis_dap_handle->caps & INFO_CAPS_SWO_UART) &&
1891 !(cmsis_dap_handle->caps & INFO_CAPS_SWO_MANCHESTER)) {
1892 LOG_ERROR("SWO-trace is not supported by the device.");
1897 if (pin_protocol == TPIU_PIN_PROTOCOL_ASYNC_UART &&
1898 (cmsis_dap_handle->caps & INFO_CAPS_SWO_UART)) {
1899 swo_mode = DAP_SWO_MODE_UART;
1900 } else if (pin_protocol == TPIU_PIN_PROTOCOL_ASYNC_MANCHESTER &&
1901 (cmsis_dap_handle->caps & INFO_CAPS_SWO_MANCHESTER)) {
1902 swo_mode = DAP_SWO_MODE_MANCHESTER;
1904 LOG_ERROR("Selected pin protocol is not supported.");
1908 if (*swo_freq == 0) {
1909 LOG_INFO("SWO-trace frequency autodetection not implemented.");
1913 retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_STOP);
1914 if (retval != ERROR_OK)
1917 cmsis_dap_handle->trace_enabled = false;
1919 retval = cmsis_dap_get_swo_buf_sz(&cmsis_dap_handle->swo_buf_sz);
1920 if (retval != ERROR_OK)
1923 retval = cmsis_dap_cmd_dap_swo_transport(DAP_SWO_TRANSPORT_DATA);
1924 if (retval != ERROR_OK)
1927 retval = cmsis_dap_cmd_dap_swo_mode(swo_mode);
1928 if (retval != ERROR_OK)
1931 retval = cmsis_dap_cmd_dap_swo_baudrate(*swo_freq, swo_freq);
1932 if (retval != ERROR_OK)
1935 if (!calculate_swo_prescaler(traceclkin_hz, *swo_freq,
1937 LOG_ERROR("SWO frequency is not suitable. Please choose a "
1938 "different frequency or use auto-detection.");
1942 LOG_INFO("SWO frequency: %u Hz.", *swo_freq);
1943 LOG_INFO("SWO prescaler: %u.", *swo_prescaler);
1945 retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_START);
1946 if (retval != ERROR_OK)
1949 cmsis_dap_handle->trace_enabled = true;
1955 * @see adapter_driver::poll_trace
1957 static int cmsis_dap_poll_trace(uint8_t *buf, size_t *size)
1959 uint8_t trace_status;
1962 if (!cmsis_dap_handle->trace_enabled) {
1967 int retval = cmsis_dap_cmd_dap_swo_status(&trace_status, &trace_count);
1968 if (retval != ERROR_OK)
1970 if ((trace_status & DAP_SWO_STATUS_CAPTURE_MASK) != DAP_SWO_STATUS_CAPTURE_ACTIVE)
1973 *size = trace_count < *size ? trace_count : *size;
1974 size_t read_so_far = 0;
1977 uint32_t packet_size = cmsis_dap_handle->packet_size - 4 /*data-reply*/;
1978 uint32_t remaining = *size - read_so_far;
1979 if (remaining < packet_size)
1980 packet_size = remaining;
1981 retval = cmsis_dap_cmd_dap_swo_data(
1986 if (retval != ERROR_OK)
1988 if ((trace_status & DAP_SWO_STATUS_CAPTURE_MASK) != DAP_SWO_STATUS_CAPTURE_ACTIVE)
1992 } while (read_so_far < *size);
1997 COMMAND_HANDLER(cmsis_dap_handle_info_command)
1999 if (cmsis_dap_get_version_info() == ERROR_OK)
2000 cmsis_dap_get_status();
2005 COMMAND_HANDLER(cmsis_dap_handle_cmd_command)
2007 uint8_t *command = cmsis_dap_handle->command;
2009 for (unsigned i = 0; i < CMD_ARGC; i++)
2010 COMMAND_PARSE_NUMBER(u8, CMD_ARGV[i], command[i]);
2012 int retval = cmsis_dap_xfer(cmsis_dap_handle, CMD_ARGC);
2014 if (retval != ERROR_OK) {
2015 LOG_ERROR("CMSIS-DAP command failed.");
2016 return ERROR_JTAG_DEVICE_ERROR;
2019 uint8_t *resp = cmsis_dap_handle->response;
2020 LOG_INFO("Returned data %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8,
2021 resp[1], resp[2], resp[3], resp[4]);
2026 COMMAND_HANDLER(cmsis_dap_handle_vid_pid_command)
2028 if (CMD_ARGC > MAX_USB_IDS * 2) {
2029 LOG_WARNING("ignoring extra IDs in cmsis_dap_vid_pid "
2030 "(maximum is %d pairs)", MAX_USB_IDS);
2031 CMD_ARGC = MAX_USB_IDS * 2;
2033 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
2034 LOG_WARNING("incomplete cmsis_dap_vid_pid configuration directive");
2036 return ERROR_COMMAND_SYNTAX_ERROR;
2037 /* remove the incomplete trailing id */
2042 for (i = 0; i < CMD_ARGC; i += 2) {
2043 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], cmsis_dap_vid[i >> 1]);
2044 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], cmsis_dap_pid[i >> 1]);
2048 * Explicitly terminate, in case there are multiples instances of
2049 * cmsis_dap_vid_pid.
2051 cmsis_dap_vid[i >> 1] = cmsis_dap_pid[i >> 1] = 0;
2056 COMMAND_HANDLER(cmsis_dap_handle_backend_command)
2058 if (CMD_ARGC == 1) {
2059 if (strcmp(CMD_ARGV[0], "auto") == 0) {
2060 cmsis_dap_backend = -1; /* autoselect */
2062 for (unsigned int i = 0; i < ARRAY_SIZE(cmsis_dap_backends); i++) {
2063 if (strcasecmp(cmsis_dap_backends[i]->name, CMD_ARGV[0]) == 0) {
2064 cmsis_dap_backend = i;
2069 LOG_ERROR("invalid backend argument to cmsis_dap_backend <backend>");
2072 LOG_ERROR("expected exactly one argument to cmsis_dap_backend <backend>");
2078 static const struct command_registration cmsis_dap_subcommand_handlers[] = {
2081 .handler = &cmsis_dap_handle_info_command,
2082 .mode = COMMAND_EXEC,
2084 .help = "show cmsis-dap info",
2088 .handler = &cmsis_dap_handle_cmd_command,
2089 .mode = COMMAND_EXEC,
2091 .help = "issue cmsis-dap command",
2093 COMMAND_REGISTRATION_DONE
2097 static const struct command_registration cmsis_dap_command_handlers[] = {
2099 .name = "cmsis-dap",
2100 .mode = COMMAND_ANY,
2101 .help = "perform CMSIS-DAP management",
2103 .chain = cmsis_dap_subcommand_handlers,
2106 .name = "cmsis_dap_vid_pid",
2107 .handler = &cmsis_dap_handle_vid_pid_command,
2108 .mode = COMMAND_CONFIG,
2109 .help = "the vendor ID and product ID of the CMSIS-DAP device",
2110 .usage = "(vid pid)*",
2113 .name = "cmsis_dap_backend",
2114 .handler = &cmsis_dap_handle_backend_command,
2115 .mode = COMMAND_CONFIG,
2116 .help = "set the communication backend to use (USB bulk or HID).",
2117 .usage = "(auto | usb_bulk | hid)",
2119 #if BUILD_CMSIS_DAP_USB
2121 .name = "cmsis_dap_usb",
2122 .chain = cmsis_dap_usb_subcommand_handlers,
2123 .mode = COMMAND_ANY,
2124 .help = "USB bulk backend-specific commands",
2128 COMMAND_REGISTRATION_DONE
2131 static const struct swd_driver cmsis_dap_swd_driver = {
2132 .init = cmsis_dap_swd_init,
2133 .switch_seq = cmsis_dap_swd_switch_seq,
2134 .read_reg = cmsis_dap_swd_read_reg,
2135 .write_reg = cmsis_dap_swd_write_reg,
2136 .run = cmsis_dap_swd_run_queue,
2139 static const char * const cmsis_dap_transport[] = { "swd", "jtag", NULL };
2141 static struct jtag_interface cmsis_dap_interface = {
2142 .supported = DEBUG_CAP_TMS_SEQ,
2143 .execute_queue = cmsis_dap_execute_queue,
2146 struct adapter_driver cmsis_dap_adapter_driver = {
2147 .name = "cmsis-dap",
2148 .transports = cmsis_dap_transport,
2149 .commands = cmsis_dap_command_handlers,
2151 .init = cmsis_dap_init,
2152 .quit = cmsis_dap_quit,
2153 .reset = cmsis_dap_reset,
2154 .speed = cmsis_dap_speed,
2155 .khz = cmsis_dap_khz,
2156 .speed_div = cmsis_dap_speed_div,
2157 .config_trace = cmsis_dap_config_trace,
2158 .poll_trace = cmsis_dap_poll_trace,
2160 .jtag_ops = &cmsis_dap_interface,
2161 .swd_ops = &cmsis_dap_swd_driver,