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