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