jtag: linuxgpiod: drop extra parenthesis
[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 unsigned int packet_count = dap->quirk_mode ? 1 : dap->packet_count;
865 dap->pending_fifo_put_idx = (dap->pending_fifo_put_idx + 1) % packet_count;
866 dap->pending_fifo_block_count++;
867 if (dap->pending_fifo_block_count > packet_count)
868 LOG_ERROR("internal: too much pending writes %u", dap->pending_fifo_block_count);
869
870 return;
871
872 skip:
873 block->transfer_count = 0;
874 }
875
876 static void cmsis_dap_swd_read_process(struct cmsis_dap *dap, enum cmsis_dap_blocking blocking)
877 {
878 int retval;
879 struct pending_request_block *block = &dap->pending_fifo[dap->pending_fifo_get_idx];
880
881 if (dap->pending_fifo_block_count == 0) {
882 LOG_ERROR("internal: no pending write when reading?!");
883 return;
884 }
885
886 if (queued_retval != ERROR_OK) {
887 /* keep reading blocks until the pipeline is empty */
888 retval = dap->backend->read(dap, 10, NULL);
889 if (retval == ERROR_TIMEOUT_REACHED || retval == 0) {
890 /* timeout means that we flushed the pipeline,
891 * we can safely discard remaining pending requests */
892 cmsis_dap_swd_discard_all_pending(dap);
893 return;
894 }
895 goto skip;
896 }
897
898 /* get reply */
899 struct timeval tv = {
900 .tv_sec = 0,
901 .tv_usec = 0
902 };
903 retval = dap->backend->read(dap, LIBUSB_TIMEOUT_MS, blocking ? NULL : &tv);
904 bool timeout = (retval == ERROR_TIMEOUT_REACHED || retval == 0);
905 if (timeout && blocking == CMSIS_DAP_NON_BLOCKING)
906 return;
907
908 if (retval <= 0) {
909 LOG_DEBUG("error reading adapter response");
910 queued_retval = ERROR_FAIL;
911 if (timeout) {
912 /* timeout means that we flushed the pipeline,
913 * we can safely discard remaining pending requests */
914 cmsis_dap_swd_discard_all_pending(dap);
915 return;
916 }
917 goto skip;
918 }
919
920 uint8_t *resp = dap->response;
921 if (resp[0] != block->command) {
922 LOG_ERROR("CMSIS-DAP command mismatch. Expected 0x%x received 0x%" PRIx8,
923 block->command, resp[0]);
924 cmsis_dap_swd_cancel_transfers(dap);
925 queued_retval = ERROR_FAIL;
926 return;
927 }
928
929 unsigned int transfer_count;
930 unsigned int idx;
931 if (block->command == CMD_DAP_TFER_BLOCK) {
932 transfer_count = le_to_h_u16(&resp[1]);
933 idx = 3;
934 } else {
935 transfer_count = resp[1];
936 idx = 2;
937 }
938 if (resp[idx] & 0x08) {
939 LOG_DEBUG("CMSIS-DAP Protocol Error @ %d (wrong parity)", transfer_count);
940 queued_retval = ERROR_FAIL;
941 goto skip;
942 }
943 uint8_t ack = resp[idx++] & 0x07;
944 if (ack != SWD_ACK_OK) {
945 LOG_DEBUG("SWD ack not OK @ %d %s", transfer_count,
946 ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
947 queued_retval = swd_ack_to_error_code(ack);
948 /* TODO: use results of transfers completed before the error occurred? */
949 goto skip;
950 }
951
952 if (block->transfer_count != transfer_count) {
953 LOG_ERROR("CMSIS-DAP transfer count mismatch: expected %d, got %d",
954 block->transfer_count, transfer_count);
955 cmsis_dap_swd_cancel_transfers(dap);
956 queued_retval = ERROR_FAIL;
957 return;
958 }
959
960 LOG_DEBUG_IO("Received results of %d queued transactions FIFO index %u, %s mode",
961 transfer_count, dap->pending_fifo_get_idx,
962 blocking ? "blocking" : "nonblocking");
963
964 for (unsigned int i = 0; i < transfer_count; i++) {
965 struct pending_transfer_result *transfer = &(block->transfers[i]);
966 if (transfer->cmd & SWD_CMD_RNW) {
967 static uint32_t last_read;
968 uint32_t data = le_to_h_u32(&resp[idx]);
969 uint32_t tmp = data;
970 idx += 4;
971
972 LOG_DEBUG_IO("Read result: %" PRIx32, data);
973
974 /* Imitate posted AP reads */
975 if ((transfer->cmd & SWD_CMD_APNDP) ||
976 ((transfer->cmd & SWD_CMD_A32) >> 1 == DP_RDBUFF)) {
977 tmp = last_read;
978 last_read = data;
979 }
980
981 if (transfer->buffer)
982 *(uint32_t *)(transfer->buffer) = tmp;
983 }
984 }
985
986 skip:
987 block->transfer_count = 0;
988 if (!dap->quirk_mode && dap->packet_count > 1)
989 dap->pending_fifo_get_idx = (dap->pending_fifo_get_idx + 1) % dap->packet_count;
990 dap->pending_fifo_block_count--;
991 }
992
993 static int cmsis_dap_swd_run_queue(void)
994 {
995 if (cmsis_dap_handle->write_count + cmsis_dap_handle->read_count) {
996 if (cmsis_dap_handle->pending_fifo_block_count)
997 cmsis_dap_swd_read_process(cmsis_dap_handle, CMSIS_DAP_NON_BLOCKING);
998
999 cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
1000 }
1001
1002 while (cmsis_dap_handle->pending_fifo_block_count)
1003 cmsis_dap_swd_read_process(cmsis_dap_handle, CMSIS_DAP_BLOCKING);
1004
1005 cmsis_dap_handle->pending_fifo_put_idx = 0;
1006 cmsis_dap_handle->pending_fifo_get_idx = 0;
1007
1008 int retval = queued_retval;
1009 queued_retval = ERROR_OK;
1010
1011 return retval;
1012 }
1013
1014 static unsigned int cmsis_dap_tfer_cmd_size(unsigned int write_count,
1015 unsigned int read_count, bool block_tfer)
1016 {
1017 unsigned int size;
1018 if (block_tfer) {
1019 size = 5; /* DAP_TransferBlock header */
1020 size += write_count * 4; /* data */
1021 } else {
1022 size = 3; /* DAP_Transfer header */
1023 size += write_count * (1 + 4); /* DAP register + data */
1024 size += read_count; /* DAP register */
1025 }
1026 return size;
1027 }
1028
1029 static unsigned int cmsis_dap_tfer_resp_size(unsigned int write_count,
1030 unsigned int read_count, bool block_tfer)
1031 {
1032 unsigned int size;
1033 if (block_tfer)
1034 size = 4; /* DAP_TransferBlock response header */
1035 else
1036 size = 3; /* DAP_Transfer response header */
1037
1038 size += read_count * 4; /* data */
1039 return size;
1040 }
1041
1042 static void cmsis_dap_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data)
1043 {
1044 /* TARGETSEL register write cannot be queued */
1045 if (swd_cmd(false, false, DP_TARGETSEL) == cmd) {
1046 queued_retval = cmsis_dap_swd_run_queue();
1047
1048 cmsis_dap_metacmd_targetsel(data);
1049 return;
1050 }
1051
1052 /* Compute sizes of the DAP Transfer command and the expected response
1053 * for all queued and this operation */
1054 unsigned int write_count = cmsis_dap_handle->write_count;
1055 unsigned int read_count = cmsis_dap_handle->read_count;
1056 bool block_cmd;
1057 if (write_count + read_count < CMD_DAP_TFER_BLOCK_MIN_OPS)
1058 block_cmd = false;
1059 else
1060 block_cmd = !cmsis_dap_handle->swd_cmds_differ
1061 && cmd == cmsis_dap_handle->common_swd_cmd;
1062
1063 if (cmd & SWD_CMD_RNW)
1064 read_count++;
1065 else
1066 write_count++;
1067
1068 unsigned int cmd_size = cmsis_dap_tfer_cmd_size(write_count, read_count,
1069 block_cmd);
1070 unsigned int resp_size = cmsis_dap_tfer_resp_size(write_count, read_count,
1071 block_cmd);
1072 unsigned int max_transfer_count = block_cmd ? 65535 : 255;
1073
1074 /* Does the DAP Transfer command and also its expected response fit into one packet? */
1075 if (cmd_size > tfer_max_command_size
1076 || resp_size > tfer_max_response_size
1077 || write_count + read_count > max_transfer_count) {
1078 if (cmsis_dap_handle->pending_fifo_block_count)
1079 cmsis_dap_swd_read_process(cmsis_dap_handle, CMSIS_DAP_NON_BLOCKING);
1080
1081 /* Not enough room in the queue. Run the queue. */
1082 cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
1083
1084 unsigned int packet_count = cmsis_dap_handle->quirk_mode ? 1 : cmsis_dap_handle->packet_count;
1085 if (cmsis_dap_handle->pending_fifo_block_count >= packet_count)
1086 cmsis_dap_swd_read_process(cmsis_dap_handle, CMSIS_DAP_BLOCKING);
1087 }
1088
1089 assert(cmsis_dap_handle->pending_fifo[cmsis_dap_handle->pending_fifo_put_idx].transfer_count < pending_queue_len);
1090
1091 if (queued_retval != ERROR_OK)
1092 return;
1093
1094 struct pending_request_block *block = &cmsis_dap_handle->pending_fifo[cmsis_dap_handle->pending_fifo_put_idx];
1095 struct pending_transfer_result *transfer = &(block->transfers[block->transfer_count]);
1096 transfer->data = data;
1097 transfer->cmd = cmd;
1098 if (block->transfer_count == 0) {
1099 cmsis_dap_handle->swd_cmds_differ = false;
1100 cmsis_dap_handle->common_swd_cmd = cmd;
1101 } else if (cmd != cmsis_dap_handle->common_swd_cmd) {
1102 cmsis_dap_handle->swd_cmds_differ = true;
1103 }
1104
1105 if (cmd & SWD_CMD_RNW) {
1106 /* Queue a read transaction */
1107 transfer->buffer = dst;
1108 cmsis_dap_handle->read_count++;
1109 } else {
1110 cmsis_dap_handle->write_count++;
1111 }
1112 block->transfer_count++;
1113 }
1114
1115 static void cmsis_dap_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
1116 {
1117 assert(!(cmd & SWD_CMD_RNW));
1118 cmsis_dap_swd_queue_cmd(cmd, NULL, value);
1119 }
1120
1121 static void cmsis_dap_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
1122 {
1123 assert(cmd & SWD_CMD_RNW);
1124 cmsis_dap_swd_queue_cmd(cmd, value, 0);
1125 }
1126
1127 static int cmsis_dap_get_serial_info(void)
1128 {
1129 uint8_t *data;
1130
1131 int retval = cmsis_dap_cmd_dap_info(INFO_ID_SERNUM, &data);
1132 if (retval != ERROR_OK)
1133 return retval;
1134
1135 if (data[0]) /* strlen */
1136 LOG_INFO("CMSIS-DAP: Serial# = %s", &data[1]);
1137
1138 return ERROR_OK;
1139 }
1140
1141 static int cmsis_dap_get_version_info(void)
1142 {
1143 uint8_t *data;
1144
1145 /* INFO_ID_FW_VER - string */
1146 int retval = cmsis_dap_cmd_dap_info(INFO_ID_FW_VER, &data);
1147 if (retval != ERROR_OK)
1148 return retval;
1149
1150 if (data[0]) /* strlen */
1151 LOG_INFO("CMSIS-DAP: FW Version = %s", &data[1]);
1152
1153 return ERROR_OK;
1154 }
1155
1156 static int cmsis_dap_get_caps_info(void)
1157 {
1158 uint8_t *data;
1159
1160 /* INFO_ID_CAPS - byte */
1161 int retval = cmsis_dap_cmd_dap_info(INFO_ID_CAPS, &data);
1162 if (retval != ERROR_OK)
1163 return retval;
1164
1165 if (data[0] == 1 || data[0] == 2) {
1166 uint16_t caps = data[1];
1167 if (data[0] == 2)
1168 caps |= (uint16_t)data[2] << 8;
1169
1170 cmsis_dap_handle->caps = caps;
1171
1172 for (unsigned int i = 0; i < INFO_CAPS__NUM_CAPS; ++i) {
1173 if (caps & BIT(i))
1174 LOG_INFO("CMSIS-DAP: %s", info_caps_str[i]);
1175 }
1176 }
1177
1178 return ERROR_OK;
1179 }
1180
1181 static int cmsis_dap_get_swo_buf_sz(uint32_t *swo_buf_sz)
1182 {
1183 uint8_t *data;
1184
1185 /* INFO_ID_SWO_BUF_SZ - word */
1186 int retval = cmsis_dap_cmd_dap_info(INFO_ID_SWO_BUF_SZ, &data);
1187 if (retval != ERROR_OK)
1188 return retval;
1189
1190 if (data[0] != 4)
1191 return ERROR_FAIL;
1192
1193 *swo_buf_sz = le_to_h_u32(&data[1]);
1194
1195 LOG_INFO("CMSIS-DAP: SWO Trace Buffer Size = %u bytes", *swo_buf_sz);
1196
1197 return ERROR_OK;
1198 }
1199
1200 static int cmsis_dap_get_status(void)
1201 {
1202 uint8_t d;
1203
1204 int retval = cmsis_dap_cmd_dap_swj_pins(0, 0, 0, &d);
1205
1206 if (retval == ERROR_OK) {
1207 LOG_INFO("SWCLK/TCK = %d SWDIO/TMS = %d TDI = %d TDO = %d nTRST = %d nRESET = %d",
1208 (d & SWJ_PIN_TCK) ? 1 : 0,
1209 (d & SWJ_PIN_TMS) ? 1 : 0,
1210 (d & SWJ_PIN_TDI) ? 1 : 0,
1211 (d & SWJ_PIN_TDO) ? 1 : 0,
1212 (d & SWJ_PIN_TRST) ? 1 : 0,
1213 (d & SWJ_PIN_SRST) ? 1 : 0);
1214 }
1215
1216 return retval;
1217 }
1218
1219 static int cmsis_dap_swd_switch_seq(enum swd_special_seq seq)
1220 {
1221 const uint8_t *s;
1222 unsigned int s_len;
1223 int retval;
1224
1225 if (swd_mode)
1226 queued_retval = cmsis_dap_swd_run_queue();
1227
1228 if (cmsis_dap_handle->quirk_mode && seq != LINE_RESET &&
1229 (output_pins & (SWJ_PIN_SRST | SWJ_PIN_TRST))
1230 == (SWJ_PIN_SRST | SWJ_PIN_TRST)) {
1231 /* Following workaround deasserts reset on most adapters.
1232 * Do not reconnect if a reset line is active!
1233 * Reconnecting would break connecting under reset. */
1234
1235 /* First disconnect before connecting, Atmel EDBG needs it for SAMD/R/L/C */
1236 cmsis_dap_cmd_dap_disconnect();
1237
1238 /* When we are reconnecting, DAP_Connect needs to be rerun, at
1239 * least on Keil ULINK-ME */
1240 retval = cmsis_dap_cmd_dap_connect(CONNECT_SWD);
1241 if (retval != ERROR_OK)
1242 return retval;
1243 }
1244
1245 switch (seq) {
1246 case LINE_RESET:
1247 LOG_DEBUG_IO("SWD line reset");
1248 s = swd_seq_line_reset;
1249 s_len = swd_seq_line_reset_len;
1250 break;
1251 case JTAG_TO_SWD:
1252 LOG_DEBUG("JTAG-to-SWD");
1253 s = swd_seq_jtag_to_swd;
1254 s_len = swd_seq_jtag_to_swd_len;
1255 break;
1256 case JTAG_TO_DORMANT:
1257 LOG_DEBUG("JTAG-to-DORMANT");
1258 s = swd_seq_jtag_to_dormant;
1259 s_len = swd_seq_jtag_to_dormant_len;
1260 break;
1261 case SWD_TO_JTAG:
1262 LOG_DEBUG("SWD-to-JTAG");
1263 s = swd_seq_swd_to_jtag;
1264 s_len = swd_seq_swd_to_jtag_len;
1265 break;
1266 case SWD_TO_DORMANT:
1267 LOG_DEBUG("SWD-to-DORMANT");
1268 s = swd_seq_swd_to_dormant;
1269 s_len = swd_seq_swd_to_dormant_len;
1270 break;
1271 case DORMANT_TO_SWD:
1272 LOG_DEBUG("DORMANT-to-SWD");
1273 s = swd_seq_dormant_to_swd;
1274 s_len = swd_seq_dormant_to_swd_len;
1275 break;
1276 case DORMANT_TO_JTAG:
1277 LOG_DEBUG("DORMANT-to-JTAG");
1278 s = swd_seq_dormant_to_jtag;
1279 s_len = swd_seq_dormant_to_jtag_len;
1280 break;
1281 default:
1282 LOG_ERROR("Sequence %d not supported", seq);
1283 return ERROR_FAIL;
1284 }
1285
1286 retval = cmsis_dap_cmd_dap_swj_sequence(s_len, s);
1287 if (retval != ERROR_OK)
1288 return retval;
1289
1290 /* Atmel EDBG needs renew clock setting after SWJ_Sequence
1291 * otherwise default frequency is used */
1292 return cmsis_dap_cmd_dap_swj_clock(adapter_get_speed_khz());
1293 }
1294
1295 static int cmsis_dap_swd_open(void)
1296 {
1297 if (!(cmsis_dap_handle->caps & INFO_CAPS_SWD)) {
1298 LOG_ERROR("CMSIS-DAP: SWD not supported");
1299 return ERROR_JTAG_DEVICE_ERROR;
1300 }
1301
1302 int retval = cmsis_dap_cmd_dap_connect(CONNECT_SWD);
1303 if (retval != ERROR_OK)
1304 return retval;
1305
1306 /* Add more setup here.??... */
1307
1308 LOG_INFO("CMSIS-DAP: Interface Initialised (SWD)");
1309 return ERROR_OK;
1310 }
1311
1312 static int cmsis_dap_init(void)
1313 {
1314 uint8_t *data;
1315
1316 int retval = cmsis_dap_open();
1317 if (retval != ERROR_OK)
1318 return retval;
1319
1320 cmsis_dap_flush_read(cmsis_dap_handle);
1321
1322 retval = cmsis_dap_get_caps_info();
1323 if (retval != ERROR_OK)
1324 return retval;
1325
1326 retval = cmsis_dap_get_version_info();
1327 if (retval != ERROR_OK)
1328 return retval;
1329
1330 retval = cmsis_dap_get_serial_info();
1331 if (retval != ERROR_OK)
1332 return retval;
1333
1334 if (swd_mode) {
1335 retval = cmsis_dap_swd_open();
1336 if (retval != ERROR_OK)
1337 return retval;
1338 } else {
1339 /* Connect in JTAG mode */
1340 if (!(cmsis_dap_handle->caps & INFO_CAPS_JTAG)) {
1341 LOG_ERROR("CMSIS-DAP: JTAG not supported");
1342 return ERROR_JTAG_DEVICE_ERROR;
1343 }
1344
1345 retval = cmsis_dap_cmd_dap_connect(CONNECT_JTAG);
1346 if (retval != ERROR_OK)
1347 return retval;
1348
1349 LOG_INFO("CMSIS-DAP: Interface Initialised (JTAG)");
1350 }
1351
1352 /* Be conservative and suppress submitting multiple HID requests
1353 * until we get packet count info from the adaptor */
1354 cmsis_dap_handle->packet_count = 1;
1355
1356 /* INFO_ID_PKT_SZ - short */
1357 retval = cmsis_dap_cmd_dap_info(INFO_ID_PKT_SZ, &data);
1358 if (retval != ERROR_OK)
1359 goto init_err;
1360
1361 if (data[0] == 2) { /* short */
1362 uint16_t pkt_sz = data[1] + (data[2] << 8);
1363 if (pkt_sz != cmsis_dap_handle->packet_size) {
1364 cmsis_dap_handle->backend->packet_buffer_free(cmsis_dap_handle);
1365 retval = cmsis_dap_handle->backend->packet_buffer_alloc(cmsis_dap_handle, pkt_sz);
1366 if (retval != ERROR_OK)
1367 goto init_err;
1368
1369 LOG_DEBUG("CMSIS-DAP: Packet Size = %" PRIu16, pkt_sz);
1370 }
1371 }
1372
1373 /* Maximal number of transfers which fit to one packet:
1374 * Limited by response size: 3 bytes of response header + 4 per read
1375 * Plus writes to full command size: 3 bytes cmd header + 1 per read + 5 per write */
1376 tfer_max_command_size = cmsis_dap_handle->packet_usable_size;
1377 tfer_max_response_size = cmsis_dap_handle->packet_usable_size;
1378 unsigned int max_reads = tfer_max_response_size / 4;
1379 pending_queue_len = max_reads + (tfer_max_command_size - max_reads) / 5;
1380 cmsis_dap_handle->write_count = 0;
1381 cmsis_dap_handle->read_count = 0;
1382
1383 /* INFO_ID_PKT_CNT - byte */
1384 retval = cmsis_dap_cmd_dap_info(INFO_ID_PKT_CNT, &data);
1385 if (retval != ERROR_OK)
1386 goto init_err;
1387
1388 if (data[0] == 1) { /* byte */
1389 unsigned int pkt_cnt = data[1];
1390 if (pkt_cnt > 1)
1391 cmsis_dap_handle->packet_count = MIN(MAX_PENDING_REQUESTS, pkt_cnt);
1392
1393 LOG_DEBUG("CMSIS-DAP: Packet Count = %u", pkt_cnt);
1394 }
1395
1396 LOG_DEBUG("Allocating FIFO for %u pending packets", cmsis_dap_handle->packet_count);
1397 for (unsigned int i = 0; i < cmsis_dap_handle->packet_count; i++) {
1398 cmsis_dap_handle->pending_fifo[i].transfers = malloc(pending_queue_len
1399 * sizeof(struct pending_transfer_result));
1400 if (!cmsis_dap_handle->pending_fifo[i].transfers) {
1401 LOG_ERROR("Unable to allocate memory for CMSIS-DAP queue");
1402 retval = ERROR_FAIL;
1403 goto init_err;
1404 }
1405 }
1406
1407 /* Intentionally not checked for error, just logs an info message
1408 * not vital for further debugging */
1409 (void)cmsis_dap_get_status();
1410
1411 /* Now try to connect to the target
1412 * TODO: This is all SWD only @ present */
1413 retval = cmsis_dap_cmd_dap_swj_clock(adapter_get_speed_khz());
1414 if (retval != ERROR_OK)
1415 goto init_err;
1416
1417 /* Ask CMSIS-DAP to automatically retry on receiving WAIT for
1418 * up to 64 times. This must be changed to 0 if sticky
1419 * overrun detection is enabled. */
1420 retval = cmsis_dap_cmd_dap_tfer_configure(0, 64, 0);
1421 if (retval != ERROR_OK)
1422 goto init_err;
1423
1424 if (swd_mode) {
1425 /* Data Phase (bit 2) must be set to 1 if sticky overrun
1426 * detection is enabled */
1427 retval = cmsis_dap_cmd_dap_swd_configure(0); /* 1 TRN, no Data Phase */
1428 if (retval != ERROR_OK)
1429 goto init_err;
1430 }
1431 /* Both LEDs on */
1432 /* Intentionally not checked for error, debugging will work
1433 * without LEDs */
1434 (void)cmsis_dap_cmd_dap_led(LED_ID_CONNECT, LED_ON);
1435 (void)cmsis_dap_cmd_dap_led(LED_ID_RUN, LED_ON);
1436
1437 /* support connecting with srst asserted */
1438 enum reset_types jtag_reset_config = jtag_get_reset_config();
1439
1440 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
1441 if (jtag_reset_config & RESET_SRST_NO_GATING) {
1442 retval = cmsis_dap_cmd_dap_swj_pins(0, SWJ_PIN_SRST, 0, NULL);
1443 if (retval != ERROR_OK)
1444 goto init_err;
1445 LOG_INFO("Connecting under reset");
1446 }
1447 }
1448 LOG_INFO("CMSIS-DAP: Interface ready");
1449 return ERROR_OK;
1450
1451 init_err:
1452 cmsis_dap_quit();
1453 return retval;
1454 }
1455
1456 static int cmsis_dap_swd_init(void)
1457 {
1458 swd_mode = true;
1459 return ERROR_OK;
1460 }
1461
1462 static int cmsis_dap_quit(void)
1463 {
1464 cmsis_dap_cmd_dap_disconnect();
1465
1466 /* Both LEDs off */
1467 cmsis_dap_cmd_dap_led(LED_ID_RUN, LED_OFF);
1468 cmsis_dap_cmd_dap_led(LED_ID_CONNECT, LED_OFF);
1469
1470 cmsis_dap_close(cmsis_dap_handle);
1471
1472 return ERROR_OK;
1473 }
1474
1475 static int cmsis_dap_reset(int trst, int srst)
1476 {
1477 /* Set both TRST and SRST even if they're not enabled as
1478 * there's no way to tristate them */
1479
1480 output_pins = 0;
1481 if (!srst)
1482 output_pins |= SWJ_PIN_SRST;
1483 if (!trst)
1484 output_pins |= SWJ_PIN_TRST;
1485
1486 int retval = cmsis_dap_cmd_dap_swj_pins(output_pins,
1487 SWJ_PIN_TRST | SWJ_PIN_SRST, 0, NULL);
1488 if (retval != ERROR_OK)
1489 LOG_ERROR("CMSIS-DAP: Interface reset failed");
1490 return retval;
1491 }
1492
1493 static void cmsis_dap_execute_sleep(struct jtag_command *cmd)
1494 {
1495 #if 0
1496 int retval = cmsis_dap_cmd_dap_delay(cmd->cmd.sleep->us);
1497 if (retval != ERROR_OK)
1498 #endif
1499 jtag_sleep(cmd->cmd.sleep->us);
1500 }
1501
1502 /* Set TMS high for five TCK clocks, to move the TAP to the Test-Logic-Reset state */
1503 static int cmsis_dap_execute_tlr_reset(struct jtag_command *cmd)
1504 {
1505 LOG_INFO("cmsis-dap JTAG TLR_RESET");
1506 uint8_t seq = 0xff;
1507
1508 int retval = cmsis_dap_cmd_dap_swj_sequence(8, &seq);
1509 if (retval == ERROR_OK)
1510 tap_set_state(TAP_RESET);
1511 return retval;
1512 }
1513
1514 /* Set new end state */
1515 static void cmsis_dap_end_state(tap_state_t state)
1516 {
1517 if (tap_is_state_stable(state))
1518 tap_set_end_state(state);
1519 else {
1520 LOG_ERROR("BUG: %i is not a valid end state", state);
1521 exit(-1);
1522 }
1523 }
1524
1525 #ifdef SPRINT_BINARY
1526 static void sprint_binary(char *s, const uint8_t *buf, unsigned int offset, unsigned int len)
1527 {
1528 if (!len)
1529 return;
1530
1531 /*
1532 buf = { 0x18 } len=5 should result in: 11000
1533 buf = { 0xff 0x18 } len=13 should result in: 11111111 11000
1534 buf = { 0xc0 0x18 } offset=3 len=10 should result in: 11000 11000
1535 i=3 there means i/8 = 0 so c = 0xFF, and
1536 */
1537 for (unsigned int i = offset; i < offset + len; ++i) {
1538 uint8_t c = buf[i / 8], mask = 1 << (i % 8);
1539 if ((i != offset) && !(i % 8))
1540 putchar(' ');
1541 *s++ = (c & mask) ? '1' : '0';
1542 }
1543 *s = 0;
1544 }
1545 #endif
1546
1547 #ifdef CMSIS_DAP_JTAG_DEBUG
1548 static void debug_parse_cmsis_buf(const uint8_t *cmd, int cmdlen)
1549 {
1550 /* cmd is a usb packet to go to the cmsis-dap interface */
1551 printf("cmsis-dap buffer (%d b): ", cmdlen);
1552 for (int i = 0; i < cmdlen; ++i)
1553 printf(" %02x", cmd[i]);
1554 printf("\n");
1555 switch (cmd[0]) {
1556 case CMD_DAP_JTAG_SEQ: {
1557 printf("cmsis-dap jtag sequence command %02x (n=%d)\n", cmd[0], cmd[1]);
1558 /*
1559 * #1 = number of sequences
1560 * #2 = sequence info 1
1561 * #3...4+n_bytes-1 = sequence 1
1562 * #4+n_bytes = sequence info 2
1563 * #5+n_bytes = sequence 2 (single bit)
1564 */
1565 int pos = 2;
1566 for (int seq = 0; seq < cmd[1]; ++seq) {
1567 uint8_t info = cmd[pos++];
1568 int len = info & DAP_JTAG_SEQ_TCK;
1569 if (len == 0)
1570 len = 64;
1571 printf(" sequence %d starting %d: info %02x (len=%d tms=%d read_tdo=%d): ",
1572 seq, pos, info, len, info & DAP_JTAG_SEQ_TMS, info & DAP_JTAG_SEQ_TDO);
1573 for (int i = 0; i < DIV_ROUND_UP(len, 8); ++i)
1574 printf(" %02x", cmd[pos+i]);
1575 pos += DIV_ROUND_UP(len, 8);
1576 printf("\n");
1577 }
1578 if (pos != cmdlen) {
1579 printf("BUFFER LENGTH MISMATCH looks like %d but %d specified", pos, cmdlen);
1580 exit(-1);
1581 }
1582
1583 break;
1584 }
1585 default:
1586 LOG_DEBUG("unknown cmsis-dap command %02x", cmd[1]);
1587 break;
1588 }
1589 }
1590 #endif
1591
1592 static void cmsis_dap_flush(void)
1593 {
1594 if (!queued_seq_count)
1595 return;
1596
1597 LOG_DEBUG_IO("Flushing %d queued sequences (%d bytes) with %d pending scan results to capture",
1598 queued_seq_count, queued_seq_buf_end, pending_scan_result_count);
1599
1600 /* prepare CMSIS-DAP packet */
1601 uint8_t *command = cmsis_dap_handle->command;
1602 command[0] = CMD_DAP_JTAG_SEQ;
1603 command[1] = queued_seq_count;
1604 memcpy(&command[2], queued_seq_buf, queued_seq_buf_end);
1605
1606 #ifdef CMSIS_DAP_JTAG_DEBUG
1607 debug_parse_cmsis_buf(command, queued_seq_buf_end + 2);
1608 #endif
1609
1610 /* send command to USB device */
1611 int retval = cmsis_dap_xfer(cmsis_dap_handle, queued_seq_buf_end + 2);
1612
1613 uint8_t *resp = cmsis_dap_handle->response;
1614 if (retval != ERROR_OK || resp[1] != DAP_OK) {
1615 LOG_ERROR("CMSIS-DAP command CMD_DAP_JTAG_SEQ failed.");
1616 exit(-1);
1617 }
1618
1619 #ifdef CMSIS_DAP_JTAG_DEBUG
1620 LOG_DEBUG_IO("USB response buf:");
1621 for (int c = 0; c < queued_seq_buf_end + 3; ++c)
1622 printf("%02X ", resp[c]);
1623 printf("\n");
1624 #endif
1625
1626 /* copy scan results into client buffers */
1627 for (int i = 0; i < pending_scan_result_count; ++i) {
1628 struct pending_scan_result *scan = &pending_scan_results[i];
1629 LOG_DEBUG_IO("Copying pending_scan_result %d/%d: %d bits from byte %d -> buffer + %d bits",
1630 i, pending_scan_result_count, scan->length, scan->first + 2, scan->buffer_offset);
1631 #ifdef CMSIS_DAP_JTAG_DEBUG
1632 for (uint32_t b = 0; b < DIV_ROUND_UP(scan->length, 8); ++b)
1633 printf("%02X ", resp[2+scan->first+b]);
1634 printf("\n");
1635 #endif
1636 bit_copy(scan->buffer, scan->buffer_offset, &resp[2 + scan->first], 0, scan->length);
1637 }
1638
1639 /* reset */
1640 queued_seq_count = 0;
1641 queued_seq_buf_end = 0;
1642 queued_seq_tdo_ptr = 0;
1643 pending_scan_result_count = 0;
1644 }
1645
1646 /* queue a sequence of bits to clock out TDI / in TDO, executing if the buffer is full.
1647 *
1648 * sequence=NULL means clock out zeros on TDI
1649 * tdo_buffer=NULL means don't capture TDO
1650 */
1651 static void cmsis_dap_add_jtag_sequence(unsigned int s_len, const uint8_t *sequence,
1652 unsigned int s_offset, bool tms,
1653 uint8_t *tdo_buffer, unsigned int tdo_buffer_offset)
1654 {
1655 LOG_DEBUG_IO("[at %d] %u bits, tms %s, seq offset %u, tdo buf %p, tdo offset %u",
1656 queued_seq_buf_end,
1657 s_len, tms ? "HIGH" : "LOW", s_offset, tdo_buffer, tdo_buffer_offset);
1658
1659 if (s_len == 0)
1660 return;
1661
1662 if (s_len > 64) {
1663 LOG_DEBUG_IO("START JTAG SEQ SPLIT");
1664 for (unsigned int offset = 0; offset < s_len; offset += 64) {
1665 unsigned int len = s_len - offset;
1666 if (len > 64)
1667 len = 64;
1668 LOG_DEBUG_IO("Splitting long jtag sequence: %u-bit chunk starting at offset %u", len, offset);
1669 cmsis_dap_add_jtag_sequence(
1670 len,
1671 sequence,
1672 s_offset + offset,
1673 tms,
1674 tdo_buffer,
1675 !tdo_buffer ? 0 : (tdo_buffer_offset + offset)
1676 );
1677 }
1678 LOG_DEBUG_IO("END JTAG SEQ SPLIT");
1679 return;
1680 }
1681
1682 unsigned int cmd_len = 1 + DIV_ROUND_UP(s_len, 8);
1683 if (queued_seq_count >= 255 || queued_seq_buf_end + cmd_len > QUEUED_SEQ_BUF_LEN)
1684 /* empty out the buffer */
1685 cmsis_dap_flush();
1686
1687 ++queued_seq_count;
1688
1689 /* control byte */
1690 queued_seq_buf[queued_seq_buf_end] =
1691 (tms ? DAP_JTAG_SEQ_TMS : 0) |
1692 (tdo_buffer ? DAP_JTAG_SEQ_TDO : 0) |
1693 (s_len == 64 ? 0 : s_len);
1694
1695 if (sequence)
1696 bit_copy(&queued_seq_buf[queued_seq_buf_end + 1], 0, sequence, s_offset, s_len);
1697 else
1698 memset(&queued_seq_buf[queued_seq_buf_end + 1], 0, DIV_ROUND_UP(s_len, 8));
1699
1700 queued_seq_buf_end += cmd_len;
1701
1702 if (tdo_buffer) {
1703 struct pending_scan_result *scan = &pending_scan_results[pending_scan_result_count++];
1704 scan->first = queued_seq_tdo_ptr;
1705 queued_seq_tdo_ptr += DIV_ROUND_UP(s_len, 8);
1706 scan->length = s_len;
1707 scan->buffer = tdo_buffer;
1708 scan->buffer_offset = tdo_buffer_offset;
1709 }
1710 }
1711
1712 /* queue a sequence of bits to clock out TMS, executing if the buffer is full */
1713 static void cmsis_dap_add_tms_sequence(const uint8_t *sequence, int s_len)
1714 {
1715 LOG_DEBUG_IO("%d bits: %02X", s_len, *sequence);
1716 /* we use a series of CMD_DAP_JTAG_SEQ commands to toggle TMS,
1717 because even though it seems ridiculously inefficient, it
1718 allows us to combine TMS and scan sequences into the same
1719 USB packet. */
1720 /* TODO: combine runs of the same tms value */
1721 for (int i = 0; i < s_len; ++i) {
1722 bool bit = (sequence[i / 8] & (1 << (i % 8))) != 0;
1723 cmsis_dap_add_jtag_sequence(1, NULL, 0, bit, NULL, 0);
1724 }
1725 }
1726
1727 /* Move to the end state by queuing a sequence to clock into TMS */
1728 static void cmsis_dap_state_move(void)
1729 {
1730 uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1731 uint8_t tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1732
1733 LOG_DEBUG_IO("state move from %s to %s: %d clocks, %02X on tms",
1734 tap_state_name(tap_get_state()), tap_state_name(tap_get_end_state()),
1735 tms_scan_bits, tms_scan);
1736 cmsis_dap_add_tms_sequence(&tms_scan, tms_scan_bits);
1737
1738 tap_set_state(tap_get_end_state());
1739 }
1740
1741
1742 /* Execute a JTAG scan operation by queueing TMS and TDI/TDO sequences */
1743 static void cmsis_dap_execute_scan(struct jtag_command *cmd)
1744 {
1745 LOG_DEBUG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
1746 jtag_scan_type(cmd->cmd.scan));
1747
1748 /* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
1749 while (cmd->cmd.scan->num_fields > 0
1750 && cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
1751 cmd->cmd.scan->num_fields--;
1752 LOG_DEBUG("discarding trailing empty field");
1753 }
1754
1755 if (cmd->cmd.scan->num_fields == 0) {
1756 LOG_DEBUG("empty scan, doing nothing");
1757 return;
1758 }
1759
1760 if (cmd->cmd.scan->ir_scan) {
1761 if (tap_get_state() != TAP_IRSHIFT) {
1762 cmsis_dap_end_state(TAP_IRSHIFT);
1763 cmsis_dap_state_move();
1764 }
1765 } else {
1766 if (tap_get_state() != TAP_DRSHIFT) {
1767 cmsis_dap_end_state(TAP_DRSHIFT);
1768 cmsis_dap_state_move();
1769 }
1770 }
1771
1772 cmsis_dap_end_state(cmd->cmd.scan->end_state);
1773
1774 struct scan_field *field = cmd->cmd.scan->fields;
1775 unsigned scan_size = 0;
1776
1777 for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
1778 scan_size += field->num_bits;
1779 LOG_DEBUG_IO("%s%s field %d/%d %d bits",
1780 field->in_value ? "in" : "",
1781 field->out_value ? "out" : "",
1782 i,
1783 cmd->cmd.scan->num_fields,
1784 field->num_bits);
1785
1786 if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
1787 LOG_DEBUG_IO("Last field and have to move out of SHIFT state");
1788 /* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
1789 * movement. This last field can't have length zero, it was checked above. */
1790 cmsis_dap_add_jtag_sequence(
1791 field->num_bits - 1, /* number of bits to clock */
1792 field->out_value, /* output sequence */
1793 0, /* output offset */
1794 false, /* TMS low */
1795 field->in_value,
1796 0);
1797
1798 /* Clock the last bit out, with TMS high */
1799 uint8_t last_bit = 0;
1800 if (field->out_value)
1801 bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
1802 cmsis_dap_add_jtag_sequence(
1803 1,
1804 &last_bit,
1805 0,
1806 true,
1807 field->in_value,
1808 field->num_bits - 1);
1809 tap_set_state(tap_state_transition(tap_get_state(), 1));
1810
1811 /* Now clock one more cycle, with TMS low, to get us into a PAUSE state */
1812 cmsis_dap_add_jtag_sequence(
1813 1,
1814 &last_bit,
1815 0,
1816 false,
1817 NULL,
1818 0);
1819 tap_set_state(tap_state_transition(tap_get_state(), 0));
1820 } else {
1821 LOG_DEBUG_IO("Internal field, staying in SHIFT state afterwards");
1822 /* Clocking part of a sequence into DR or IR with TMS=0,
1823 leaving TMS=0 at the end so we can continue later */
1824 cmsis_dap_add_jtag_sequence(
1825 field->num_bits,
1826 field->out_value,
1827 0,
1828 false,
1829 field->in_value,
1830 0);
1831 }
1832 }
1833
1834 if (tap_get_state() != tap_get_end_state()) {
1835 cmsis_dap_end_state(tap_get_end_state());
1836 cmsis_dap_state_move();
1837 }
1838
1839 LOG_DEBUG_IO("%s scan, %i bits, end in %s",
1840 (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1841 tap_state_name(tap_get_end_state()));
1842 }
1843
1844 static void cmsis_dap_pathmove(int num_states, tap_state_t *path)
1845 {
1846 uint8_t tms0 = 0x00;
1847 uint8_t tms1 = 0xff;
1848
1849 for (int i = 0; i < num_states; i++) {
1850 if (path[i] == tap_state_transition(tap_get_state(), false))
1851 cmsis_dap_add_tms_sequence(&tms0, 1);
1852 else if (path[i] == tap_state_transition(tap_get_state(), true))
1853 cmsis_dap_add_tms_sequence(&tms1, 1);
1854 else {
1855 LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
1856 tap_state_name(tap_get_state()), tap_state_name(path[i]));
1857 exit(-1);
1858 }
1859
1860 tap_set_state(path[i]);
1861 }
1862
1863 cmsis_dap_end_state(tap_get_state());
1864 }
1865
1866 static void cmsis_dap_execute_pathmove(struct jtag_command *cmd)
1867 {
1868 LOG_DEBUG_IO("pathmove: %i states, end in %i",
1869 cmd->cmd.pathmove->num_states,
1870 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
1871
1872 cmsis_dap_pathmove(cmd->cmd.pathmove->num_states, cmd->cmd.pathmove->path);
1873 }
1874
1875 static void cmsis_dap_stableclocks(int num_cycles)
1876 {
1877 uint8_t tms = tap_get_state() == TAP_RESET;
1878 /* TODO: Perform optimizations? */
1879 /* Execute num_cycles. */
1880 for (int i = 0; i < num_cycles; i++)
1881 cmsis_dap_add_tms_sequence(&tms, 1);
1882 }
1883
1884 static void cmsis_dap_runtest(int num_cycles)
1885 {
1886 tap_state_t saved_end_state = tap_get_end_state();
1887
1888 /* Only do a state_move when we're not already in IDLE. */
1889 if (tap_get_state() != TAP_IDLE) {
1890 cmsis_dap_end_state(TAP_IDLE);
1891 cmsis_dap_state_move();
1892 }
1893 cmsis_dap_stableclocks(num_cycles);
1894
1895 /* Finish in end_state. */
1896 cmsis_dap_end_state(saved_end_state);
1897
1898 if (tap_get_state() != tap_get_end_state())
1899 cmsis_dap_state_move();
1900 }
1901
1902 static void cmsis_dap_execute_runtest(struct jtag_command *cmd)
1903 {
1904 LOG_DEBUG_IO("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles,
1905 cmd->cmd.runtest->end_state);
1906
1907 cmsis_dap_end_state(cmd->cmd.runtest->end_state);
1908 cmsis_dap_runtest(cmd->cmd.runtest->num_cycles);
1909 }
1910
1911 static void cmsis_dap_execute_stableclocks(struct jtag_command *cmd)
1912 {
1913 LOG_DEBUG_IO("stableclocks %i cycles", cmd->cmd.runtest->num_cycles);
1914 cmsis_dap_stableclocks(cmd->cmd.runtest->num_cycles);
1915 }
1916
1917 static void cmsis_dap_execute_tms(struct jtag_command *cmd)
1918 {
1919 LOG_DEBUG_IO("TMS: %d bits", cmd->cmd.tms->num_bits);
1920 cmsis_dap_cmd_dap_swj_sequence(cmd->cmd.tms->num_bits, cmd->cmd.tms->bits);
1921 }
1922
1923 /* TODO: Is there need to call cmsis_dap_flush() for the JTAG_PATHMOVE,
1924 * JTAG_RUNTEST, JTAG_STABLECLOCKS? */
1925 static void cmsis_dap_execute_command(struct jtag_command *cmd)
1926 {
1927 switch (cmd->type) {
1928 case JTAG_SLEEP:
1929 cmsis_dap_flush();
1930 cmsis_dap_execute_sleep(cmd);
1931 break;
1932 case JTAG_TLR_RESET:
1933 cmsis_dap_flush();
1934 cmsis_dap_execute_tlr_reset(cmd);
1935 break;
1936 case JTAG_SCAN:
1937 cmsis_dap_execute_scan(cmd);
1938 break;
1939 case JTAG_PATHMOVE:
1940 cmsis_dap_execute_pathmove(cmd);
1941 break;
1942 case JTAG_RUNTEST:
1943 cmsis_dap_execute_runtest(cmd);
1944 break;
1945 case JTAG_STABLECLOCKS:
1946 cmsis_dap_execute_stableclocks(cmd);
1947 break;
1948 case JTAG_TMS:
1949 cmsis_dap_execute_tms(cmd);
1950 break;
1951 default:
1952 LOG_ERROR("BUG: unknown JTAG command type 0x%X encountered", cmd->type);
1953 exit(-1);
1954 }
1955 }
1956
1957 static int cmsis_dap_execute_queue(struct jtag_command *cmd_queue)
1958 {
1959 struct jtag_command *cmd = cmd_queue;
1960
1961 while (cmd) {
1962 cmsis_dap_execute_command(cmd);
1963 cmd = cmd->next;
1964 }
1965
1966 cmsis_dap_flush();
1967
1968 return ERROR_OK;
1969 }
1970
1971 static int cmsis_dap_speed(int speed)
1972 {
1973 if (speed == 0) {
1974 LOG_ERROR("RTCK not supported. Set nonzero \"adapter speed\".");
1975 return ERROR_JTAG_NOT_IMPLEMENTED;
1976 }
1977
1978 return cmsis_dap_cmd_dap_swj_clock(speed);
1979 }
1980
1981 static int cmsis_dap_speed_div(int speed, int *khz)
1982 {
1983 *khz = speed;
1984 return ERROR_OK;
1985 }
1986
1987 static int cmsis_dap_khz(int khz, int *jtag_speed)
1988 {
1989 *jtag_speed = khz;
1990 return ERROR_OK;
1991 }
1992
1993 static bool calculate_swo_prescaler(unsigned int traceclkin_freq,
1994 uint32_t trace_freq, uint16_t *prescaler)
1995 {
1996 unsigned int presc = (traceclkin_freq + trace_freq / 2) / trace_freq;
1997 if (presc == 0 || presc > TPIU_ACPR_MAX_SWOSCALER + 1)
1998 return false;
1999
2000 /* Probe's UART speed must be within 3% of the TPIU's SWO baud rate. */
2001 unsigned int max_deviation = (traceclkin_freq * 3) / 100;
2002 if (presc * trace_freq < traceclkin_freq - max_deviation ||
2003 presc * trace_freq > traceclkin_freq + max_deviation)
2004 return false;
2005
2006 *prescaler = presc;
2007
2008 return true;
2009 }
2010
2011 /**
2012 * @see adapter_driver::config_trace
2013 */
2014 static int cmsis_dap_config_trace(
2015 bool trace_enabled,
2016 enum tpiu_pin_protocol pin_protocol,
2017 uint32_t port_size,
2018 unsigned int *swo_freq,
2019 unsigned int traceclkin_hz,
2020 uint16_t *swo_prescaler)
2021 {
2022 int retval;
2023
2024 if (!trace_enabled) {
2025 if (cmsis_dap_handle->trace_enabled) {
2026 retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_STOP);
2027 if (retval != ERROR_OK) {
2028 LOG_ERROR("Failed to disable the SWO-trace.");
2029 return retval;
2030 }
2031 }
2032 cmsis_dap_handle->trace_enabled = false;
2033 LOG_INFO("SWO-trace disabled.");
2034 return ERROR_OK;
2035 }
2036
2037 if (!(cmsis_dap_handle->caps & INFO_CAPS_SWO_UART) &&
2038 !(cmsis_dap_handle->caps & INFO_CAPS_SWO_MANCHESTER)) {
2039 LOG_ERROR("SWO-trace is not supported by the device.");
2040 return ERROR_FAIL;
2041 }
2042
2043 uint8_t swo_mode;
2044 if (pin_protocol == TPIU_PIN_PROTOCOL_ASYNC_UART &&
2045 (cmsis_dap_handle->caps & INFO_CAPS_SWO_UART)) {
2046 swo_mode = DAP_SWO_MODE_UART;
2047 } else if (pin_protocol == TPIU_PIN_PROTOCOL_ASYNC_MANCHESTER &&
2048 (cmsis_dap_handle->caps & INFO_CAPS_SWO_MANCHESTER)) {
2049 swo_mode = DAP_SWO_MODE_MANCHESTER;
2050 } else {
2051 LOG_ERROR("Selected pin protocol is not supported.");
2052 return ERROR_FAIL;
2053 }
2054
2055 if (*swo_freq == 0) {
2056 LOG_INFO("SWO-trace frequency autodetection not implemented.");
2057 return ERROR_FAIL;
2058 }
2059
2060 retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_STOP);
2061 if (retval != ERROR_OK)
2062 return retval;
2063
2064 cmsis_dap_handle->trace_enabled = false;
2065
2066 retval = cmsis_dap_get_swo_buf_sz(&cmsis_dap_handle->swo_buf_sz);
2067 if (retval != ERROR_OK)
2068 return retval;
2069
2070 retval = cmsis_dap_cmd_dap_swo_transport(DAP_SWO_TRANSPORT_DATA);
2071 if (retval != ERROR_OK)
2072 return retval;
2073
2074 retval = cmsis_dap_cmd_dap_swo_mode(swo_mode);
2075 if (retval != ERROR_OK)
2076 return retval;
2077
2078 retval = cmsis_dap_cmd_dap_swo_baudrate(*swo_freq, swo_freq);
2079 if (retval != ERROR_OK)
2080 return retval;
2081
2082 if (!calculate_swo_prescaler(traceclkin_hz, *swo_freq,
2083 swo_prescaler)) {
2084 LOG_ERROR("SWO frequency is not suitable. Please choose a "
2085 "different frequency or use auto-detection.");
2086 return ERROR_FAIL;
2087 }
2088
2089 LOG_INFO("SWO frequency: %u Hz.", *swo_freq);
2090 LOG_INFO("SWO prescaler: %u.", *swo_prescaler);
2091
2092 retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_START);
2093 if (retval != ERROR_OK)
2094 return retval;
2095
2096 cmsis_dap_handle->trace_enabled = true;
2097
2098 return ERROR_OK;
2099 }
2100
2101 /**
2102 * @see adapter_driver::poll_trace
2103 */
2104 static int cmsis_dap_poll_trace(uint8_t *buf, size_t *size)
2105 {
2106 uint8_t trace_status;
2107 size_t trace_count;
2108
2109 if (!cmsis_dap_handle->trace_enabled) {
2110 *size = 0;
2111 return ERROR_OK;
2112 }
2113
2114 int retval = cmsis_dap_cmd_dap_swo_status(&trace_status, &trace_count);
2115 if (retval != ERROR_OK)
2116 return retval;
2117 if ((trace_status & DAP_SWO_STATUS_CAPTURE_MASK) != DAP_SWO_STATUS_CAPTURE_ACTIVE)
2118 return ERROR_FAIL;
2119
2120 *size = trace_count < *size ? trace_count : *size;
2121 size_t read_so_far = 0;
2122 do {
2123 size_t rb = 0;
2124 uint32_t packet_size = cmsis_dap_handle->packet_size - 4 /*data-reply*/;
2125 uint32_t remaining = *size - read_so_far;
2126 if (remaining < packet_size)
2127 packet_size = remaining;
2128 retval = cmsis_dap_cmd_dap_swo_data(
2129 packet_size,
2130 &trace_status,
2131 &rb,
2132 &buf[read_so_far]);
2133 if (retval != ERROR_OK)
2134 return retval;
2135 if ((trace_status & DAP_SWO_STATUS_CAPTURE_MASK) != DAP_SWO_STATUS_CAPTURE_ACTIVE)
2136 return ERROR_FAIL;
2137
2138 read_so_far += rb;
2139 } while (read_so_far < *size);
2140
2141 return ERROR_OK;
2142 }
2143
2144 COMMAND_HANDLER(cmsis_dap_handle_info_command)
2145 {
2146 if (cmsis_dap_get_version_info() == ERROR_OK)
2147 cmsis_dap_get_status();
2148
2149 return ERROR_OK;
2150 }
2151
2152 COMMAND_HANDLER(cmsis_dap_handle_cmd_command)
2153 {
2154 uint8_t *command = cmsis_dap_handle->command;
2155
2156 for (unsigned i = 0; i < CMD_ARGC; i++)
2157 COMMAND_PARSE_NUMBER(u8, CMD_ARGV[i], command[i]);
2158
2159 int retval = cmsis_dap_xfer(cmsis_dap_handle, CMD_ARGC);
2160
2161 if (retval != ERROR_OK) {
2162 LOG_ERROR("CMSIS-DAP command failed.");
2163 return ERROR_JTAG_DEVICE_ERROR;
2164 }
2165
2166 uint8_t *resp = cmsis_dap_handle->response;
2167 LOG_INFO("Returned data %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8,
2168 resp[1], resp[2], resp[3], resp[4]);
2169
2170 return ERROR_OK;
2171 }
2172
2173 COMMAND_HANDLER(cmsis_dap_handle_vid_pid_command)
2174 {
2175 if (CMD_ARGC > MAX_USB_IDS * 2) {
2176 LOG_WARNING("ignoring extra IDs in cmsis-dap vid_pid "
2177 "(maximum is %d pairs)", MAX_USB_IDS);
2178 CMD_ARGC = MAX_USB_IDS * 2;
2179 }
2180 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
2181 LOG_WARNING("incomplete cmsis-dap vid_pid configuration directive");
2182 if (CMD_ARGC < 2)
2183 return ERROR_COMMAND_SYNTAX_ERROR;
2184 /* remove the incomplete trailing id */
2185 CMD_ARGC -= 1;
2186 }
2187
2188 unsigned i;
2189 for (i = 0; i < CMD_ARGC; i += 2) {
2190 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], cmsis_dap_vid[i >> 1]);
2191 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], cmsis_dap_pid[i >> 1]);
2192 }
2193
2194 /*
2195 * Explicitly terminate, in case there are multiples instances of
2196 * cmsis_dap_vid_pid.
2197 */
2198 cmsis_dap_vid[i >> 1] = cmsis_dap_pid[i >> 1] = 0;
2199
2200 return ERROR_OK;
2201 }
2202
2203 COMMAND_HANDLER(cmsis_dap_handle_backend_command)
2204 {
2205 if (CMD_ARGC == 1) {
2206 if (strcmp(CMD_ARGV[0], "auto") == 0) {
2207 cmsis_dap_backend = -1; /* autoselect */
2208 } else {
2209 for (unsigned int i = 0; i < ARRAY_SIZE(cmsis_dap_backends); i++) {
2210 if (strcasecmp(cmsis_dap_backends[i]->name, CMD_ARGV[0]) == 0) {
2211 cmsis_dap_backend = i;
2212 return ERROR_OK;
2213 }
2214 }
2215
2216 command_print(CMD, "invalid backend argument to cmsis-dap backend <backend>");
2217 return ERROR_COMMAND_ARGUMENT_INVALID;
2218 }
2219 } else {
2220 return ERROR_COMMAND_SYNTAX_ERROR;
2221 }
2222
2223 return ERROR_OK;
2224 }
2225
2226 COMMAND_HANDLER(cmsis_dap_handle_quirk_command)
2227 {
2228 if (CMD_ARGC > 1)
2229 return ERROR_COMMAND_SYNTAX_ERROR;
2230
2231 if (CMD_ARGC == 1)
2232 COMMAND_PARSE_ENABLE(CMD_ARGV[0], cmsis_dap_handle->quirk_mode);
2233
2234 command_print(CMD, "CMSIS-DAP quirk workarounds %s",
2235 cmsis_dap_handle->quirk_mode ? "enabled" : "disabled");
2236 return ERROR_OK;
2237 }
2238
2239 static const struct command_registration cmsis_dap_subcommand_handlers[] = {
2240 {
2241 .name = "info",
2242 .handler = &cmsis_dap_handle_info_command,
2243 .mode = COMMAND_EXEC,
2244 .usage = "",
2245 .help = "show cmsis-dap info",
2246 },
2247 {
2248 .name = "cmd",
2249 .handler = &cmsis_dap_handle_cmd_command,
2250 .mode = COMMAND_EXEC,
2251 .usage = "",
2252 .help = "issue cmsis-dap command",
2253 },
2254 {
2255 .name = "vid_pid",
2256 .handler = &cmsis_dap_handle_vid_pid_command,
2257 .mode = COMMAND_CONFIG,
2258 .help = "the vendor ID and product ID of the CMSIS-DAP device",
2259 .usage = "(vid pid)*",
2260 },
2261 {
2262 .name = "backend",
2263 .handler = &cmsis_dap_handle_backend_command,
2264 .mode = COMMAND_CONFIG,
2265 .help = "set the communication backend to use (USB bulk or HID).",
2266 .usage = "(auto | usb_bulk | hid)",
2267 },
2268 {
2269 .name = "quirk",
2270 .handler = &cmsis_dap_handle_quirk_command,
2271 .mode = COMMAND_ANY,
2272 .help = "allow expensive workarounds of known adapter quirks.",
2273 .usage = "[enable | disable]",
2274 },
2275 #if BUILD_CMSIS_DAP_USB
2276 {
2277 .name = "usb",
2278 .chain = cmsis_dap_usb_subcommand_handlers,
2279 .mode = COMMAND_ANY,
2280 .help = "USB bulk backend-specific commands",
2281 .usage = "<cmd>",
2282 },
2283 #endif
2284 COMMAND_REGISTRATION_DONE
2285 };
2286
2287
2288 static const struct command_registration cmsis_dap_command_handlers[] = {
2289 {
2290 .name = "cmsis-dap",
2291 .mode = COMMAND_ANY,
2292 .help = "perform CMSIS-DAP management",
2293 .usage = "<cmd>",
2294 .chain = cmsis_dap_subcommand_handlers,
2295 },
2296 COMMAND_REGISTRATION_DONE
2297 };
2298
2299 static const struct swd_driver cmsis_dap_swd_driver = {
2300 .init = cmsis_dap_swd_init,
2301 .switch_seq = cmsis_dap_swd_switch_seq,
2302 .read_reg = cmsis_dap_swd_read_reg,
2303 .write_reg = cmsis_dap_swd_write_reg,
2304 .run = cmsis_dap_swd_run_queue,
2305 };
2306
2307 static const char * const cmsis_dap_transport[] = { "swd", "jtag", NULL };
2308
2309 static struct jtag_interface cmsis_dap_interface = {
2310 .supported = DEBUG_CAP_TMS_SEQ,
2311 .execute_queue = cmsis_dap_execute_queue,
2312 };
2313
2314 struct adapter_driver cmsis_dap_adapter_driver = {
2315 .name = "cmsis-dap",
2316 .transports = cmsis_dap_transport,
2317 .commands = cmsis_dap_command_handlers,
2318
2319 .init = cmsis_dap_init,
2320 .quit = cmsis_dap_quit,
2321 .reset = cmsis_dap_reset,
2322 .speed = cmsis_dap_speed,
2323 .khz = cmsis_dap_khz,
2324 .speed_div = cmsis_dap_speed_div,
2325 .config_trace = cmsis_dap_config_trace,
2326 .poll_trace = cmsis_dap_poll_trace,
2327
2328 .jtag_ops = &cmsis_dap_interface,
2329 .swd_ops = &cmsis_dap_swd_driver,
2330 };

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)