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