jtag/drivers/cmsis_dap: implement canceling of pending USB requests
[openocd.git] / src / jtag / drivers / cmsis_dap.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2
3 /***************************************************************************
4 * Copyright (C) 2021 by Adrian Negreanu *
5 * groleo@gmail.com *
6 * *
7 * Copyright (C) 2018 by Mickaƫl Thomas *
8 * mickael9@gmail.com *
9 * *
10 * Copyright (C) 2016 by Maksym Hilliaka *
11 * oter@frozen-team.com *
12 * *
13 * Copyright (C) 2016 by Phillip Pearson *
14 * pp@myelin.co.nz *
15 * *
16 * Copyright (C) 2014 by Paul Fertser *
17 * fercerpav@gmail.com *
18 * *
19 * Copyright (C) 2013 by mike brown *
20 * mike@theshedworks.org.uk *
21 * *
22 * Copyright (C) 2013 by Spencer Oliver *
23 * spen@spen-soft.co.uk *
24 ***************************************************************************/
25
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include <transport/transport.h>
31 #include "helper/replacements.h"
32 #include <jtag/adapter.h>
33 #include <jtag/swd.h>
34 #include <jtag/interface.h>
35 #include <jtag/commands.h>
36 #include <jtag/tcl.h>
37 #include <target/cortex_m.h>
38
39 #include "cmsis_dap.h"
40 #include "libusb_helper.h"
41
42 static const struct cmsis_dap_backend *const cmsis_dap_backends[] = {
43 #if BUILD_CMSIS_DAP_USB == 1
44 &cmsis_dap_usb_backend,
45 #endif
46
47 #if BUILD_CMSIS_DAP_HID == 1
48 &cmsis_dap_hid_backend,
49 #endif
50 };
51
52 /* USB Config */
53
54 /* Known vid/pid pairs:
55 * VID 0xc251: Keil Software
56 * PID 0xf001: LPC-Link-II CMSIS_DAP
57 * PID 0xf002: OPEN-SDA CMSIS_DAP (Freedom Board)
58 * PID 0x2722: Keil ULINK2 CMSIS-DAP
59 * PID 0x2750: Keil ULINKplus CMSIS-DAP
60 *
61 * VID 0x0d28: mbed Software
62 * PID 0x0204: MBED CMSIS-DAP
63 */
64
65 #define MAX_USB_IDS 8
66 /* vid = pid = 0 marks the end of the list */
67 static uint16_t cmsis_dap_vid[MAX_USB_IDS + 1] = { 0 };
68 static uint16_t cmsis_dap_pid[MAX_USB_IDS + 1] = { 0 };
69 static int cmsis_dap_backend = -1;
70 static bool swd_mode;
71
72 /* CMSIS-DAP General Commands */
73 #define CMD_DAP_INFO 0x00
74 #define CMD_DAP_LED 0x01
75 #define CMD_DAP_CONNECT 0x02
76 #define CMD_DAP_DISCONNECT 0x03
77 #define CMD_DAP_WRITE_ABORT 0x08
78 #define CMD_DAP_DELAY 0x09
79 #define CMD_DAP_RESET_TARGET 0x0A
80
81 /* CMD_INFO */
82 #define INFO_ID_VENDOR 0x01 /* string */
83 #define INFO_ID_PRODUCT 0x02 /* string */
84 #define INFO_ID_SERNUM 0x03 /* string */
85 #define INFO_ID_FW_VER 0x04 /* string */
86 #define INFO_ID_TD_VEND 0x05 /* string */
87 #define INFO_ID_TD_NAME 0x06 /* string */
88 #define INFO_ID_CAPS 0xf0 /* byte */
89 #define INFO_ID_PKT_CNT 0xfe /* byte */
90 #define INFO_ID_PKT_SZ 0xff /* short */
91 #define INFO_ID_SWO_BUF_SZ 0xfd /* word */
92
93 #define INFO_CAPS_SWD BIT(0)
94 #define INFO_CAPS_JTAG BIT(1)
95 #define INFO_CAPS_SWO_UART BIT(2)
96 #define INFO_CAPS_SWO_MANCHESTER BIT(3)
97 #define INFO_CAPS_ATOMIC_CMDS BIT(4)
98 #define INFO_CAPS_TEST_DOMAIN_TIMER BIT(5)
99 #define INFO_CAPS_SWO_STREAMING_TRACE BIT(6)
100 #define INFO_CAPS_UART_PORT BIT(7)
101 #define INFO_CAPS_USB_COM_PORT BIT(8)
102 #define INFO_CAPS__NUM_CAPS 9
103
104 /* CMD_LED */
105 #define LED_ID_CONNECT 0x00
106 #define LED_ID_RUN 0x01
107
108 #define LED_OFF 0x00
109 #define LED_ON 0x01
110
111 /* CMD_CONNECT */
112 #define CONNECT_DEFAULT 0x00
113 #define CONNECT_SWD 0x01
114 #define CONNECT_JTAG 0x02
115
116 /* CMSIS-DAP Common SWD/JTAG Commands */
117 #define CMD_DAP_DELAY 0x09
118 #define CMD_DAP_SWJ_PINS 0x10
119 #define CMD_DAP_SWJ_CLOCK 0x11
120 #define CMD_DAP_SWJ_SEQ 0x12
121
122 /*
123 * PINS
124 * Bit 0: SWCLK/TCK
125 * Bit 1: SWDIO/TMS
126 * Bit 2: TDI
127 * Bit 3: TDO
128 * Bit 5: nTRST
129 * Bit 7: nRESET
130 */
131
132 #define SWJ_PIN_TCK (1<<0)
133 #define SWJ_PIN_TMS (1<<1)
134 #define SWJ_PIN_TDI (1<<2)
135 #define SWJ_PIN_TDO (1<<3)
136 #define SWJ_PIN_TRST (1<<5)
137 #define SWJ_PIN_SRST (1<<7)
138
139 /* CMSIS-DAP SWD Commands */
140 #define CMD_DAP_SWD_CONFIGURE 0x13
141 #define CMD_DAP_SWD_SEQUENCE 0x1D
142
143 /* CMSIS-DAP JTAG Commands */
144 #define CMD_DAP_JTAG_SEQ 0x14
145 #define CMD_DAP_JTAG_CONFIGURE 0x15
146 #define CMD_DAP_JTAG_IDCODE 0x16
147
148 /* CMSIS-DAP JTAG sequence info masks */
149 /* Number of bits to clock through (0 means 64) */
150 #define DAP_JTAG_SEQ_TCK 0x3F
151 /* TMS will be set during the sequence if this bit is set */
152 #define DAP_JTAG_SEQ_TMS 0x40
153 /* TDO output will be captured if this bit is set */
154 #define DAP_JTAG_SEQ_TDO 0x80
155
156
157 /* CMSIS-DAP Transfer Commands */
158 #define CMD_DAP_TFER_CONFIGURE 0x04
159 #define CMD_DAP_TFER 0x05
160 #define CMD_DAP_TFER_BLOCK 0x06
161 #define CMD_DAP_TFER_ABORT 0x07
162
163 /* DAP_TransferBlock increases the sum of command/response sizes
164 * (due to 16-bit Transfer Count) if used in a small packet.
165 * Prevent using it until we have at least r/w operations. */
166 #define CMD_DAP_TFER_BLOCK_MIN_OPS 4
167
168 /* DAP Status Code */
169 #define DAP_OK 0
170 #define DAP_ERROR 0xFF
171
172 /* CMSIS-DAP SWO Commands */
173 #define CMD_DAP_SWO_TRANSPORT 0x17
174 #define CMD_DAP_SWO_MODE 0x18
175 #define CMD_DAP_SWO_BAUDRATE 0x19
176 #define CMD_DAP_SWO_CONTROL 0x1A
177 #define CMD_DAP_SWO_STATUS 0x1B
178 #define CMD_DAP_SWO_DATA 0x1C
179 #define CMD_DAP_SWO_EX_STATUS 0x1E
180
181 /* SWO transport mode for reading trace data */
182 #define DAP_SWO_TRANSPORT_NONE 0
183 #define DAP_SWO_TRANSPORT_DATA 1
184 #define DAP_SWO_TRANSPORT_WINUSB 2
185
186 /* SWO trace capture mode */
187 #define DAP_SWO_MODE_OFF 0
188 #define DAP_SWO_MODE_UART 1
189 #define DAP_SWO_MODE_MANCHESTER 2
190
191 /* SWO trace data capture */
192 #define DAP_SWO_CONTROL_STOP 0
193 #define DAP_SWO_CONTROL_START 1
194
195 /* SWO trace status */
196 #define DAP_SWO_STATUS_CAPTURE_INACTIVE 0
197 #define DAP_SWO_STATUS_CAPTURE_ACTIVE 1
198 #define DAP_SWO_STATUS_CAPTURE_MASK BIT(0)
199 #define DAP_SWO_STATUS_STREAM_ERROR_MASK BIT(6)
200 #define DAP_SWO_STATUS_BUFFER_OVERRUN_MASK BIT(7)
201
202 /* CMSIS-DAP Vendor Commands
203 * None as yet... */
204
205 static const char * const info_caps_str[INFO_CAPS__NUM_CAPS] = {
206 "SWD supported",
207 "JTAG supported",
208 "SWO-UART supported",
209 "SWO-MANCHESTER supported",
210 "Atomic commands supported",
211 "Test domain timer supported",
212 "SWO streaming trace supported",
213 "UART communication port supported",
214 "UART via USB COM port supported",
215 };
216
217 struct pending_scan_result {
218 /** Offset in bytes in the CMD_DAP_JTAG_SEQ response buffer. */
219 unsigned int first;
220 /** Number of bits to read. */
221 unsigned int length;
222 /** Location to store the result */
223 uint8_t *buffer;
224 /** Offset in the destination buffer */
225 unsigned int buffer_offset;
226 };
227
228 /* Read mode */
229 enum cmsis_dap_blocking {
230 CMSIS_DAP_NON_BLOCKING,
231 CMSIS_DAP_BLOCKING
232 };
233
234 /* Each block in FIFO can contain up to pending_queue_len transfers */
235 static unsigned int pending_queue_len;
236 static unsigned int tfer_max_command_size;
237 static unsigned int tfer_max_response_size;
238
239 /* pointers to buffers that will receive jtag scan results on the next flush */
240 #define MAX_PENDING_SCAN_RESULTS 256
241 static int pending_scan_result_count;
242 static struct pending_scan_result pending_scan_results[MAX_PENDING_SCAN_RESULTS];
243
244 /* queued JTAG sequences that will be executed on the next flush */
245 #define QUEUED_SEQ_BUF_LEN (cmsis_dap_handle->packet_usable_size - 3)
246 static int queued_seq_count;
247 static int queued_seq_buf_end;
248 static int queued_seq_tdo_ptr;
249 static uint8_t queued_seq_buf[1024]; /* TODO: make dynamic / move into cmsis object */
250
251 static int queued_retval;
252
253 static uint8_t output_pins = SWJ_PIN_SRST | SWJ_PIN_TRST;
254
255 static struct cmsis_dap *cmsis_dap_handle;
256
257
258 static int cmsis_dap_quit(void);
259
260 static int cmsis_dap_open(void)
261 {
262 const struct cmsis_dap_backend *backend = NULL;
263
264 struct cmsis_dap *dap = calloc(1, sizeof(struct cmsis_dap));
265 if (!dap) {
266 LOG_ERROR("unable to allocate memory");
267 return ERROR_FAIL;
268 }
269
270 if (cmsis_dap_backend >= 0) {
271 /* Use forced backend */
272 backend = cmsis_dap_backends[cmsis_dap_backend];
273 if (backend->open(dap, cmsis_dap_vid, cmsis_dap_pid, adapter_get_required_serial()) != ERROR_OK)
274 backend = NULL;
275 } else {
276 /* Try all backends */
277 for (unsigned int i = 0; i < ARRAY_SIZE(cmsis_dap_backends); i++) {
278 backend = cmsis_dap_backends[i];
279 if (backend->open(dap, cmsis_dap_vid, cmsis_dap_pid, adapter_get_required_serial()) == ERROR_OK)
280 break;
281 else
282 backend = NULL;
283 }
284 }
285
286 if (!backend) {
287 LOG_ERROR("unable to find a matching CMSIS-DAP device");
288 free(dap);
289 return ERROR_FAIL;
290 }
291
292 dap->backend = backend;
293
294 cmsis_dap_handle = dap;
295
296 return ERROR_OK;
297 }
298
299 static void cmsis_dap_close(struct cmsis_dap *dap)
300 {
301 if (dap->backend) {
302 dap->backend->close(dap);
303 dap->backend = NULL;
304 }
305
306 free(dap->packet_buffer);
307
308 for (unsigned int i = 0; i < MAX_PENDING_REQUESTS; i++) {
309 free(dap->pending_fifo[i].transfers);
310 dap->pending_fifo[i].transfers = NULL;
311 }
312
313 free(cmsis_dap_handle);
314 cmsis_dap_handle = NULL;
315 }
316
317 static void cmsis_dap_flush_read(struct cmsis_dap *dap)
318 {
319 unsigned int i;
320 /* Some CMSIS-DAP adapters keep buffered packets over
321 * USB close/open so we need to flush up to 64 old packets
322 * to be sure all buffers are empty */
323 for (i = 0; i < 64; i++) {
324 int retval = dap->backend->read(dap, 10, NULL);
325 if (retval == ERROR_TIMEOUT_REACHED)
326 break;
327 }
328 if (i)
329 LOG_DEBUG("Flushed %u packets", i);
330 }
331
332 /* Send a message and receive the reply */
333 static int cmsis_dap_xfer(struct cmsis_dap *dap, int txlen)
334 {
335 if (dap->write_count + dap->read_count) {
336 LOG_ERROR("internal: queue not empty before xfer");
337 }
338 if (dap->pending_fifo_block_count) {
339 LOG_ERROR("pending %u blocks, flushing", dap->pending_fifo_block_count);
340 while (dap->pending_fifo_block_count) {
341 dap->backend->read(dap, 10, NULL);
342 dap->pending_fifo_block_count--;
343 }
344 dap->pending_fifo_put_idx = 0;
345 dap->pending_fifo_get_idx = 0;
346 }
347
348 uint8_t current_cmd = dap->command[0];
349 int retval = dap->backend->write(dap, txlen, LIBUSB_TIMEOUT_MS);
350 if (retval < 0)
351 return retval;
352
353 /* get reply */
354 retval = dap->backend->read(dap, LIBUSB_TIMEOUT_MS, NULL);
355 if (retval < 0)
356 return retval;
357
358 uint8_t *resp = dap->response;
359 if (resp[0] == DAP_ERROR) {
360 LOG_ERROR("CMSIS-DAP command 0x%" PRIx8 " not implemented", current_cmd);
361 return ERROR_NOT_IMPLEMENTED;
362 }
363
364 if (resp[0] != current_cmd) {
365 LOG_ERROR("CMSIS-DAP command mismatch. Sent 0x%" PRIx8
366 " received 0x%" PRIx8, current_cmd, resp[0]);
367
368 dap->backend->cancel_all(dap);
369 cmsis_dap_flush_read(dap);
370 return ERROR_FAIL;
371 }
372
373 return ERROR_OK;
374 }
375
376 static int cmsis_dap_cmd_dap_swj_pins(uint8_t pins, uint8_t mask, uint32_t delay, uint8_t *input)
377 {
378 uint8_t *command = cmsis_dap_handle->command;
379
380 command[0] = CMD_DAP_SWJ_PINS;
381 command[1] = pins;
382 command[2] = mask;
383 h_u32_to_le(&command[3], delay);
384
385 int retval = cmsis_dap_xfer(cmsis_dap_handle, 7);
386 if (retval != ERROR_OK) {
387 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_PINS failed.");
388 return ERROR_JTAG_DEVICE_ERROR;
389 }
390
391 if (input)
392 *input = cmsis_dap_handle->response[1];
393
394 return ERROR_OK;
395 }
396
397 static int cmsis_dap_cmd_dap_swj_clock(uint32_t swj_clock)
398 {
399 uint8_t *command = cmsis_dap_handle->command;
400
401 /* set clock in Hz */
402 swj_clock *= 1000;
403
404 command[0] = CMD_DAP_SWJ_CLOCK;
405 h_u32_to_le(&command[1], swj_clock);
406
407 int retval = cmsis_dap_xfer(cmsis_dap_handle, 5);
408 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
409 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_CLOCK failed.");
410 return ERROR_JTAG_DEVICE_ERROR;
411 }
412
413 return ERROR_OK;
414 }
415
416 /* clock a sequence of bits out on TMS, to change JTAG states */
417 static int cmsis_dap_cmd_dap_swj_sequence(uint8_t s_len, const uint8_t *sequence)
418 {
419 uint8_t *command = cmsis_dap_handle->command;
420
421 #ifdef CMSIS_DAP_JTAG_DEBUG
422 LOG_DEBUG("cmsis-dap TMS sequence: len=%d", s_len);
423 for (unsigned int i = 0; i < DIV_ROUND_UP(s_len, 8); ++i)
424 printf("%02X ", sequence[i]);
425
426 printf("\n");
427 #endif
428
429 command[0] = CMD_DAP_SWJ_SEQ;
430 command[1] = s_len;
431 bit_copy(&command[2], 0, sequence, 0, s_len);
432
433 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2 + DIV_ROUND_UP(s_len, 8));
434 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK)
435 return ERROR_FAIL;
436
437 return ERROR_OK;
438 }
439
440 static int cmsis_dap_cmd_dap_info(uint8_t info, uint8_t **data)
441 {
442 uint8_t *command = cmsis_dap_handle->command;
443
444 command[0] = CMD_DAP_INFO;
445 command[1] = info;
446
447 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
448 if (retval != ERROR_OK) {
449 LOG_ERROR("CMSIS-DAP command CMD_INFO failed.");
450 return ERROR_JTAG_DEVICE_ERROR;
451 }
452
453 *data = &cmsis_dap_handle->response[1];
454
455 return ERROR_OK;
456 }
457
458 static int cmsis_dap_cmd_dap_led(uint8_t led, uint8_t state)
459 {
460 uint8_t *command = cmsis_dap_handle->command;
461
462 command[0] = CMD_DAP_LED;
463 command[1] = led;
464 command[2] = state;
465
466 int retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
467 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
468 LOG_ERROR("CMSIS-DAP command CMD_LED failed.");
469 return ERROR_JTAG_DEVICE_ERROR;
470 }
471
472 return ERROR_OK;
473 }
474
475 static int cmsis_dap_cmd_dap_connect(uint8_t mode)
476 {
477 uint8_t *command = cmsis_dap_handle->command;
478
479 command[0] = CMD_DAP_CONNECT;
480 command[1] = mode;
481
482 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
483 if (retval != ERROR_OK) {
484 LOG_ERROR("CMSIS-DAP command CMD_CONNECT failed.");
485 return ERROR_JTAG_DEVICE_ERROR;
486 }
487
488 if (cmsis_dap_handle->response[1] != mode) {
489 LOG_ERROR("CMSIS-DAP failed to connect in mode (%d)", mode);
490 return ERROR_JTAG_DEVICE_ERROR;
491 }
492
493 return ERROR_OK;
494 }
495
496 static int cmsis_dap_cmd_dap_disconnect(void)
497 {
498 uint8_t *command = cmsis_dap_handle->command;
499
500 command[0] = CMD_DAP_DISCONNECT;
501
502 int retval = cmsis_dap_xfer(cmsis_dap_handle, 1);
503 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
504 LOG_ERROR("CMSIS-DAP command CMD_DISCONNECT failed.");
505 return ERROR_JTAG_DEVICE_ERROR;
506 }
507
508 return ERROR_OK;
509 }
510
511 static int cmsis_dap_cmd_dap_tfer_configure(uint8_t idle, uint16_t retry_count, uint16_t match_retry)
512 {
513 uint8_t *command = cmsis_dap_handle->command;
514
515 command[0] = CMD_DAP_TFER_CONFIGURE;
516 command[1] = idle;
517 h_u16_to_le(&command[2], retry_count);
518 h_u16_to_le(&command[4], match_retry);
519
520 int retval = cmsis_dap_xfer(cmsis_dap_handle, 6);
521 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
522 LOG_ERROR("CMSIS-DAP command CMD_TFER_Configure failed.");
523 return ERROR_JTAG_DEVICE_ERROR;
524 }
525
526 return ERROR_OK;
527 }
528
529 static int cmsis_dap_cmd_dap_swd_configure(uint8_t cfg)
530 {
531 uint8_t *command = cmsis_dap_handle->command;
532
533 command[0] = CMD_DAP_SWD_CONFIGURE;
534 command[1] = cfg;
535
536 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
537 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
538 LOG_ERROR("CMSIS-DAP command CMD_SWD_Configure failed.");
539 return ERROR_JTAG_DEVICE_ERROR;
540 }
541
542 return ERROR_OK;
543 }
544
545 #if 0
546 static int cmsis_dap_cmd_dap_delay(uint16_t delay_us)
547 {
548 uint8_t *command = cmsis_dap_handle->command;
549
550 command[0] = CMD_DAP_DELAY;
551 h_u16_to_le(&command[1], delay_us);
552
553 int retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
554 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
555 LOG_ERROR("CMSIS-DAP command CMD_Delay failed.");
556 return ERROR_JTAG_DEVICE_ERROR;
557 }
558
559 return ERROR_OK;
560 }
561 #endif
562
563 static int cmsis_dap_metacmd_targetsel(uint32_t instance_id)
564 {
565 uint8_t *command = cmsis_dap_handle->command;
566 const uint32_t SEQ_RD = 0x80, SEQ_WR = 0x00;
567
568 /* SWD multi-drop requires a transfer ala CMD_DAP_TFER,
569 but with no expectation of an SWD ACK response. In
570 CMSIS-DAP v1.20 and v2.00, CMD_DAP_SWD_SEQUENCE was
571 added to allow this special sequence to be generated.
572 The purpose of this operation is to select the target
573 corresponding to the instance_id that is written */
574
575 LOG_DEBUG_IO("DP write reg TARGETSEL %" PRIx32, instance_id);
576
577 size_t idx = 0;
578 command[idx++] = CMD_DAP_SWD_SEQUENCE;
579 command[idx++] = 3; /* sequence count */
580
581 /* sequence 0: packet request for TARGETSEL */
582 command[idx++] = SEQ_WR | 8;
583 command[idx++] = SWD_CMD_START | swd_cmd(false, false, DP_TARGETSEL) | SWD_CMD_STOP | SWD_CMD_PARK;
584
585 /* sequence 1: read Trn ACK Trn, no expectation for target to ACK */
586 command[idx++] = SEQ_RD | 5;
587
588 /* sequence 2: WDATA plus parity */
589 command[idx++] = SEQ_WR | (32 + 1);
590 h_u32_to_le(command + idx, instance_id);
591 idx += 4;
592 command[idx++] = parity_u32(instance_id);
593
594 int retval = cmsis_dap_xfer(cmsis_dap_handle, idx);
595 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
596 LOG_ERROR("CMSIS-DAP command SWD_Sequence failed.");
597 return ERROR_JTAG_DEVICE_ERROR;
598 }
599
600 return ERROR_OK;
601 }
602
603 /**
604 * Sets the SWO transport mode.
605 * @param[in] transport The transport mode. Can be None, SWO_Data or
606 * WinUSB (requires CMSIS-DAP v2).
607 */
608 static int cmsis_dap_cmd_dap_swo_transport(uint8_t transport)
609 {
610 uint8_t *command = cmsis_dap_handle->command;
611
612 command[0] = CMD_DAP_SWO_TRANSPORT;
613 command[1] = transport;
614
615 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
616 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
617 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Transport(%d) failed.", transport);
618 return ERROR_JTAG_DEVICE_ERROR;
619 }
620
621 return ERROR_OK;
622 }
623
624 /**
625 * Sets the SWO trace capture mode.
626 * @param[in] mode Trace capture mode. Can be UART or MANCHESTER.
627 */
628 static int cmsis_dap_cmd_dap_swo_mode(uint8_t mode)
629 {
630 uint8_t *command = cmsis_dap_handle->command;
631
632 command[0] = CMD_DAP_SWO_MODE;
633 command[1] = mode;
634
635 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
636 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
637 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Mode(%d) failed.", mode);
638 return ERROR_JTAG_DEVICE_ERROR;
639 }
640
641 return ERROR_OK;
642 }
643
644 /**
645 * Sets the baudrate for capturing SWO trace data.
646 * Can be called iteratively to determine supported baudrates.
647 * @param[in] in_baudrate Requested baudrate.
648 * @param[out] dev_baudrate Actual baudrate or 0 (baudrate not configured).
649 * When requested baudrate is not achievable the
650 * closest configured baudrate can be returned or
651 * 0 which indicates that baudrate was not configured.
652 */
653 static int cmsis_dap_cmd_dap_swo_baudrate(
654 uint32_t in_baudrate,
655 uint32_t *dev_baudrate)
656 {
657 uint8_t *command = cmsis_dap_handle->command;
658
659 command[0] = CMD_DAP_SWO_BAUDRATE;
660 h_u32_to_le(&command[1], in_baudrate);
661
662 int retval = cmsis_dap_xfer(cmsis_dap_handle, 5);
663 uint32_t rvbr = le_to_h_u32(&cmsis_dap_handle->response[1]);
664 if (retval != ERROR_OK || rvbr == 0) {
665 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Baudrate(%u) -> %u failed.", in_baudrate, rvbr);
666 if (dev_baudrate)
667 *dev_baudrate = 0;
668 return ERROR_JTAG_DEVICE_ERROR;
669 }
670
671 if (dev_baudrate)
672 *dev_baudrate = rvbr;
673
674 return ERROR_OK;
675 }
676
677 /**
678 * Controls the SWO trace data capture.
679 * @param[in] control Start or stop a trace. Starting capture automatically
680 * flushes any existing trace data in buffers which has
681 * not yet been read.
682 */
683 static int cmsis_dap_cmd_dap_swo_control(uint8_t control)
684 {
685 uint8_t *command = cmsis_dap_handle->command;
686
687 command[0] = CMD_DAP_SWO_CONTROL;
688 command[1] = control;
689
690 int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
691 if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
692 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Control(%d) failed.", control);
693 return ERROR_JTAG_DEVICE_ERROR;
694 }
695
696 return ERROR_OK;
697 }
698
699 /**
700 * Reads the SWO trace status.
701 * @param[out] trace_status The trace's status.
702 * Bit0: Trace Capture (1 - active, 0 - inactive).
703 * Bit6: Trace Stream Error.
704 * Bit7: Trace Buffer Overrun.
705 * @param[out] trace_count Number of bytes in Trace Buffer (not yet read).
706 */
707 static int cmsis_dap_cmd_dap_swo_status(
708 uint8_t *trace_status,
709 size_t *trace_count)
710 {
711 uint8_t *command = cmsis_dap_handle->command;
712
713 command[0] = CMD_DAP_SWO_STATUS;
714
715 int retval = cmsis_dap_xfer(cmsis_dap_handle, 1);
716 if (retval != ERROR_OK) {
717 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Status failed.");
718 return ERROR_JTAG_DEVICE_ERROR;
719 }
720
721 if (trace_status)
722 *trace_status = cmsis_dap_handle->response[1];
723 if (trace_count)
724 *trace_count = le_to_h_u32(&cmsis_dap_handle->response[2]);
725
726 return ERROR_OK;
727 }
728
729 /**
730 * Reads the captured SWO trace data from Trace Buffer.
731 * @param[in] max_trace_count Maximum number of Trace Data bytes to read.
732 * @param[out] trace_status The trace's status.
733 * @param[out] trace_count Number of Trace Data bytes read.
734 * @param[out] data Trace Data bytes read.
735 */
736 static int cmsis_dap_cmd_dap_swo_data(
737 size_t max_trace_count,
738 uint8_t *trace_status,
739 size_t *trace_count,
740 uint8_t *data)
741 {
742 uint8_t *command = cmsis_dap_handle->command;
743
744 command[0] = CMD_DAP_SWO_DATA;
745 h_u16_to_le(&command[1], max_trace_count);
746
747 int retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
748 if (retval != ERROR_OK) {
749 LOG_ERROR("CMSIS-DAP: command CMD_SWO_Data failed.");
750 return ERROR_JTAG_DEVICE_ERROR;
751 }
752
753 *trace_status = cmsis_dap_handle->response[1];
754 *trace_count = le_to_h_u16(&cmsis_dap_handle->response[2]);
755
756 if (*trace_count > 0)
757 memcpy(data, &cmsis_dap_handle->response[4], *trace_count);
758
759 return ERROR_OK;
760 }
761
762 static void cmsis_dap_swd_discard_all_pending(struct cmsis_dap *dap)
763 {
764 for (unsigned int i = 0; i < MAX_PENDING_REQUESTS; i++)
765 dap->pending_fifo[i].transfer_count = 0;
766
767 dap->pending_fifo_put_idx = 0;
768 dap->pending_fifo_get_idx = 0;
769 dap->pending_fifo_block_count = 0;
770 }
771
772 static void cmsis_dap_swd_cancel_transfers(struct cmsis_dap *dap)
773 {
774 dap->backend->cancel_all(dap);
775 cmsis_dap_flush_read(dap);
776 cmsis_dap_swd_discard_all_pending(dap);
777 }
778
779 static void cmsis_dap_swd_write_from_queue(struct cmsis_dap *dap)
780 {
781 uint8_t *command = dap->command;
782 struct pending_request_block *block = &dap->pending_fifo[dap->pending_fifo_put_idx];
783
784 assert(dap->write_count + dap->read_count == block->transfer_count);
785
786 /* Reset packet size check counters for the next packet */
787 dap->write_count = 0;
788 dap->read_count = 0;
789
790 LOG_DEBUG_IO("Executing %d queued transactions from FIFO index %u%s",
791 block->transfer_count, dap->pending_fifo_put_idx,
792 cmsis_dap_handle->swd_cmds_differ ? "" : ", same swd ops");
793
794 if (queued_retval != ERROR_OK) {
795 LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
796 goto skip;
797 }
798
799 if (block->transfer_count == 0) {
800 LOG_ERROR("internal: write an empty queue?!");
801 goto skip;
802 }
803
804 bool block_cmd = !cmsis_dap_handle->swd_cmds_differ
805 && block->transfer_count >= CMD_DAP_TFER_BLOCK_MIN_OPS;
806 block->command = block_cmd ? CMD_DAP_TFER_BLOCK : CMD_DAP_TFER;
807
808 command[0] = block->command;
809 command[1] = 0x00; /* DAP Index */
810
811 unsigned int idx;
812 if (block_cmd) {
813 h_u16_to_le(&command[2], block->transfer_count);
814 idx = 4; /* The first transfer will store the common DAP register */
815 } else {
816 command[2] = block->transfer_count;
817 idx = 3;
818 }
819
820 for (unsigned int i = 0; i < block->transfer_count; i++) {
821 struct pending_transfer_result *transfer = &(block->transfers[i]);
822 uint8_t cmd = transfer->cmd;
823 uint32_t data = transfer->data;
824
825 LOG_DEBUG_IO("%s %s reg %x %" PRIx32,
826 cmd & SWD_CMD_APNDP ? "AP" : "DP",
827 cmd & SWD_CMD_RNW ? "read" : "write",
828 (cmd & SWD_CMD_A32) >> 1, data);
829
830 /* When proper WAIT handling is implemented in the
831 * common SWD framework, this kludge can be
832 * removed. However, this might lead to minor
833 * performance degradation as the adapter wouldn't be
834 * able to automatically retry anything (because ARM
835 * has forgotten to implement sticky error flags
836 * clearing). See also comments regarding
837 * cmsis_dap_cmd_dap_tfer_configure() and
838 * cmsis_dap_cmd_dap_swd_configure() in
839 * cmsis_dap_init().
840 */
841 if (!(cmd & SWD_CMD_RNW) &&
842 !(cmd & SWD_CMD_APNDP) &&
843 (cmd & SWD_CMD_A32) >> 1 == DP_CTRL_STAT &&
844 (data & CORUNDETECT)) {
845 LOG_DEBUG("refusing to enable sticky overrun detection");
846 data &= ~CORUNDETECT;
847 }
848
849 if (!block_cmd || i == 0)
850 command[idx++] = (cmd >> 1) & 0x0f;
851
852 if (!(cmd & SWD_CMD_RNW)) {
853 h_u32_to_le(&command[idx], data);
854 idx += 4;
855 }
856 }
857
858 int retval = dap->backend->write(dap, idx, LIBUSB_TIMEOUT_MS);
859 if (retval < 0) {
860 queued_retval = retval;
861 goto skip;
862 }
863
864 dap->pending_fifo_put_idx = (dap->pending_fifo_put_idx + 1) % dap->packet_count;
865 dap->pending_fifo_block_count++;
866 if (dap->pending_fifo_block_count > dap->packet_count)
867 LOG_ERROR("internal: too much pending writes %u", dap->pending_fifo_block_count);
868
869 return;
870
871 skip:
872 block->transfer_count = 0;
873 }
874
875 static void cmsis_dap_swd_read_process(struct cmsis_dap *dap, enum cmsis_dap_blocking blocking)
876 {
877 int retval;
878 struct pending_request_block *block = &dap->pending_fifo[dap->pending_fifo_get_idx];
879
880 if (dap->pending_fifo_block_count == 0) {
881 LOG_ERROR("internal: no pending write when reading?!");
882 return;
883 }
884
885 if (queued_retval != ERROR_OK) {
886 /* keep reading blocks until the pipeline is empty */
887 retval = dap->backend->read(dap, 10, NULL);
888 if (retval == ERROR_TIMEOUT_REACHED || retval == 0) {
889 /* timeout means that we flushed the pipeline,
890 * we can safely discard remaining pending requests */
891 cmsis_dap_swd_discard_all_pending(dap);
892 return;
893 }
894 goto skip;
895 }
896
897 /* get reply */
898 struct timeval tv = {
899 .tv_sec = 0,
900 .tv_usec = 0
901 };
902 retval = dap->backend->read(dap, LIBUSB_TIMEOUT_MS, blocking ? NULL : &tv);
903 bool timeout = (retval == ERROR_TIMEOUT_REACHED || retval == 0);
904 if (timeout && blocking == CMSIS_DAP_NON_BLOCKING)
905 return;
906
907 if (retval <= 0) {
908 LOG_DEBUG("error reading adapter response");
909 queued_retval = ERROR_FAIL;
910 if (timeout) {
911 /* timeout means that we flushed the pipeline,
912 * we can safely discard remaining pending requests */
913 cmsis_dap_swd_discard_all_pending(dap);
914 return;
915 }
916 goto skip;
917 }
918
919 uint8_t *resp = dap->response;
920 if (resp[0] != block->command) {
921 LOG_ERROR("CMSIS-DAP command mismatch. Expected 0x%x received 0x%" PRIx8,
922 block->command, resp[0]);
923 cmsis_dap_swd_cancel_transfers(dap);
924 queued_retval = ERROR_FAIL;
925 return;
926 }
927
928 unsigned int transfer_count;
929 unsigned int idx;
930 if (block->command == CMD_DAP_TFER_BLOCK) {
931 transfer_count = le_to_h_u16(&resp[1]);
932 idx = 3;
933 } else {
934 transfer_count = resp[1];
935 idx = 2;
936 }
937 if (resp[idx] & 0x08) {
938 LOG_DEBUG("CMSIS-DAP Protocol Error @ %d (wrong parity)", transfer_count);
939 queued_retval = ERROR_FAIL;
940 goto skip;
941 }
942 uint8_t ack = resp[idx++] & 0x07;
943 if (ack != SWD_ACK_OK) {
944 LOG_DEBUG("SWD ack not OK @ %d %s", transfer_count,
945 ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
946 queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
947 /* TODO: use results of transfers completed before the error occurred? */
948 goto skip;
949 }
950
951 if (block->transfer_count != transfer_count) {
952 LOG_ERROR("CMSIS-DAP transfer count mismatch: expected %d, got %d",
953 block->transfer_count, transfer_count);
954 cmsis_dap_swd_cancel_transfers(dap);
955 queued_retval = ERROR_FAIL;
956 return;
957 }
958
959 LOG_DEBUG_IO("Received results of %d queued transactions FIFO index %u, %s mode",
960 transfer_count, dap->pending_fifo_get_idx,
961 blocking ? "blocking" : "nonblocking");
962
963 for (unsigned int i = 0; i < transfer_count; i++) {
964 struct pending_transfer_result *transfer = &(block->transfers[i]);
965 if (transfer->cmd & SWD_CMD_RNW) {
966 static uint32_t last_read;
967 uint32_t data = le_to_h_u32(&resp[idx]);
968 uint32_t tmp = data;
969 idx += 4;
970
971 LOG_DEBUG_IO("Read result: %" PRIx32, data);
972
973 /* Imitate posted AP reads */
974 if ((transfer->cmd & SWD_CMD_APNDP) ||
975 ((transfer->cmd & SWD_CMD_A32) >> 1 == DP_RDBUFF)) {
976 tmp = last_read;
977 last_read = data;
978 }
979
980 if (transfer->buffer)
981 *(uint32_t *)(transfer->buffer) = tmp;
982 }
983 }
984
985 skip:
986 block->transfer_count = 0;
987 dap->pending_fifo_get_idx = (dap->pending_fifo_get_idx + 1) % dap->packet_count;
988 dap->pending_fifo_block_count--;
989 }
990
991 static int cmsis_dap_swd_run_queue(void)
992 {
993 if (cmsis_dap_handle->write_count + cmsis_dap_handle->read_count) {
994 if (cmsis_dap_handle->pending_fifo_block_count)
995 cmsis_dap_swd_read_process(cmsis_dap_handle, CMSIS_DAP_NON_BLOCKING);
996
997 cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
998 }
999
1000 while (cmsis_dap_handle->pending_fifo_block_count)
1001 cmsis_dap_swd_read_process(cmsis_dap_handle, CMSIS_DAP_BLOCKING);
1002
1003 cmsis_dap_handle->pending_fifo_put_idx = 0;
1004 cmsis_dap_handle->pending_fifo_get_idx = 0;
1005
1006 int retval = queued_retval;
1007 queued_retval = ERROR_OK;
1008
1009 return retval;
1010 }
1011
1012 static unsigned int cmsis_dap_tfer_cmd_size(unsigned int write_count,
1013 unsigned int read_count, bool block_tfer)
1014 {
1015 unsigned int size;
1016 if (block_tfer) {
1017 size = 5; /* DAP_TransferBlock header */
1018 size += write_count * 4; /* data */
1019 } else {
1020 size = 3; /* DAP_Transfer header */
1021 size += write_count * (1 + 4); /* DAP register + data */
1022 size += read_count; /* DAP register */
1023 }
1024 return size;
1025 }
1026
1027 static unsigned int cmsis_dap_tfer_resp_size(unsigned int write_count,
1028 unsigned int read_count, bool block_tfer)
1029 {
1030 unsigned int size;
1031 if (block_tfer)
1032 size = 4; /* DAP_TransferBlock response header */
1033 else
1034 size = 3; /* DAP_Transfer response header */
1035
1036 size += read_count * 4; /* data */
1037 return size;
1038 }
1039
1040 static void cmsis_dap_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data)
1041 {
1042 /* TARGETSEL register write cannot be queued */
1043 if (swd_cmd(false, false, DP_TARGETSEL) == cmd) {
1044 queued_retval = cmsis_dap_swd_run_queue();
1045
1046 cmsis_dap_metacmd_targetsel(data);
1047 return;
1048 }
1049
1050 /* Compute sizes of the DAP Transfer command and the expected response
1051 * for all queued and this operation */
1052 unsigned int write_count = cmsis_dap_handle->write_count;
1053 unsigned int read_count = cmsis_dap_handle->read_count;
1054 bool block_cmd;
1055 if (write_count + read_count < CMD_DAP_TFER_BLOCK_MIN_OPS)
1056 block_cmd = false;
1057 else
1058 block_cmd = !cmsis_dap_handle->swd_cmds_differ
1059 && cmd == cmsis_dap_handle->common_swd_cmd;
1060
1061 if (cmd & SWD_CMD_RNW)
1062 read_count++;
1063 else
1064 write_count++;
1065
1066 unsigned int cmd_size = cmsis_dap_tfer_cmd_size(write_count, read_count,
1067 block_cmd);
1068 unsigned int resp_size = cmsis_dap_tfer_resp_size(write_count, read_count,
1069 block_cmd);
1070 unsigned int max_transfer_count = block_cmd ? 65535 : 255;
1071
1072 /* Does the DAP Transfer command and also its expected response fit into one packet? */
1073 if (cmd_size > tfer_max_command_size
1074 || resp_size > tfer_max_response_size
1075 || write_count + read_count > max_transfer_count) {
1076 if (cmsis_dap_handle->pending_fifo_block_count)
1077 cmsis_dap_swd_read_process(cmsis_dap_handle, CMSIS_DAP_NON_BLOCKING);
1078
1079 /* Not enough room in the queue. Run the queue. */
1080 cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
1081
1082 if (cmsis_dap_handle->pending_fifo_block_count >= cmsis_dap_handle->packet_count)
1083 cmsis_dap_swd_read_process(cmsis_dap_handle, CMSIS_DAP_BLOCKING);
1084 }
1085
1086 assert(cmsis_dap_handle->pending_fifo[cmsis_dap_handle->pending_fifo_put_idx].transfer_count < pending_queue_len);
1087
1088 if (queued_retval != ERROR_OK)
1089 return;
1090
1091 struct pending_request_block *block = &cmsis_dap_handle->pending_fifo[cmsis_dap_handle->pending_fifo_put_idx];
1092 struct pending_transfer_result *transfer = &(block->transfers[block->transfer_count]);
1093 transfer->data = data;
1094 transfer->cmd = cmd;
1095 if (block->transfer_count == 0) {
1096 cmsis_dap_handle->swd_cmds_differ = false;
1097 cmsis_dap_handle->common_swd_cmd = cmd;
1098 } else if (cmd != cmsis_dap_handle->common_swd_cmd) {
1099 cmsis_dap_handle->swd_cmds_differ = true;
1100 }
1101
1102 if (cmd & SWD_CMD_RNW) {
1103 /* Queue a read transaction */
1104 transfer->buffer = dst;
1105 cmsis_dap_handle->read_count++;
1106 } else {
1107 cmsis_dap_handle->write_count++;
1108 }
1109 block->transfer_count++;
1110 }
1111
1112 static void cmsis_dap_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
1113 {
1114 assert(!(cmd & SWD_CMD_RNW));
1115 cmsis_dap_swd_queue_cmd(cmd, NULL, value);
1116 }
1117
1118 static void cmsis_dap_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
1119 {
1120 assert(cmd & SWD_CMD_RNW);
1121 cmsis_dap_swd_queue_cmd(cmd, value, 0);
1122 }
1123
1124 static int cmsis_dap_get_serial_info(void)
1125 {
1126 uint8_t *data;
1127
1128 int retval = cmsis_dap_cmd_dap_info(INFO_ID_SERNUM, &data);
1129 if (retval != ERROR_OK)
1130 return retval;
1131
1132 if (data[0]) /* strlen */
1133 LOG_INFO("CMSIS-DAP: Serial# = %s", &data[1]);
1134
1135 return ERROR_OK;
1136 }
1137
1138 static int cmsis_dap_get_version_info(void)
1139 {
1140 uint8_t *data;
1141
1142 /* INFO_ID_FW_VER - string */
1143 int retval = cmsis_dap_cmd_dap_info(INFO_ID_FW_VER, &data);
1144 if (retval != ERROR_OK)
1145 return retval;
1146
1147 if (data[0]) /* strlen */
1148 LOG_INFO("CMSIS-DAP: FW Version = %s", &data[1]);
1149
1150 return ERROR_OK;
1151 }
1152
1153 static int cmsis_dap_get_caps_info(void)
1154 {
1155 uint8_t *data;
1156
1157 /* INFO_ID_CAPS - byte */
1158 int retval = cmsis_dap_cmd_dap_info(INFO_ID_CAPS, &data);
1159 if (retval != ERROR_OK)
1160 return retval;
1161
1162 if (data[0] == 1 || data[0] == 2) {
1163 uint16_t caps = data[1];
1164 if (data[0] == 2)
1165 caps |= (uint16_t)data[2] << 8;
1166
1167 cmsis_dap_handle->caps = caps;
1168
1169 for (unsigned int i = 0; i < INFO_CAPS__NUM_CAPS; ++i) {
1170 if (caps & BIT(i))
1171 LOG_INFO("CMSIS-DAP: %s", info_caps_str[i]);
1172 }
1173 }
1174
1175 return ERROR_OK;
1176 }
1177
1178 static int cmsis_dap_get_swo_buf_sz(uint32_t *swo_buf_sz)
1179 {
1180 uint8_t *data;
1181
1182 /* INFO_ID_SWO_BUF_SZ - word */
1183 int retval = cmsis_dap_cmd_dap_info(INFO_ID_SWO_BUF_SZ, &data);
1184 if (retval != ERROR_OK)
1185 return retval;
1186
1187 if (data[0] != 4)
1188 return ERROR_FAIL;
1189
1190 *swo_buf_sz = le_to_h_u32(&data[1]);
1191
1192 LOG_INFO("CMSIS-DAP: SWO Trace Buffer Size = %u bytes", *swo_buf_sz);
1193
1194 return ERROR_OK;
1195 }
1196
1197 static int cmsis_dap_get_status(void)
1198 {
1199 uint8_t d;
1200
1201 int retval = cmsis_dap_cmd_dap_swj_pins(0, 0, 0, &d);
1202
1203 if (retval == ERROR_OK) {
1204 LOG_INFO("SWCLK/TCK = %d SWDIO/TMS = %d TDI = %d TDO = %d nTRST = %d nRESET = %d",
1205 (d & SWJ_PIN_TCK) ? 1 : 0,
1206 (d & SWJ_PIN_TMS) ? 1 : 0,
1207 (d & SWJ_PIN_TDI) ? 1 : 0,
1208 (d & SWJ_PIN_TDO) ? 1 : 0,
1209 (d & SWJ_PIN_TRST) ? 1 : 0,
1210 (d & SWJ_PIN_SRST) ? 1 : 0);
1211 }
1212
1213 return retval;
1214 }
1215
1216 static int cmsis_dap_swd_switch_seq(enum swd_special_seq seq)
1217 {
1218 const uint8_t *s;
1219 unsigned int s_len;
1220 int retval;
1221
1222 if (swd_mode)
1223 queued_retval = cmsis_dap_swd_run_queue();
1224
1225 if (seq != LINE_RESET &&
1226 (output_pins & (SWJ_PIN_SRST | SWJ_PIN_TRST))
1227 == (SWJ_PIN_SRST | SWJ_PIN_TRST)) {
1228 /* Following workaround deasserts reset on most adapters.
1229 * Do not reconnect if a reset line is active!
1230 * Reconnecting would break connecting under reset. */
1231
1232 /* First disconnect before connecting, Atmel EDBG needs it for SAMD/R/L/C */
1233 cmsis_dap_cmd_dap_disconnect();
1234
1235 /* When we are reconnecting, DAP_Connect needs to be rerun, at
1236 * least on Keil ULINK-ME */
1237 retval = cmsis_dap_cmd_dap_connect(CONNECT_SWD);
1238 if (retval != ERROR_OK)
1239 return retval;
1240 }
1241
1242 switch (seq) {
1243 case LINE_RESET:
1244 LOG_DEBUG_IO("SWD line reset");
1245 s = swd_seq_line_reset;
1246 s_len = swd_seq_line_reset_len;
1247 break;
1248 case JTAG_TO_SWD:
1249 LOG_DEBUG("JTAG-to-SWD");
1250 s = swd_seq_jtag_to_swd;
1251 s_len = swd_seq_jtag_to_swd_len;
1252 break;
1253 case JTAG_TO_DORMANT:
1254 LOG_DEBUG("JTAG-to-DORMANT");
1255 s = swd_seq_jtag_to_dormant;
1256 s_len = swd_seq_jtag_to_dormant_len;
1257 break;
1258 case SWD_TO_JTAG:
1259 LOG_DEBUG("SWD-to-JTAG");
1260 s = swd_seq_swd_to_jtag;
1261 s_len = swd_seq_swd_to_jtag_len;
1262 break;
1263 case SWD_TO_DORMANT:
1264 LOG_DEBUG("SWD-to-DORMANT");
1265 s = swd_seq_swd_to_dormant;
1266 s_len = swd_seq_swd_to_dormant_len;
1267 break;
1268 case DORMANT_TO_SWD:
1269 LOG_DEBUG("DORMANT-to-SWD");
1270 s = swd_seq_dormant_to_swd;
1271 s_len = swd_seq_dormant_to_swd_len;
1272 break;
1273 case DORMANT_TO_JTAG:
1274 LOG_DEBUG("DORMANT-to-JTAG");
1275 s = swd_seq_dormant_to_jtag;
1276 s_len = swd_seq_dormant_to_jtag_len;
1277 break;
1278 default:
1279 LOG_ERROR("Sequence %d not supported", seq);
1280 return ERROR_FAIL;
1281 }
1282
1283 retval = cmsis_dap_cmd_dap_swj_sequence(s_len, s);
1284 if (retval != ERROR_OK)
1285 return retval;
1286
1287 /* Atmel EDBG needs renew clock setting after SWJ_Sequence
1288 * otherwise default frequency is used */
1289 return cmsis_dap_cmd_dap_swj_clock(adapter_get_speed_khz());
1290 }
1291
1292 static int cmsis_dap_swd_open(void)
1293 {
1294 if (!(cmsis_dap_handle->caps & INFO_CAPS_SWD)) {
1295 LOG_ERROR("CMSIS-DAP: SWD not supported");
1296 return ERROR_JTAG_DEVICE_ERROR;
1297 }
1298
1299 int retval = cmsis_dap_cmd_dap_connect(CONNECT_SWD);
1300 if (retval != ERROR_OK)
1301 return retval;
1302
1303 /* Add more setup here.??... */
1304
1305 LOG_INFO("CMSIS-DAP: Interface Initialised (SWD)");
1306 return ERROR_OK;
1307 }
1308
1309 static int cmsis_dap_init(void)
1310 {
1311 uint8_t *data;
1312
1313 int retval = cmsis_dap_open();
1314 if (retval != ERROR_OK)
1315 return retval;
1316
1317 cmsis_dap_flush_read(cmsis_dap_handle);
1318
1319 retval = cmsis_dap_get_caps_info();
1320 if (retval != ERROR_OK)
1321 return retval;
1322
1323 retval = cmsis_dap_get_version_info();
1324 if (retval != ERROR_OK)
1325 return retval;
1326
1327 retval = cmsis_dap_get_serial_info();
1328 if (retval != ERROR_OK)
1329 return retval;
1330
1331 if (swd_mode) {
1332 retval = cmsis_dap_swd_open();
1333 if (retval != ERROR_OK)
1334 return retval;
1335 } else {
1336 /* Connect in JTAG mode */
1337 if (!(cmsis_dap_handle->caps & INFO_CAPS_JTAG)) {
1338 LOG_ERROR("CMSIS-DAP: JTAG not supported");
1339 return ERROR_JTAG_DEVICE_ERROR;
1340 }
1341
1342 retval = cmsis_dap_cmd_dap_connect(CONNECT_JTAG);
1343 if (retval != ERROR_OK)
1344 return retval;
1345
1346 LOG_INFO("CMSIS-DAP: Interface Initialised (JTAG)");
1347 }
1348
1349 /* Be conservative and suppress submitting multiple HID requests
1350 * until we get packet count info from the adaptor */
1351 cmsis_dap_handle->packet_count = 1;
1352
1353 /* INFO_ID_PKT_SZ - short */
1354 retval = cmsis_dap_cmd_dap_info(INFO_ID_PKT_SZ, &data);
1355 if (retval != ERROR_OK)
1356 goto init_err;
1357
1358 if (data[0] == 2) { /* short */
1359 uint16_t pkt_sz = data[1] + (data[2] << 8);
1360 if (pkt_sz != cmsis_dap_handle->packet_size) {
1361 cmsis_dap_handle->backend->packet_buffer_free(cmsis_dap_handle);
1362 retval = cmsis_dap_handle->backend->packet_buffer_alloc(cmsis_dap_handle, pkt_sz);
1363 if (retval != ERROR_OK)
1364 goto init_err;
1365
1366 LOG_DEBUG("CMSIS-DAP: Packet Size = %" PRIu16, pkt_sz);
1367 }
1368 }
1369
1370 /* Maximal number of transfers which fit to one packet:
1371 * Limited by response size: 3 bytes of response header + 4 per read
1372 * Plus writes to full command size: 3 bytes cmd header + 1 per read + 5 per write */
1373 tfer_max_command_size = cmsis_dap_handle->packet_usable_size;
1374 tfer_max_response_size = cmsis_dap_handle->packet_usable_size;
1375 unsigned int max_reads = tfer_max_response_size / 4;
1376 pending_queue_len = max_reads + (tfer_max_command_size - max_reads) / 5;
1377 cmsis_dap_handle->write_count = 0;
1378 cmsis_dap_handle->read_count = 0;
1379
1380 /* INFO_ID_PKT_CNT - byte */
1381 retval = cmsis_dap_cmd_dap_info(INFO_ID_PKT_CNT, &data);
1382 if (retval != ERROR_OK)
1383 goto init_err;
1384
1385 if (data[0] == 1) { /* byte */
1386 unsigned int pkt_cnt = data[1];
1387 if (pkt_cnt > 1)
1388 cmsis_dap_handle->packet_count = MIN(MAX_PENDING_REQUESTS, pkt_cnt);
1389
1390 LOG_DEBUG("CMSIS-DAP: Packet Count = %u", pkt_cnt);
1391 }
1392
1393 LOG_DEBUG("Allocating FIFO for %u pending packets", cmsis_dap_handle->packet_count);
1394 for (unsigned int i = 0; i < cmsis_dap_handle->packet_count; i++) {
1395 cmsis_dap_handle->pending_fifo[i].transfers = malloc(pending_queue_len
1396 * sizeof(struct pending_transfer_result));
1397 if (!cmsis_dap_handle->pending_fifo[i].transfers) {
1398 LOG_ERROR("Unable to allocate memory for CMSIS-DAP queue");
1399 retval = ERROR_FAIL;
1400 goto init_err;
1401 }
1402 }
1403
1404 /* Intentionally not checked for error, just logs an info message
1405 * not vital for further debugging */
1406 (void)cmsis_dap_get_status();
1407
1408 /* Now try to connect to the target
1409 * TODO: This is all SWD only @ present */
1410 retval = cmsis_dap_cmd_dap_swj_clock(adapter_get_speed_khz());
1411 if (retval != ERROR_OK)
1412 goto init_err;
1413
1414 /* Ask CMSIS-DAP to automatically retry on receiving WAIT for
1415 * up to 64 times. This must be changed to 0 if sticky
1416 * overrun detection is enabled. */
1417 retval = cmsis_dap_cmd_dap_tfer_configure(0, 64, 0);
1418 if (retval != ERROR_OK)
1419 goto init_err;
1420
1421 if (swd_mode) {
1422 /* Data Phase (bit 2) must be set to 1 if sticky overrun
1423 * detection is enabled */
1424 retval = cmsis_dap_cmd_dap_swd_configure(0); /* 1 TRN, no Data Phase */
1425 if (retval != ERROR_OK)
1426 goto init_err;
1427 }
1428 /* Both LEDs on */
1429 /* Intentionally not checked for error, debugging will work
1430 * without LEDs */
1431 (void)cmsis_dap_cmd_dap_led(LED_ID_CONNECT, LED_ON);
1432 (void)cmsis_dap_cmd_dap_led(LED_ID_RUN, LED_ON);
1433
1434 /* support connecting with srst asserted */
1435 enum reset_types jtag_reset_config = jtag_get_reset_config();
1436
1437 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
1438 if (jtag_reset_config & RESET_SRST_NO_GATING) {
1439 retval = cmsis_dap_cmd_dap_swj_pins(0, SWJ_PIN_SRST, 0, NULL);
1440 if (retval != ERROR_OK)
1441 goto init_err;
1442 LOG_INFO("Connecting under reset");
1443 }
1444 }
1445 LOG_INFO("CMSIS-DAP: Interface ready");
1446 return ERROR_OK;
1447
1448 init_err:
1449 cmsis_dap_quit();
1450 return retval;
1451 }
1452
1453 static int cmsis_dap_swd_init(void)
1454 {
1455 swd_mode = true;
1456 return ERROR_OK;
1457 }
1458
1459 static int cmsis_dap_quit(void)
1460 {
1461 cmsis_dap_cmd_dap_disconnect();
1462
1463 /* Both LEDs off */
1464 cmsis_dap_cmd_dap_led(LED_ID_RUN, LED_OFF);
1465 cmsis_dap_cmd_dap_led(LED_ID_CONNECT, LED_OFF);
1466
1467 cmsis_dap_close(cmsis_dap_handle);
1468
1469 return ERROR_OK;
1470 }
1471
1472 static int cmsis_dap_reset(int trst, int srst)
1473 {
1474 /* Set both TRST and SRST even if they're not enabled as
1475 * there's no way to tristate them */
1476
1477 output_pins = 0;
1478 if (!srst)
1479 output_pins |= SWJ_PIN_SRST;
1480 if (!trst)
1481 output_pins |= SWJ_PIN_TRST;
1482
1483 int retval = cmsis_dap_cmd_dap_swj_pins(output_pins,
1484 SWJ_PIN_TRST | SWJ_PIN_SRST, 0, NULL);
1485 if (retval != ERROR_OK)
1486 LOG_ERROR("CMSIS-DAP: Interface reset failed");
1487 return retval;
1488 }
1489
1490 static void cmsis_dap_execute_sleep(struct jtag_command *cmd)
1491 {
1492 #if 0
1493 int retval = cmsis_dap_cmd_dap_delay(cmd->cmd.sleep->us);
1494 if (retval != ERROR_OK)
1495 #endif
1496 jtag_sleep(cmd->cmd.sleep->us);
1497 }
1498
1499 /* Set TMS high for five TCK clocks, to move the TAP to the Test-Logic-Reset state */
1500 static int cmsis_dap_execute_tlr_reset(struct jtag_command *cmd)
1501 {
1502 LOG_INFO("cmsis-dap JTAG TLR_RESET");
1503 uint8_t seq = 0xff;
1504
1505 int retval = cmsis_dap_cmd_dap_swj_sequence(8, &seq);
1506 if (retval == ERROR_OK)
1507 tap_set_state(TAP_RESET);
1508 return retval;
1509 }
1510
1511 /* Set new end state */
1512 static void cmsis_dap_end_state(tap_state_t state)
1513 {
1514 if (tap_is_state_stable(state))
1515 tap_set_end_state(state);
1516 else {
1517 LOG_ERROR("BUG: %i is not a valid end state", state);
1518 exit(-1);
1519 }
1520 }
1521
1522 #ifdef SPRINT_BINARY
1523 static void sprint_binary(char *s, const uint8_t *buf, unsigned int offset, unsigned int len)
1524 {
1525 if (!len)
1526 return;
1527
1528 /*
1529 buf = { 0x18 } len=5 should result in: 11000
1530 buf = { 0xff 0x18 } len=13 should result in: 11111111 11000
1531 buf = { 0xc0 0x18 } offset=3 len=10 should result in: 11000 11000
1532 i=3 there means i/8 = 0 so c = 0xFF, and
1533 */
1534 for (unsigned int i = offset; i < offset + len; ++i) {
1535 uint8_t c = buf[i / 8], mask = 1 << (i % 8);
1536 if ((i != offset) && !(i % 8))
1537 putchar(' ');
1538 *s++ = (c & mask) ? '1' : '0';
1539 }
1540 *s = 0;
1541 }
1542 #endif
1543
1544 #ifdef CMSIS_DAP_JTAG_DEBUG
1545 static void debug_parse_cmsis_buf(const uint8_t *cmd, int cmdlen)
1546 {
1547 /* cmd is a usb packet to go to the cmsis-dap interface */
1548 printf("cmsis-dap buffer (%d b): ", cmdlen);
1549 for (int i = 0; i < cmdlen; ++i)
1550 printf(" %02x", cmd[i]);
1551 printf("\n");
1552 switch (cmd[0]) {
1553 case CMD_DAP_JTAG_SEQ: {
1554 printf("cmsis-dap jtag sequence command %02x (n=%d)\n", cmd[0], cmd[1]);
1555 /*
1556 * #1 = number of sequences
1557 * #2 = sequence info 1
1558 * #3...4+n_bytes-1 = sequence 1
1559 * #4+n_bytes = sequence info 2
1560 * #5+n_bytes = sequence 2 (single bit)
1561 */
1562 int pos = 2;
1563 for (int seq = 0; seq < cmd[1]; ++seq) {
1564 uint8_t info = cmd[pos++];
1565 int len = info & DAP_JTAG_SEQ_TCK;
1566 if (len == 0)
1567 len = 64;
1568 printf(" sequence %d starting %d: info %02x (len=%d tms=%d read_tdo=%d): ",
1569 seq, pos, info, len, info & DAP_JTAG_SEQ_TMS, info & DAP_JTAG_SEQ_TDO);
1570 for (int i = 0; i < DIV_ROUND_UP(len, 8); ++i)
1571 printf(" %02x", cmd[pos+i]);
1572 pos += DIV_ROUND_UP(len, 8);
1573 printf("\n");
1574 }
1575 if (pos != cmdlen) {
1576 printf("BUFFER LENGTH MISMATCH looks like %d but %d specified", pos, cmdlen);
1577 exit(-1);
1578 }
1579
1580 break;
1581 }
1582 default:
1583 LOG_DEBUG("unknown cmsis-dap command %02x", cmd[1]);
1584 break;
1585 }
1586 }
1587 #endif
1588
1589 static void cmsis_dap_flush(void)
1590 {
1591 if (!queued_seq_count)
1592 return;
1593
1594 LOG_DEBUG_IO("Flushing %d queued sequences (%d bytes) with %d pending scan results to capture",
1595 queued_seq_count, queued_seq_buf_end, pending_scan_result_count);
1596
1597 /* prepare CMSIS-DAP packet */
1598 uint8_t *command = cmsis_dap_handle->command;
1599 command[0] = CMD_DAP_JTAG_SEQ;
1600 command[1] = queued_seq_count;
1601 memcpy(&command[2], queued_seq_buf, queued_seq_buf_end);
1602
1603 #ifdef CMSIS_DAP_JTAG_DEBUG
1604 debug_parse_cmsis_buf(command, queued_seq_buf_end + 2);
1605 #endif
1606
1607 /* send command to USB device */
1608 int retval = cmsis_dap_xfer(cmsis_dap_handle, queued_seq_buf_end + 2);
1609
1610 uint8_t *resp = cmsis_dap_handle->response;
1611 if (retval != ERROR_OK || resp[1] != DAP_OK) {
1612 LOG_ERROR("CMSIS-DAP command CMD_DAP_JTAG_SEQ failed.");
1613 exit(-1);
1614 }
1615
1616 #ifdef CMSIS_DAP_JTAG_DEBUG
1617 LOG_DEBUG_IO("USB response buf:");
1618 for (int c = 0; c < queued_seq_buf_end + 3; ++c)
1619 printf("%02X ", resp[c]);
1620 printf("\n");
1621 #endif
1622
1623 /* copy scan results into client buffers */
1624 for (int i = 0; i < pending_scan_result_count; ++i) {
1625 struct pending_scan_result *scan = &pending_scan_results[i];
1626 LOG_DEBUG_IO("Copying pending_scan_result %d/%d: %d bits from byte %d -> buffer + %d bits",
1627 i, pending_scan_result_count, scan->length, scan->first + 2, scan->buffer_offset);
1628 #ifdef CMSIS_DAP_JTAG_DEBUG
1629 for (uint32_t b = 0; b < DIV_ROUND_UP(scan->length, 8); ++b)
1630 printf("%02X ", resp[2+scan->first+b]);
1631 printf("\n");
1632 #endif
1633 bit_copy(scan->buffer, scan->buffer_offset, &resp[2 + scan->first], 0, scan->length);
1634 }
1635
1636 /* reset */
1637 queued_seq_count = 0;
1638 queued_seq_buf_end = 0;
1639 queued_seq_tdo_ptr = 0;
1640 pending_scan_result_count = 0;
1641 }
1642
1643 /* queue a sequence of bits to clock out TDI / in TDO, executing if the buffer is full.
1644 *
1645 * sequence=NULL means clock out zeros on TDI
1646 * tdo_buffer=NULL means don't capture TDO
1647 */
1648 static void cmsis_dap_add_jtag_sequence(unsigned int s_len, const uint8_t *sequence,
1649 unsigned int s_offset, bool tms,
1650 uint8_t *tdo_buffer, unsigned int tdo_buffer_offset)
1651 {
1652 LOG_DEBUG_IO("[at %d] %u bits, tms %s, seq offset %u, tdo buf %p, tdo offset %u",
1653 queued_seq_buf_end,
1654 s_len, tms ? "HIGH" : "LOW", s_offset, tdo_buffer, tdo_buffer_offset);
1655
1656 if (s_len == 0)
1657 return;
1658
1659 if (s_len > 64) {
1660 LOG_DEBUG_IO("START JTAG SEQ SPLIT");
1661 for (unsigned int offset = 0; offset < s_len; offset += 64) {
1662 unsigned int len = s_len - offset;
1663 if (len > 64)
1664 len = 64;
1665 LOG_DEBUG_IO("Splitting long jtag sequence: %u-bit chunk starting at offset %u", len, offset);
1666 cmsis_dap_add_jtag_sequence(
1667 len,
1668 sequence,
1669 s_offset + offset,
1670 tms,
1671 tdo_buffer,
1672 !tdo_buffer ? 0 : (tdo_buffer_offset + offset)
1673 );
1674 }
1675 LOG_DEBUG_IO("END JTAG SEQ SPLIT");
1676 return;
1677 }
1678
1679 unsigned int cmd_len = 1 + DIV_ROUND_UP(s_len, 8);
1680 if (queued_seq_count >= 255 || queued_seq_buf_end + cmd_len > QUEUED_SEQ_BUF_LEN)
1681 /* empty out the buffer */
1682 cmsis_dap_flush();
1683
1684 ++queued_seq_count;
1685
1686 /* control byte */
1687 queued_seq_buf[queued_seq_buf_end] =
1688 (tms ? DAP_JTAG_SEQ_TMS : 0) |
1689 (tdo_buffer ? DAP_JTAG_SEQ_TDO : 0) |
1690 (s_len == 64 ? 0 : s_len);
1691
1692 if (sequence)
1693 bit_copy(&queued_seq_buf[queued_seq_buf_end + 1], 0, sequence, s_offset, s_len);
1694 else
1695 memset(&queued_seq_buf[queued_seq_buf_end + 1], 0, DIV_ROUND_UP(s_len, 8));
1696
1697 queued_seq_buf_end += cmd_len;
1698
1699 if (tdo_buffer) {
1700 struct pending_scan_result *scan = &pending_scan_results[pending_scan_result_count++];
1701 scan->first = queued_seq_tdo_ptr;
1702 queued_seq_tdo_ptr += DIV_ROUND_UP(s_len, 8);
1703 scan->length = s_len;
1704 scan->buffer = tdo_buffer;
1705 scan->buffer_offset = tdo_buffer_offset;
1706 }
1707 }
1708
1709 /* queue a sequence of bits to clock out TMS, executing if the buffer is full */
1710 static void cmsis_dap_add_tms_sequence(const uint8_t *sequence, int s_len)
1711 {
1712 LOG_DEBUG_IO("%d bits: %02X", s_len, *sequence);
1713 /* we use a series of CMD_DAP_JTAG_SEQ commands to toggle TMS,
1714 because even though it seems ridiculously inefficient, it
1715 allows us to combine TMS and scan sequences into the same
1716 USB packet. */
1717 /* TODO: combine runs of the same tms value */
1718 for (int i = 0; i < s_len; ++i) {
1719 bool bit = (sequence[i / 8] & (1 << (i % 8))) != 0;
1720 cmsis_dap_add_jtag_sequence(1, NULL, 0, bit, NULL, 0);
1721 }
1722 }
1723
1724 /* Move to the end state by queuing a sequence to clock into TMS */
1725 static void cmsis_dap_state_move(void)
1726 {
1727 uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1728 uint8_t tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1729
1730 LOG_DEBUG_IO("state move from %s to %s: %d clocks, %02X on tms",
1731 tap_state_name(tap_get_state()), tap_state_name(tap_get_end_state()),
1732 tms_scan_bits, tms_scan);
1733 cmsis_dap_add_tms_sequence(&tms_scan, tms_scan_bits);
1734
1735 tap_set_state(tap_get_end_state());
1736 }
1737
1738
1739 /* Execute a JTAG scan operation by queueing TMS and TDI/TDO sequences */
1740 static void cmsis_dap_execute_scan(struct jtag_command *cmd)
1741 {
1742 LOG_DEBUG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
1743 jtag_scan_type(cmd->cmd.scan));
1744
1745 /* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
1746 while (cmd->cmd.scan->num_fields > 0
1747 && cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
1748 cmd->cmd.scan->num_fields--;
1749 LOG_DEBUG("discarding trailing empty field");
1750 }
1751
1752 if (cmd->cmd.scan->num_fields == 0) {
1753 LOG_DEBUG("empty scan, doing nothing");
1754 return;
1755 }
1756
1757 if (cmd->cmd.scan->ir_scan) {
1758 if (tap_get_state() != TAP_IRSHIFT) {
1759 cmsis_dap_end_state(TAP_IRSHIFT);
1760 cmsis_dap_state_move();
1761 }
1762 } else {
1763 if (tap_get_state() != TAP_DRSHIFT) {
1764 cmsis_dap_end_state(TAP_DRSHIFT);
1765 cmsis_dap_state_move();
1766 }
1767 }
1768
1769 cmsis_dap_end_state(cmd->cmd.scan->end_state);
1770
1771 struct scan_field *field = cmd->cmd.scan->fields;
1772 unsigned scan_size = 0;
1773
1774 for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
1775 scan_size += field->num_bits;
1776 LOG_DEBUG_IO("%s%s field %d/%d %d bits",
1777 field->in_value ? "in" : "",
1778 field->out_value ? "out" : "",
1779 i,
1780 cmd->cmd.scan->num_fields,
1781 field->num_bits);
1782
1783 if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
1784 LOG_DEBUG_IO("Last field and have to move out of SHIFT state");
1785 /* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
1786 * movement. This last field can't have length zero, it was checked above. */
1787 cmsis_dap_add_jtag_sequence(
1788 field->num_bits - 1, /* number of bits to clock */
1789 field->out_value, /* output sequence */
1790 0, /* output offset */
1791 false, /* TMS low */
1792 field->in_value,
1793 0);
1794
1795 /* Clock the last bit out, with TMS high */
1796 uint8_t last_bit = 0;
1797 if (field->out_value)
1798 bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
1799 cmsis_dap_add_jtag_sequence(
1800 1,
1801 &last_bit,
1802 0,
1803 true,
1804 field->in_value,
1805 field->num_bits - 1);
1806 tap_set_state(tap_state_transition(tap_get_state(), 1));
1807
1808 /* Now clock one more cycle, with TMS low, to get us into a PAUSE state */
1809 cmsis_dap_add_jtag_sequence(
1810 1,
1811 &last_bit,
1812 0,
1813 false,
1814 NULL,
1815 0);
1816 tap_set_state(tap_state_transition(tap_get_state(), 0));
1817 } else {
1818 LOG_DEBUG_IO("Internal field, staying in SHIFT state afterwards");
1819 /* Clocking part of a sequence into DR or IR with TMS=0,
1820 leaving TMS=0 at the end so we can continue later */
1821 cmsis_dap_add_jtag_sequence(
1822 field->num_bits,
1823 field->out_value,
1824 0,
1825 false,
1826 field->in_value,
1827 0);
1828 }
1829 }
1830
1831 if (tap_get_state() != tap_get_end_state()) {
1832 cmsis_dap_end_state(tap_get_end_state());
1833 cmsis_dap_state_move();
1834 }
1835
1836 LOG_DEBUG_IO("%s scan, %i bits, end in %s",
1837 (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1838 tap_state_name(tap_get_end_state()));
1839 }
1840
1841 static void cmsis_dap_pathmove(int num_states, tap_state_t *path)
1842 {
1843 uint8_t tms0 = 0x00;
1844 uint8_t tms1 = 0xff;
1845
1846 for (int i = 0; i < num_states; i++) {
1847 if (path[i] == tap_state_transition(tap_get_state(), false))
1848 cmsis_dap_add_tms_sequence(&tms0, 1);
1849 else if (path[i] == tap_state_transition(tap_get_state(), true))
1850 cmsis_dap_add_tms_sequence(&tms1, 1);
1851 else {
1852 LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
1853 tap_state_name(tap_get_state()), tap_state_name(path[i]));
1854 exit(-1);
1855 }
1856
1857 tap_set_state(path[i]);
1858 }
1859
1860 cmsis_dap_end_state(tap_get_state());
1861 }
1862
1863 static void cmsis_dap_execute_pathmove(struct jtag_command *cmd)
1864 {
1865 LOG_DEBUG_IO("pathmove: %i states, end in %i",
1866 cmd->cmd.pathmove->num_states,
1867 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
1868
1869 cmsis_dap_pathmove(cmd->cmd.pathmove->num_states, cmd->cmd.pathmove->path);
1870 }
1871
1872 static void cmsis_dap_stableclocks(int num_cycles)
1873 {
1874 uint8_t tms = tap_get_state() == TAP_RESET;
1875 /* TODO: Perform optimizations? */
1876 /* Execute num_cycles. */
1877 for (int i = 0; i < num_cycles; i++)
1878 cmsis_dap_add_tms_sequence(&tms, 1);
1879 }
1880
1881 static void cmsis_dap_runtest(int num_cycles)
1882 {
1883 tap_state_t saved_end_state = tap_get_end_state();
1884
1885 /* Only do a state_move when we're not already in IDLE. */
1886 if (tap_get_state() != TAP_IDLE) {
1887 cmsis_dap_end_state(TAP_IDLE);
1888 cmsis_dap_state_move();
1889 }
1890 cmsis_dap_stableclocks(num_cycles);
1891
1892 /* Finish in end_state. */
1893 cmsis_dap_end_state(saved_end_state);
1894
1895 if (tap_get_state() != tap_get_end_state())
1896 cmsis_dap_state_move();
1897 }
1898
1899 static void cmsis_dap_execute_runtest(struct jtag_command *cmd)
1900 {
1901 LOG_DEBUG_IO("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles,
1902 cmd->cmd.runtest->end_state);
1903
1904 cmsis_dap_end_state(cmd->cmd.runtest->end_state);
1905 cmsis_dap_runtest(cmd->cmd.runtest->num_cycles);
1906 }
1907
1908 static void cmsis_dap_execute_stableclocks(struct jtag_command *cmd)
1909 {
1910 LOG_DEBUG_IO("stableclocks %i cycles", cmd->cmd.runtest->num_cycles);
1911 cmsis_dap_stableclocks(cmd->cmd.runtest->num_cycles);
1912 }
1913
1914 static void cmsis_dap_execute_tms(struct jtag_command *cmd)
1915 {
1916 LOG_DEBUG_IO("TMS: %d bits", cmd->cmd.tms->num_bits);
1917 cmsis_dap_cmd_dap_swj_sequence(cmd->cmd.tms->num_bits, cmd->cmd.tms->bits);
1918 }
1919
1920 /* TODO: Is there need to call cmsis_dap_flush() for the JTAG_PATHMOVE,
1921 * JTAG_RUNTEST, JTAG_STABLECLOCKS? */
1922 static void cmsis_dap_execute_command(struct jtag_command *cmd)
1923 {
1924 switch (cmd->type) {
1925 case JTAG_SLEEP:
1926 cmsis_dap_flush();
1927 cmsis_dap_execute_sleep(cmd);
1928 break;
1929 case JTAG_TLR_RESET:
1930 cmsis_dap_flush();
1931 cmsis_dap_execute_tlr_reset(cmd);
1932 break;
1933 case JTAG_SCAN:
1934 cmsis_dap_execute_scan(cmd);
1935 break;
1936 case JTAG_PATHMOVE:
1937 cmsis_dap_execute_pathmove(cmd);
1938 break;
1939 case JTAG_RUNTEST:
1940 cmsis_dap_execute_runtest(cmd);
1941 break;
1942 case JTAG_STABLECLOCKS:
1943 cmsis_dap_execute_stableclocks(cmd);
1944 break;
1945 case JTAG_TMS:
1946 cmsis_dap_execute_tms(cmd);
1947 break;
1948 default:
1949 LOG_ERROR("BUG: unknown JTAG command type 0x%X encountered", cmd->type);
1950 exit(-1);
1951 }
1952 }
1953
1954 static int cmsis_dap_execute_queue(void)
1955 {
1956 struct jtag_command *cmd = jtag_command_queue;
1957
1958 while (cmd) {
1959 cmsis_dap_execute_command(cmd);
1960 cmd = cmd->next;
1961 }
1962
1963 cmsis_dap_flush();
1964
1965 return ERROR_OK;
1966 }
1967
1968 static int cmsis_dap_speed(int speed)
1969 {
1970 if (speed == 0) {
1971 LOG_ERROR("RTCK not supported. Set nonzero \"adapter speed\".");
1972 return ERROR_JTAG_NOT_IMPLEMENTED;
1973 }
1974
1975 return cmsis_dap_cmd_dap_swj_clock(speed);
1976 }
1977
1978 static int cmsis_dap_speed_div(int speed, int *khz)
1979 {
1980 *khz = speed;
1981 return ERROR_OK;
1982 }
1983
1984 static int cmsis_dap_khz(int khz, int *jtag_speed)
1985 {
1986 *jtag_speed = khz;
1987 return ERROR_OK;
1988 }
1989
1990 static bool calculate_swo_prescaler(unsigned int traceclkin_freq,
1991 uint32_t trace_freq, uint16_t *prescaler)
1992 {
1993 unsigned int presc = (traceclkin_freq + trace_freq / 2) / trace_freq;
1994 if (presc == 0 || presc > TPIU_ACPR_MAX_SWOSCALER + 1)
1995 return false;
1996
1997 /* Probe's UART speed must be within 3% of the TPIU's SWO baud rate. */
1998 unsigned int max_deviation = (traceclkin_freq * 3) / 100;
1999 if (presc * trace_freq < traceclkin_freq - max_deviation ||
2000 presc * trace_freq > traceclkin_freq + max_deviation)
2001 return false;
2002
2003 *prescaler = presc;
2004
2005 return true;
2006 }
2007
2008 /**
2009 * @see adapter_driver::config_trace
2010 */
2011 static int cmsis_dap_config_trace(
2012 bool trace_enabled,
2013 enum tpiu_pin_protocol pin_protocol,
2014 uint32_t port_size,
2015 unsigned int *swo_freq,
2016 unsigned int traceclkin_hz,
2017 uint16_t *swo_prescaler)
2018 {
2019 int retval;
2020
2021 if (!trace_enabled) {
2022 if (cmsis_dap_handle->trace_enabled) {
2023 retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_STOP);
2024 if (retval != ERROR_OK) {
2025 LOG_ERROR("Failed to disable the SWO-trace.");
2026 return retval;
2027 }
2028 }
2029 cmsis_dap_handle->trace_enabled = false;
2030 LOG_INFO("SWO-trace disabled.");
2031 return ERROR_OK;
2032 }
2033
2034 if (!(cmsis_dap_handle->caps & INFO_CAPS_SWO_UART) &&
2035 !(cmsis_dap_handle->caps & INFO_CAPS_SWO_MANCHESTER)) {
2036 LOG_ERROR("SWO-trace is not supported by the device.");
2037 return ERROR_FAIL;
2038 }
2039
2040 uint8_t swo_mode;
2041 if (pin_protocol == TPIU_PIN_PROTOCOL_ASYNC_UART &&
2042 (cmsis_dap_handle->caps & INFO_CAPS_SWO_UART)) {
2043 swo_mode = DAP_SWO_MODE_UART;
2044 } else if (pin_protocol == TPIU_PIN_PROTOCOL_ASYNC_MANCHESTER &&
2045 (cmsis_dap_handle->caps & INFO_CAPS_SWO_MANCHESTER)) {
2046 swo_mode = DAP_SWO_MODE_MANCHESTER;
2047 } else {
2048 LOG_ERROR("Selected pin protocol is not supported.");
2049 return ERROR_FAIL;
2050 }
2051
2052 if (*swo_freq == 0) {
2053 LOG_INFO("SWO-trace frequency autodetection not implemented.");
2054 return ERROR_FAIL;
2055 }
2056
2057 retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_STOP);
2058 if (retval != ERROR_OK)
2059 return retval;
2060
2061 cmsis_dap_handle->trace_enabled = false;
2062
2063 retval = cmsis_dap_get_swo_buf_sz(&cmsis_dap_handle->swo_buf_sz);
2064 if (retval != ERROR_OK)
2065 return retval;
2066
2067 retval = cmsis_dap_cmd_dap_swo_transport(DAP_SWO_TRANSPORT_DATA);
2068 if (retval != ERROR_OK)
2069 return retval;
2070
2071 retval = cmsis_dap_cmd_dap_swo_mode(swo_mode);
2072 if (retval != ERROR_OK)
2073 return retval;
2074
2075 retval = cmsis_dap_cmd_dap_swo_baudrate(*swo_freq, swo_freq);
2076 if (retval != ERROR_OK)
2077 return retval;
2078
2079 if (!calculate_swo_prescaler(traceclkin_hz, *swo_freq,
2080 swo_prescaler)) {
2081 LOG_ERROR("SWO frequency is not suitable. Please choose a "
2082 "different frequency or use auto-detection.");
2083 return ERROR_FAIL;
2084 }
2085
2086 LOG_INFO("SWO frequency: %u Hz.", *swo_freq);
2087 LOG_INFO("SWO prescaler: %u.", *swo_prescaler);
2088
2089 retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_START);
2090 if (retval != ERROR_OK)
2091 return retval;
2092
2093 cmsis_dap_handle->trace_enabled = true;
2094
2095 return ERROR_OK;
2096 }
2097
2098 /**
2099 * @see adapter_driver::poll_trace
2100 */
2101 static int cmsis_dap_poll_trace(uint8_t *buf, size_t *size)
2102 {
2103 uint8_t trace_status;
2104 size_t trace_count;
2105
2106 if (!cmsis_dap_handle->trace_enabled) {
2107 *size = 0;
2108 return ERROR_OK;
2109 }
2110
2111 int retval = cmsis_dap_cmd_dap_swo_status(&trace_status, &trace_count);
2112 if (retval != ERROR_OK)
2113 return retval;
2114 if ((trace_status & DAP_SWO_STATUS_CAPTURE_MASK) != DAP_SWO_STATUS_CAPTURE_ACTIVE)
2115 return ERROR_FAIL;
2116
2117 *size = trace_count < *size ? trace_count : *size;
2118 size_t read_so_far = 0;
2119 do {
2120 size_t rb = 0;
2121 uint32_t packet_size = cmsis_dap_handle->packet_size - 4 /*data-reply*/;
2122 uint32_t remaining = *size - read_so_far;
2123 if (remaining < packet_size)
2124 packet_size = remaining;
2125 retval = cmsis_dap_cmd_dap_swo_data(
2126 packet_size,
2127 &trace_status,
2128 &rb,
2129 &buf[read_so_far]);
2130 if (retval != ERROR_OK)
2131 return retval;
2132 if ((trace_status & DAP_SWO_STATUS_CAPTURE_MASK) != DAP_SWO_STATUS_CAPTURE_ACTIVE)
2133 return ERROR_FAIL;
2134
2135 read_so_far += rb;
2136 } while (read_so_far < *size);
2137
2138 return ERROR_OK;
2139 }
2140
2141 COMMAND_HANDLER(cmsis_dap_handle_info_command)
2142 {
2143 if (cmsis_dap_get_version_info() == ERROR_OK)
2144 cmsis_dap_get_status();
2145
2146 return ERROR_OK;
2147 }
2148
2149 COMMAND_HANDLER(cmsis_dap_handle_cmd_command)
2150 {
2151 uint8_t *command = cmsis_dap_handle->command;
2152
2153 for (unsigned i = 0; i < CMD_ARGC; i++)
2154 COMMAND_PARSE_NUMBER(u8, CMD_ARGV[i], command[i]);
2155
2156 int retval = cmsis_dap_xfer(cmsis_dap_handle, CMD_ARGC);
2157
2158 if (retval != ERROR_OK) {
2159 LOG_ERROR("CMSIS-DAP command failed.");
2160 return ERROR_JTAG_DEVICE_ERROR;
2161 }
2162
2163 uint8_t *resp = cmsis_dap_handle->response;
2164 LOG_INFO("Returned data %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8,
2165 resp[1], resp[2], resp[3], resp[4]);
2166
2167 return ERROR_OK;
2168 }
2169
2170 COMMAND_HANDLER(cmsis_dap_handle_vid_pid_command)
2171 {
2172 if (CMD_ARGC > MAX_USB_IDS * 2) {
2173 LOG_WARNING("ignoring extra IDs in cmsis-dap vid_pid "
2174 "(maximum is %d pairs)", MAX_USB_IDS);
2175 CMD_ARGC = MAX_USB_IDS * 2;
2176 }
2177 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
2178 LOG_WARNING("incomplete cmsis-dap vid_pid configuration directive");
2179 if (CMD_ARGC < 2)
2180 return ERROR_COMMAND_SYNTAX_ERROR;
2181 /* remove the incomplete trailing id */
2182 CMD_ARGC -= 1;
2183 }
2184
2185 unsigned i;
2186 for (i = 0; i < CMD_ARGC; i += 2) {
2187 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], cmsis_dap_vid[i >> 1]);
2188 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], cmsis_dap_pid[i >> 1]);
2189 }
2190
2191 /*
2192 * Explicitly terminate, in case there are multiples instances of
2193 * cmsis_dap_vid_pid.
2194 */
2195 cmsis_dap_vid[i >> 1] = cmsis_dap_pid[i >> 1] = 0;
2196
2197 return ERROR_OK;
2198 }
2199
2200 COMMAND_HANDLER(cmsis_dap_handle_backend_command)
2201 {
2202 if (CMD_ARGC == 1) {
2203 if (strcmp(CMD_ARGV[0], "auto") == 0) {
2204 cmsis_dap_backend = -1; /* autoselect */
2205 } else {
2206 for (unsigned int i = 0; i < ARRAY_SIZE(cmsis_dap_backends); i++) {
2207 if (strcasecmp(cmsis_dap_backends[i]->name, CMD_ARGV[0]) == 0) {
2208 cmsis_dap_backend = i;
2209 return ERROR_OK;
2210 }
2211 }
2212
2213 command_print(CMD, "invalid backend argument to cmsis-dap backend <backend>");
2214 return ERROR_COMMAND_ARGUMENT_INVALID;
2215 }
2216 } else {
2217 return ERROR_COMMAND_SYNTAX_ERROR;
2218 }
2219
2220 return ERROR_OK;
2221 }
2222
2223 static const struct command_registration cmsis_dap_subcommand_handlers[] = {
2224 {
2225 .name = "info",
2226 .handler = &cmsis_dap_handle_info_command,
2227 .mode = COMMAND_EXEC,
2228 .usage = "",
2229 .help = "show cmsis-dap info",
2230 },
2231 {
2232 .name = "cmd",
2233 .handler = &cmsis_dap_handle_cmd_command,
2234 .mode = COMMAND_EXEC,
2235 .usage = "",
2236 .help = "issue cmsis-dap command",
2237 },
2238 {
2239 .name = "vid_pid",
2240 .handler = &cmsis_dap_handle_vid_pid_command,
2241 .mode = COMMAND_CONFIG,
2242 .help = "the vendor ID and product ID of the CMSIS-DAP device",
2243 .usage = "(vid pid)*",
2244 },
2245 {
2246 .name = "backend",
2247 .handler = &cmsis_dap_handle_backend_command,
2248 .mode = COMMAND_CONFIG,
2249 .help = "set the communication backend to use (USB bulk or HID).",
2250 .usage = "(auto | usb_bulk | hid)",
2251 },
2252 #if BUILD_CMSIS_DAP_USB
2253 {
2254 .name = "usb",
2255 .chain = cmsis_dap_usb_subcommand_handlers,
2256 .mode = COMMAND_ANY,
2257 .help = "USB bulk backend-specific commands",
2258 .usage = "<cmd>",
2259 },
2260 #endif
2261 COMMAND_REGISTRATION_DONE
2262 };
2263
2264
2265 static const struct command_registration cmsis_dap_command_handlers[] = {
2266 {
2267 .name = "cmsis-dap",
2268 .mode = COMMAND_ANY,
2269 .help = "perform CMSIS-DAP management",
2270 .usage = "<cmd>",
2271 .chain = cmsis_dap_subcommand_handlers,
2272 },
2273 COMMAND_REGISTRATION_DONE
2274 };
2275
2276 static const struct swd_driver cmsis_dap_swd_driver = {
2277 .init = cmsis_dap_swd_init,
2278 .switch_seq = cmsis_dap_swd_switch_seq,
2279 .read_reg = cmsis_dap_swd_read_reg,
2280 .write_reg = cmsis_dap_swd_write_reg,
2281 .run = cmsis_dap_swd_run_queue,
2282 };
2283
2284 static const char * const cmsis_dap_transport[] = { "swd", "jtag", NULL };
2285
2286 static struct jtag_interface cmsis_dap_interface = {
2287 .supported = DEBUG_CAP_TMS_SEQ,
2288 .execute_queue = cmsis_dap_execute_queue,
2289 };
2290
2291 struct adapter_driver cmsis_dap_adapter_driver = {
2292 .name = "cmsis-dap",
2293 .transports = cmsis_dap_transport,
2294 .commands = cmsis_dap_command_handlers,
2295
2296 .init = cmsis_dap_init,
2297 .quit = cmsis_dap_quit,
2298 .reset = cmsis_dap_reset,
2299 .speed = cmsis_dap_speed,
2300 .khz = cmsis_dap_khz,
2301 .speed_div = cmsis_dap_speed_div,
2302 .config_trace = cmsis_dap_config_trace,
2303 .poll_trace = cmsis_dap_poll_trace,
2304
2305 .jtag_ops = &cmsis_dap_interface,
2306 .swd_ops = &cmsis_dap_swd_driver,
2307 };

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)