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