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