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

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)