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

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)