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