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