drivers/cmsis-dap: flush read
[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 struct pending_transfer_result {
173         uint8_t cmd;
174         uint32_t data;
175         void *buffer;
176 };
177
178 struct pending_request_block {
179         struct pending_transfer_result *transfers;
180         int transfer_count;
181 };
182
183 struct pending_scan_result {
184         /** Offset in bytes in the CMD_DAP_JTAG_SEQ response buffer. */
185         unsigned first;
186         /** Number of bits to read. */
187         unsigned length;
188         /** Location to store the result */
189         uint8_t *buffer;
190         /** Offset in the destination buffer */
191         unsigned buffer_offset;
192 };
193
194 /* Up to MIN(packet_count, MAX_PENDING_REQUESTS) requests may be issued
195  * until the first response arrives */
196 #define MAX_PENDING_REQUESTS 3
197
198 /* Pending requests are organized as a FIFO - circular buffer */
199 /* Each block in FIFO can contain up to pending_queue_len transfers */
200 static int pending_queue_len;
201 static struct pending_request_block pending_fifo[MAX_PENDING_REQUESTS];
202 static int pending_fifo_put_idx, pending_fifo_get_idx;
203 static int pending_fifo_block_count;
204
205 /* pointers to buffers that will receive jtag scan results on the next flush */
206 #define MAX_PENDING_SCAN_RESULTS 256
207 static int pending_scan_result_count;
208 static struct pending_scan_result pending_scan_results[MAX_PENDING_SCAN_RESULTS];
209
210 /* queued JTAG sequences that will be executed on the next flush */
211 #define QUEUED_SEQ_BUF_LEN (cmsis_dap_handle->packet_size - 3)
212 static int queued_seq_count;
213 static int queued_seq_buf_end;
214 static int queued_seq_tdo_ptr;
215 static uint8_t queued_seq_buf[1024]; /* TODO: make dynamic / move into cmsis object */
216
217 static int queued_retval;
218
219 static uint8_t output_pins = SWJ_PIN_SRST | SWJ_PIN_TRST;
220
221 static struct cmsis_dap *cmsis_dap_handle;
222
223
224 static int cmsis_dap_quit(void);
225
226 static int cmsis_dap_open(void)
227 {
228         const struct cmsis_dap_backend *backend = NULL;
229
230         struct cmsis_dap *dap = calloc(1, sizeof(struct cmsis_dap));
231         if (dap == NULL) {
232                 LOG_ERROR("unable to allocate memory");
233                 return ERROR_FAIL;
234         }
235
236         if (cmsis_dap_backend >= 0) {
237                 /* Use forced backend */
238                 backend = cmsis_dap_backends[cmsis_dap_backend];
239                 if (backend->open(dap, cmsis_dap_vid, cmsis_dap_pid, cmsis_dap_serial) != ERROR_OK)
240                         backend = NULL;
241         } else {
242                 /* Try all backends */
243                 for (unsigned int i = 0; i < ARRAY_SIZE(cmsis_dap_backends); i++) {
244                         backend = cmsis_dap_backends[i];
245                         if (backend->open(dap, cmsis_dap_vid, cmsis_dap_pid, cmsis_dap_serial) == ERROR_OK)
246                                 break;
247                         else
248                                 backend = NULL;
249                 }
250         }
251
252         if (backend == NULL) {
253                 LOG_ERROR("unable to find a matching CMSIS-DAP device");
254                 free(dap);
255                 return ERROR_FAIL;
256         }
257
258         dap->backend = backend;
259
260         cmsis_dap_handle = dap;
261
262         return ERROR_OK;
263 }
264
265 static void cmsis_dap_close(struct cmsis_dap *dap)
266 {
267         if (dap->backend) {
268                 dap->backend->close(dap);
269                 dap->backend = NULL;
270         }
271
272         free(cmsis_dap_handle->packet_buffer);
273         free(cmsis_dap_handle);
274         cmsis_dap_handle = NULL;
275         free(cmsis_dap_serial);
276         cmsis_dap_serial = NULL;
277
278         for (int i = 0; i < MAX_PENDING_REQUESTS; i++) {
279                 free(pending_fifo[i].transfers);
280                 pending_fifo[i].transfers = NULL;
281         }
282 }
283
284 static void cmsis_dap_flush_read(struct cmsis_dap *dap)
285 {
286         unsigned int i;
287         /* Some CMSIS-DAP adapters keep buffered packets over
288          * USB close/open so we need to flush up to 64 old packets
289          * to be sure all buffers are empty */
290         for (i = 0; i < 64; i++) {
291                 int retval = dap->backend->read(dap, 10);
292                 if (retval == ERROR_TIMEOUT_REACHED)
293                         break;
294         }
295         if (i)
296                 LOG_DEBUG("Flushed %u packets", i);
297 }
298
299 /* Send a message and receive the reply */
300 static int cmsis_dap_xfer(struct cmsis_dap *dap, int txlen)
301 {
302         if (pending_fifo_block_count) {
303                 LOG_ERROR("pending %d blocks, flushing", pending_fifo_block_count);
304                 while (pending_fifo_block_count) {
305                         dap->backend->read(dap, 10);
306                         pending_fifo_block_count--;
307                 }
308                 pending_fifo_put_idx = 0;
309                 pending_fifo_get_idx = 0;
310         }
311
312         uint8_t current_cmd = cmsis_dap_handle->command[0];
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         uint8_t *resp = cmsis_dap_handle->response;
323         if (resp[0] == DAP_ERROR) {
324                 LOG_ERROR("CMSIS-DAP command 0x%" PRIx8 " not implemented", current_cmd);
325                 return ERROR_NOT_IMPLEMENTED;
326         }
327
328         if (resp[0] != current_cmd) {
329                 LOG_ERROR("CMSIS-DAP command mismatch. Sent 0x%" PRIx8
330                          " received 0x%" PRIx8, current_cmd, resp[0]);
331
332                 cmsis_dap_flush_read(dap);
333                 return ERROR_FAIL;
334         }
335
336         return ERROR_OK;
337 }
338
339 static int cmsis_dap_cmd_DAP_SWJ_Pins(uint8_t pins, uint8_t mask, uint32_t delay, uint8_t *input)
340 {
341         int retval;
342         uint8_t *command = cmsis_dap_handle->command;
343
344         command[0] = CMD_DAP_SWJ_PINS;
345         command[1] = pins;
346         command[2] = mask;
347         h_u32_to_le(&command[3], delay);
348
349         retval = cmsis_dap_xfer(cmsis_dap_handle, 7);
350
351         if (retval != ERROR_OK) {
352                 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_PINS failed.");
353                 return ERROR_JTAG_DEVICE_ERROR;
354         }
355
356         if (input)
357                 *input = cmsis_dap_handle->response[1];
358
359         return ERROR_OK;
360 }
361
362 static int cmsis_dap_cmd_DAP_SWJ_Clock(uint32_t swj_clock)
363 {
364         int retval;
365         uint8_t *command = cmsis_dap_handle->command;
366
367         /* set clock in Hz */
368         swj_clock *= 1000;
369
370         command[0] = CMD_DAP_SWJ_CLOCK;
371         h_u32_to_le(&command[1], swj_clock);
372
373         retval = cmsis_dap_xfer(cmsis_dap_handle, 5);
374
375         if (retval != ERROR_OK || cmsis_dap_handle->response[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 *command = cmsis_dap_handle->command;
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         command[0] = CMD_DAP_SWJ_SEQ;
398         command[1] = s_len;
399         bit_copy(&command[2], 0, sequence, 0, s_len);
400
401         retval = cmsis_dap_xfer(cmsis_dap_handle, 2 + DIV_ROUND_UP(s_len, 8));
402         if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK)
403                 return ERROR_FAIL;
404
405         return ERROR_OK;
406 }
407
408 static int cmsis_dap_cmd_DAP_Info(uint8_t info, uint8_t **data)
409 {
410         int retval;
411         uint8_t *command = cmsis_dap_handle->command;
412
413         command[0] = CMD_DAP_INFO;
414         command[1] = info;
415
416         retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
417
418         if (retval != ERROR_OK) {
419                 LOG_ERROR("CMSIS-DAP command CMD_INFO failed.");
420                 return ERROR_JTAG_DEVICE_ERROR;
421         }
422
423         *data = &cmsis_dap_handle->response[1];
424
425         return ERROR_OK;
426 }
427
428 static int cmsis_dap_cmd_DAP_LED(uint8_t led, uint8_t state)
429 {
430         int retval;
431         uint8_t *command = cmsis_dap_handle->command;
432
433         command[0] = CMD_DAP_LED;
434         command[1] = led;
435         command[2] = state;
436
437         retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
438
439         if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
440                 LOG_ERROR("CMSIS-DAP command CMD_LED failed.");
441                 return ERROR_JTAG_DEVICE_ERROR;
442         }
443
444         return ERROR_OK;
445 }
446
447 static int cmsis_dap_cmd_DAP_Connect(uint8_t mode)
448 {
449         int retval;
450         uint8_t *command = cmsis_dap_handle->command;
451
452         command[0] = CMD_DAP_CONNECT;
453         command[1] = mode;
454
455         retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
456
457         if (retval != ERROR_OK) {
458                 LOG_ERROR("CMSIS-DAP command CMD_CONNECT failed.");
459                 return ERROR_JTAG_DEVICE_ERROR;
460         }
461
462         if (cmsis_dap_handle->response[1] != mode) {
463                 LOG_ERROR("CMSIS-DAP failed to connect in mode (%d)", mode);
464                 return ERROR_JTAG_DEVICE_ERROR;
465         }
466
467         return ERROR_OK;
468 }
469
470 static int cmsis_dap_cmd_DAP_Disconnect(void)
471 {
472         int retval;
473         uint8_t *command = cmsis_dap_handle->command;
474
475         command[0] = CMD_DAP_DISCONNECT;
476
477         retval = cmsis_dap_xfer(cmsis_dap_handle, 1);
478
479         if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
480                 LOG_ERROR("CMSIS-DAP command CMD_DISCONNECT failed.");
481                 return ERROR_JTAG_DEVICE_ERROR;
482         }
483
484         return ERROR_OK;
485 }
486
487 static int cmsis_dap_cmd_DAP_TFER_Configure(uint8_t idle, uint16_t retry_count, uint16_t match_retry)
488 {
489         int retval;
490         uint8_t *command = cmsis_dap_handle->command;
491
492         command[0] = CMD_DAP_TFER_CONFIGURE;
493         command[1] = idle;
494         h_u16_to_le(&command[2], retry_count);
495         h_u16_to_le(&command[4], match_retry);
496
497         retval = cmsis_dap_xfer(cmsis_dap_handle, 6);
498
499         if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
500                 LOG_ERROR("CMSIS-DAP command CMD_TFER_Configure failed.");
501                 return ERROR_JTAG_DEVICE_ERROR;
502         }
503
504         return ERROR_OK;
505 }
506
507 static int cmsis_dap_cmd_DAP_SWD_Configure(uint8_t cfg)
508 {
509         int retval;
510         uint8_t *command = cmsis_dap_handle->command;
511
512         command[0] = CMD_DAP_SWD_CONFIGURE;
513         command[1] = cfg;
514
515         retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
516
517         if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
518                 LOG_ERROR("CMSIS-DAP command CMD_SWD_Configure failed.");
519                 return ERROR_JTAG_DEVICE_ERROR;
520         }
521
522         return ERROR_OK;
523 }
524
525 #if 0
526 static int cmsis_dap_cmd_DAP_Delay(uint16_t delay_us)
527 {
528         int retval;
529         uint8_t *command = cmsis_dap_handle->command;
530
531         command[0] = CMD_DAP_DELAY;
532         h_u16_to_le(&command[1], delay_us);
533
534         retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
535
536         if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
537                 LOG_ERROR("CMSIS-DAP command CMD_Delay failed.");
538                 return ERROR_JTAG_DEVICE_ERROR;
539         }
540
541         return ERROR_OK;
542 }
543 #endif
544
545 static void cmsis_dap_swd_write_from_queue(struct cmsis_dap *dap)
546 {
547         uint8_t *command = cmsis_dap_handle->command;
548         struct pending_request_block *block = &pending_fifo[pending_fifo_put_idx];
549
550         LOG_DEBUG_IO("Executing %d queued transactions from FIFO index %d", block->transfer_count, pending_fifo_put_idx);
551
552         if (queued_retval != ERROR_OK) {
553                 LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
554                 goto skip;
555         }
556
557         if (block->transfer_count == 0)
558                 goto skip;
559
560         command[0] = CMD_DAP_TFER;
561         command[1] = 0x00;      /* DAP Index */
562         command[2] = block->transfer_count;
563         size_t idx = 3;
564
565         for (int i = 0; i < block->transfer_count; i++) {
566                 struct pending_transfer_result *transfer = &(block->transfers[i]);
567                 uint8_t cmd = transfer->cmd;
568                 uint32_t data = transfer->data;
569
570                 LOG_DEBUG_IO("%s %s reg %x %"PRIx32,
571                                 cmd & SWD_CMD_APnDP ? "AP" : "DP",
572                                 cmd & SWD_CMD_RnW ? "read" : "write",
573                           (cmd & SWD_CMD_A32) >> 1, data);
574
575                 /* When proper WAIT handling is implemented in the
576                  * common SWD framework, this kludge can be
577                  * removed. However, this might lead to minor
578                  * performance degradation as the adapter wouldn't be
579                  * able to automatically retry anything (because ARM
580                  * has forgotten to implement sticky error flags
581                  * clearing). See also comments regarding
582                  * cmsis_dap_cmd_DAP_TFER_Configure() and
583                  * cmsis_dap_cmd_DAP_SWD_Configure() in
584                  * cmsis_dap_init().
585                  */
586                 if (!(cmd & SWD_CMD_RnW) &&
587                     !(cmd & SWD_CMD_APnDP) &&
588                     (cmd & SWD_CMD_A32) >> 1 == DP_CTRL_STAT &&
589                     (data & CORUNDETECT)) {
590                         LOG_DEBUG("refusing to enable sticky overrun detection");
591                         data &= ~CORUNDETECT;
592                 }
593
594                 command[idx++] = (cmd >> 1) & 0x0f;
595                 if (!(cmd & SWD_CMD_RnW)) {
596                         h_u32_to_le(&command[idx], data);
597                         idx += 4;
598                 }
599         }
600
601         int retval = dap->backend->write(dap, idx, USB_TIMEOUT);
602
603         if (retval < 0) {
604                 queued_retval = retval;
605                 goto skip;
606         } else {
607                 queued_retval = ERROR_OK;
608         }
609
610         pending_fifo_put_idx = (pending_fifo_put_idx + 1) % dap->packet_count;
611         pending_fifo_block_count++;
612         if (pending_fifo_block_count > dap->packet_count)
613                 LOG_ERROR("too much pending writes %d", pending_fifo_block_count);
614
615         return;
616
617 skip:
618         block->transfer_count = 0;
619 }
620
621 static void cmsis_dap_swd_read_process(struct cmsis_dap *dap, int timeout_ms)
622 {
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         uint8_t *resp = dap->response;
640         if (resp[0] != CMD_DAP_TFER) {
641                 LOG_ERROR("CMSIS-DAP command mismatch. Expected 0x%" PRIx8
642                          " received 0x%" PRIx8, CMD_DAP_TFER, resp[0]);
643                 queued_retval = ERROR_FAIL;
644                 goto skip;
645         }
646
647         uint8_t transfer_count = resp[1];
648         uint8_t ack = resp[2] & 0x07;
649         if (resp[2] & 0x08) {
650                 LOG_DEBUG("CMSIS-DAP Protocol Error @ %d (wrong parity)", transfer_count);
651                 queued_retval = ERROR_FAIL;
652                 goto skip;
653         }
654         if (ack != SWD_ACK_OK) {
655                 LOG_DEBUG("SWD ack not OK @ %d %s", transfer_count,
656                           ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
657                 queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
658                 /* TODO: use results of transfers completed before the error occurred? */
659                 goto skip;
660         }
661
662         if (block->transfer_count != transfer_count)
663                 LOG_ERROR("CMSIS-DAP transfer count mismatch: expected %d, got %d",
664                           block->transfer_count, transfer_count);
665
666         LOG_DEBUG_IO("Received results of %d queued transactions FIFO index %d",
667                  transfer_count, pending_fifo_get_idx);
668         size_t idx = 3;
669         for (int i = 0; i < transfer_count; i++) {
670                 struct pending_transfer_result *transfer = &(block->transfers[i]);
671                 if (transfer->cmd & SWD_CMD_RnW) {
672                         static uint32_t last_read;
673                         uint32_t data = le_to_h_u32(&resp[idx]);
674                         uint32_t tmp = data;
675                         idx += 4;
676
677                         LOG_DEBUG_IO("Read result: %"PRIx32, data);
678
679                         /* Imitate posted AP reads */
680                         if ((transfer->cmd & SWD_CMD_APnDP) ||
681                             ((transfer->cmd & SWD_CMD_A32) >> 1 == DP_RDBUFF)) {
682                                 tmp = last_read;
683                                 last_read = data;
684                         }
685
686                         if (transfer->buffer)
687                                 *(uint32_t *)(transfer->buffer) = tmp;
688                 }
689         }
690
691 skip:
692         block->transfer_count = 0;
693         pending_fifo_get_idx = (pending_fifo_get_idx + 1) % dap->packet_count;
694         pending_fifo_block_count--;
695 }
696
697 static int cmsis_dap_swd_run_queue(void)
698 {
699         if (pending_fifo_block_count)
700                 cmsis_dap_swd_read_process(cmsis_dap_handle, 0);
701
702         cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
703
704         while (pending_fifo_block_count)
705                 cmsis_dap_swd_read_process(cmsis_dap_handle, USB_TIMEOUT);
706
707         pending_fifo_put_idx = 0;
708         pending_fifo_get_idx = 0;
709
710         int retval = queued_retval;
711         queued_retval = ERROR_OK;
712
713         return retval;
714 }
715
716 static void cmsis_dap_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data)
717 {
718         if (pending_fifo[pending_fifo_put_idx].transfer_count == pending_queue_len) {
719                 if (pending_fifo_block_count)
720                         cmsis_dap_swd_read_process(cmsis_dap_handle, 0);
721
722                 /* Not enough room in the queue. Run the queue. */
723                 cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
724
725                 if (pending_fifo_block_count >= cmsis_dap_handle->packet_count)
726                         cmsis_dap_swd_read_process(cmsis_dap_handle, USB_TIMEOUT);
727         }
728
729         if (queued_retval != ERROR_OK)
730                 return;
731
732         struct pending_request_block *block = &pending_fifo[pending_fifo_put_idx];
733         struct pending_transfer_result *transfer = &(block->transfers[block->transfer_count]);
734         transfer->data = data;
735         transfer->cmd = cmd;
736         if (cmd & SWD_CMD_RnW) {
737                 /* Queue a read transaction */
738                 transfer->buffer = dst;
739         }
740         block->transfer_count++;
741 }
742
743 static void cmsis_dap_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
744 {
745         assert(!(cmd & SWD_CMD_RnW));
746         cmsis_dap_swd_queue_cmd(cmd, NULL, value);
747 }
748
749 static void cmsis_dap_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
750 {
751         assert(cmd & SWD_CMD_RnW);
752         cmsis_dap_swd_queue_cmd(cmd, value, 0);
753 }
754
755 static int cmsis_dap_get_serial_info(void)
756 {
757         uint8_t *data;
758
759         int retval = cmsis_dap_cmd_DAP_Info(INFO_ID_SERNUM, &data);
760         if (retval != ERROR_OK)
761                 return retval;
762
763         if (data[0]) /* strlen */
764                 LOG_INFO("CMSIS-DAP: Serial# = %s", &data[1]);
765
766         return ERROR_OK;
767 }
768
769 static int cmsis_dap_get_version_info(void)
770 {
771         uint8_t *data;
772
773         /* INFO_ID_FW_VER - string */
774         int retval = cmsis_dap_cmd_DAP_Info(INFO_ID_FW_VER, &data);
775         if (retval != ERROR_OK)
776                 return retval;
777
778         if (data[0]) /* strlen */
779                 LOG_INFO("CMSIS-DAP: FW Version = %s", &data[1]);
780
781         return ERROR_OK;
782 }
783
784 static int cmsis_dap_get_caps_info(void)
785 {
786         uint8_t *data;
787
788         /* INFO_ID_CAPS - byte */
789         int retval = cmsis_dap_cmd_DAP_Info(INFO_ID_CAPS, &data);
790         if (retval != ERROR_OK)
791                 return retval;
792
793         if (data[0] == 1) {
794                 uint8_t caps = data[1];
795
796                 cmsis_dap_handle->caps = caps;
797
798                 if (caps & INFO_CAPS_SWD)
799                         LOG_INFO("CMSIS-DAP: %s", info_caps_str[0]);
800                 if (caps & INFO_CAPS_JTAG)
801                         LOG_INFO("CMSIS-DAP: %s", info_caps_str[1]);
802         }
803
804         return ERROR_OK;
805 }
806
807 static int cmsis_dap_get_status(void)
808 {
809         uint8_t d;
810
811         int retval = cmsis_dap_cmd_DAP_SWJ_Pins(0, 0, 0, &d);
812
813         if (retval == ERROR_OK) {
814                 LOG_INFO("SWCLK/TCK = %d SWDIO/TMS = %d TDI = %d TDO = %d nTRST = %d nRESET = %d",
815                         (d & SWJ_PIN_TCK) ? 1 : 0,
816                         (d & SWJ_PIN_TMS) ? 1 : 0,
817                         (d & SWJ_PIN_TDI) ? 1 : 0,
818                         (d & SWJ_PIN_TDO) ? 1 : 0,
819                         (d & SWJ_PIN_TRST) ? 1 : 0,
820                         (d & SWJ_PIN_SRST) ? 1 : 0);
821         }
822
823         return retval;
824 }
825
826 static int cmsis_dap_swd_switch_seq(enum swd_special_seq seq)
827 {
828         const uint8_t *s;
829         unsigned int s_len;
830         int retval;
831
832         if ((output_pins & (SWJ_PIN_SRST | SWJ_PIN_TRST)) == (SWJ_PIN_SRST | SWJ_PIN_TRST)) {
833                 /* Following workaround deasserts reset on most adapters.
834                  * Do not reconnect if a reset line is active!
835                  * Reconnecting would break connecting under reset. */
836
837                 /* First disconnect before connecting, Atmel EDBG needs it for SAMD/R/L/C */
838                 cmsis_dap_cmd_DAP_Disconnect();
839
840                 /* When we are reconnecting, DAP_Connect needs to be rerun, at
841                  * least on Keil ULINK-ME */
842                 retval = cmsis_dap_cmd_DAP_Connect(CONNECT_SWD);
843                 if (retval != ERROR_OK)
844                         return retval;
845         }
846
847         switch (seq) {
848         case LINE_RESET:
849                 LOG_DEBUG("SWD line reset");
850                 s = swd_seq_line_reset;
851                 s_len = swd_seq_line_reset_len;
852                 break;
853         case JTAG_TO_SWD:
854                 LOG_DEBUG("JTAG-to-SWD");
855                 s = swd_seq_jtag_to_swd;
856                 s_len = swd_seq_jtag_to_swd_len;
857                 break;
858         case SWD_TO_JTAG:
859                 LOG_DEBUG("SWD-to-JTAG");
860                 s = swd_seq_swd_to_jtag;
861                 s_len = swd_seq_swd_to_jtag_len;
862                 break;
863         default:
864                 LOG_ERROR("Sequence %d not supported", seq);
865                 return ERROR_FAIL;
866         }
867
868         retval = cmsis_dap_cmd_DAP_SWJ_Sequence(s_len, s);
869         if (retval != ERROR_OK)
870                 return retval;
871
872         /* Atmel EDBG needs renew clock setting after SWJ_Sequence
873          * otherwise default frequency is used */
874         return cmsis_dap_cmd_DAP_SWJ_Clock(jtag_get_speed_khz());
875 }
876
877 static int cmsis_dap_swd_open(void)
878 {
879         int retval;
880
881         if (!(cmsis_dap_handle->caps & INFO_CAPS_SWD)) {
882                 LOG_ERROR("CMSIS-DAP: SWD not supported");
883                 return ERROR_JTAG_DEVICE_ERROR;
884         }
885
886         retval = cmsis_dap_cmd_DAP_Connect(CONNECT_SWD);
887         if (retval != ERROR_OK)
888                 return retval;
889
890         /* Add more setup here.??... */
891
892         LOG_INFO("CMSIS-DAP: Interface Initialised (SWD)");
893         return ERROR_OK;
894 }
895
896 static int cmsis_dap_init(void)
897 {
898         int retval;
899         uint8_t *data;
900
901         retval = cmsis_dap_open();
902         if (retval != ERROR_OK)
903                 return retval;
904
905         cmsis_dap_flush_read(cmsis_dap_handle);
906
907         retval = cmsis_dap_get_caps_info();
908         if (retval != ERROR_OK)
909                 return retval;
910
911         retval = cmsis_dap_get_version_info();
912         if (retval != ERROR_OK)
913                 return retval;
914
915         retval = cmsis_dap_get_serial_info();
916         if (retval != ERROR_OK)
917                 return retval;
918
919         if (swd_mode) {
920                 retval = cmsis_dap_swd_open();
921                 if (retval != ERROR_OK)
922                         return retval;
923         } else {
924                 /* Connect in JTAG mode */
925                 if (!(cmsis_dap_handle->caps & INFO_CAPS_JTAG)) {
926                         LOG_ERROR("CMSIS-DAP: JTAG not supported");
927                         return ERROR_JTAG_DEVICE_ERROR;
928                 }
929
930                 retval = cmsis_dap_cmd_DAP_Connect(CONNECT_JTAG);
931                 if (retval != ERROR_OK)
932                         return retval;
933
934                 LOG_INFO("CMSIS-DAP: Interface Initialised (JTAG)");
935         }
936
937         /* Be conservative and suppress submitting multiple HID requests
938          * until we get packet count info from the adaptor */
939         cmsis_dap_handle->packet_count = 1;
940         pending_queue_len = 12;
941
942         /* INFO_ID_PKT_SZ - short */
943         retval = cmsis_dap_cmd_DAP_Info(INFO_ID_PKT_SZ, &data);
944         if (retval != ERROR_OK)
945                 goto init_err;
946
947         if (data[0] == 2) {  /* short */
948                 uint16_t pkt_sz = data[1] + (data[2] << 8);
949                 if (pkt_sz != cmsis_dap_handle->packet_size) {
950
951                         /* 4 bytes of command header + 5 bytes per register
952                          * write. For bulk read sequences just 4 bytes are
953                          * needed per transfer, so this is suboptimal. */
954                         pending_queue_len = (pkt_sz - 4) / 5;
955
956                         free(cmsis_dap_handle->packet_buffer);
957                         retval = cmsis_dap_handle->backend->packet_buffer_alloc(cmsis_dap_handle, pkt_sz);
958                         if (retval != ERROR_OK)
959                                 goto init_err;
960
961                         LOG_DEBUG("CMSIS-DAP: Packet Size = %" PRIu16, pkt_sz);
962                 }
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                 goto init_err;
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                         retval = ERROR_FAIL;
984                         goto init_err;
985                 }
986         }
987
988         /* Intentionally not checked for error, just logs an info message
989          * not vital for further debugging */
990         (void)cmsis_dap_get_status();
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                 goto init_err;
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                 goto init_err;
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                         goto init_err;
1011         }
1012         /* Both LEDs on */
1013         /* Intentionally not checked for error, debugging will work
1014          * without LEDs */
1015         (void)cmsis_dap_cmd_DAP_LED(LED_ID_CONNECT, LED_ON);
1016         (void)cmsis_dap_cmd_DAP_LED(LED_ID_RUN, LED_ON);
1017
1018         /* support connecting with srst asserted */
1019         enum reset_types jtag_reset_config = jtag_get_reset_config();
1020
1021         if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
1022                 if (jtag_reset_config & RESET_SRST_NO_GATING) {
1023                         retval = cmsis_dap_cmd_DAP_SWJ_Pins(0, SWJ_PIN_SRST, 0, NULL);
1024                         if (retval != ERROR_OK)
1025                                 goto init_err;
1026                         LOG_INFO("Connecting under reset");
1027                 }
1028         }
1029         LOG_INFO("CMSIS-DAP: Interface ready");
1030         return ERROR_OK;
1031
1032 init_err:
1033         cmsis_dap_quit();
1034         return retval;
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         /* prepare CMSIS-DAP packet */
1180         uint8_t *command = cmsis_dap_handle->command;
1181         command[0] = CMD_DAP_JTAG_SEQ;
1182         command[1] = queued_seq_count;
1183         memcpy(&command[2], queued_seq_buf, queued_seq_buf_end);
1184
1185 #ifdef CMSIS_DAP_JTAG_DEBUG
1186         debug_parse_cmsis_buf(command, queued_seq_buf_end + 2);
1187 #endif
1188
1189         /* send command to USB device */
1190         int retval = cmsis_dap_xfer(cmsis_dap_handle, queued_seq_buf_end + 2);
1191
1192         uint8_t *resp = cmsis_dap_handle->response;
1193         if (retval != ERROR_OK || resp[1] != DAP_OK) {
1194                 LOG_ERROR("CMSIS-DAP command CMD_DAP_JTAG_SEQ failed.");
1195                 exit(-1);
1196         }
1197
1198 #ifdef CMSIS_DAP_JTAG_DEBUG
1199         LOG_DEBUG_IO("USB response buf:");
1200         for (int c = 0; c < queued_seq_buf_end + 3; ++c)
1201                 printf("%02X ", resp[c]);
1202         printf("\n");
1203 #endif
1204
1205         /* copy scan results into client buffers */
1206         for (int i = 0; i < pending_scan_result_count; ++i) {
1207                 struct pending_scan_result *scan = &pending_scan_results[i];
1208                 LOG_DEBUG_IO("Copying pending_scan_result %d/%d: %d bits from byte %d -> buffer + %d bits",
1209                         i, pending_scan_result_count, scan->length, scan->first + 2, scan->buffer_offset);
1210 #ifdef CMSIS_DAP_JTAG_DEBUG
1211                 for (uint32_t b = 0; b < DIV_ROUND_UP(scan->length, 8); ++b)
1212                         printf("%02X ", resp[2+scan->first+b]);
1213                 printf("\n");
1214 #endif
1215                 bit_copy(scan->buffer, scan->buffer_offset, &resp[2 + scan->first], 0, scan->length);
1216         }
1217
1218         /* reset */
1219         queued_seq_count = 0;
1220         queued_seq_buf_end = 0;
1221         queued_seq_tdo_ptr = 0;
1222         pending_scan_result_count = 0;
1223 }
1224
1225 /* queue a sequence of bits to clock out TDI / in TDO, executing if the buffer is full.
1226  *
1227  * sequence=NULL means clock out zeros on TDI
1228  * tdo_buffer=NULL means don't capture TDO
1229  */
1230 static void cmsis_dap_add_jtag_sequence(int s_len, const uint8_t *sequence, int s_offset,
1231                                         bool tms, uint8_t *tdo_buffer, int tdo_buffer_offset)
1232 {
1233         LOG_DEBUG_IO("[at %d] %d bits, tms %s, seq offset %d, tdo buf %p, tdo offset %d",
1234                 queued_seq_buf_end,
1235                 s_len, tms ? "HIGH" : "LOW", s_offset, tdo_buffer, tdo_buffer_offset);
1236
1237         if (s_len == 0)
1238                 return;
1239
1240         if (s_len > 64) {
1241                 LOG_DEBUG_IO("START JTAG SEQ SPLIT");
1242                 for (int offset = 0; offset < s_len; offset += 64) {
1243                         int len = s_len - offset;
1244                         if (len > 64)
1245                                 len = 64;
1246                         LOG_DEBUG_IO("Splitting long jtag sequence: %d-bit chunk starting at offset %d", len, offset);
1247                         cmsis_dap_add_jtag_sequence(
1248                                 len,
1249                                 sequence,
1250                                 s_offset + offset,
1251                                 tms,
1252                                 tdo_buffer,
1253                                 tdo_buffer == NULL ? 0 : (tdo_buffer_offset + offset)
1254                                 );
1255                 }
1256                 LOG_DEBUG_IO("END JTAG SEQ SPLIT");
1257                 return;
1258         }
1259
1260         int cmd_len = 1 + DIV_ROUND_UP(s_len, 8);
1261         if (queued_seq_count >= 255 || queued_seq_buf_end + cmd_len > QUEUED_SEQ_BUF_LEN)
1262                 /* empty out the buffer */
1263                 cmsis_dap_flush();
1264
1265         ++queued_seq_count;
1266
1267         /* control byte */
1268         queued_seq_buf[queued_seq_buf_end] =
1269                 (tms ? DAP_JTAG_SEQ_TMS : 0) |
1270                 (tdo_buffer != NULL ? DAP_JTAG_SEQ_TDO : 0) |
1271                 (s_len == 64 ? 0 : s_len);
1272
1273         if (sequence != NULL)
1274                 bit_copy(&queued_seq_buf[queued_seq_buf_end + 1], 0, sequence, s_offset, s_len);
1275         else
1276                 memset(&queued_seq_buf[queued_seq_buf_end + 1], 0, DIV_ROUND_UP(s_len, 8));
1277
1278         queued_seq_buf_end += cmd_len;
1279
1280         if (tdo_buffer != NULL) {
1281                 struct pending_scan_result *scan = &pending_scan_results[pending_scan_result_count++];
1282                 scan->first = queued_seq_tdo_ptr;
1283                 queued_seq_tdo_ptr += DIV_ROUND_UP(s_len, 8);
1284                 scan->length = s_len;
1285                 scan->buffer = tdo_buffer;
1286                 scan->buffer_offset = tdo_buffer_offset;
1287         }
1288 }
1289
1290 /* queue a sequence of bits to clock out TMS, executing if the buffer is full */
1291 static void cmsis_dap_add_tms_sequence(const uint8_t *sequence, int s_len)
1292 {
1293         LOG_DEBUG_IO("%d bits: %02X", s_len, *sequence);
1294         /* we use a series of CMD_DAP_JTAG_SEQ commands to toggle TMS,
1295            because even though it seems ridiculously inefficient, it
1296            allows us to combine TMS and scan sequences into the same
1297            USB packet. */
1298         /* TODO: combine runs of the same tms value */
1299         for (int i = 0; i < s_len; ++i) {
1300                 bool bit = (sequence[i / 8] & (1 << (i % 8))) != 0;
1301                 cmsis_dap_add_jtag_sequence(1, NULL, 0, bit, NULL, 0);
1302         }
1303 }
1304
1305 /* Move to the end state by queuing a sequence to clock into TMS */
1306 static void cmsis_dap_state_move(void)
1307 {
1308         uint8_t tms_scan;
1309         uint8_t tms_scan_bits;
1310
1311         tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1312         tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1313
1314         LOG_DEBUG_IO("state move from %s to %s: %d clocks, %02X on tms",
1315                 tap_state_name(tap_get_state()), tap_state_name(tap_get_end_state()),
1316                 tms_scan_bits, tms_scan);
1317         cmsis_dap_add_tms_sequence(&tms_scan, tms_scan_bits);
1318
1319         tap_set_state(tap_get_end_state());
1320 }
1321
1322
1323 /* Execute a JTAG scan operation by queueing TMS and TDI/TDO sequences */
1324 static void cmsis_dap_execute_scan(struct jtag_command *cmd)
1325 {
1326         LOG_DEBUG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
1327                 jtag_scan_type(cmd->cmd.scan));
1328
1329         /* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
1330         while (cmd->cmd.scan->num_fields > 0
1331                         && cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
1332                 cmd->cmd.scan->num_fields--;
1333                 LOG_DEBUG("discarding trailing empty field");
1334         }
1335
1336         if (cmd->cmd.scan->num_fields == 0) {
1337                 LOG_DEBUG("empty scan, doing nothing");
1338                 return;
1339         }
1340
1341         if (cmd->cmd.scan->ir_scan) {
1342                 if (tap_get_state() != TAP_IRSHIFT) {
1343                         cmsis_dap_end_state(TAP_IRSHIFT);
1344                         cmsis_dap_state_move();
1345                 }
1346         } else {
1347                 if (tap_get_state() != TAP_DRSHIFT) {
1348                         cmsis_dap_end_state(TAP_DRSHIFT);
1349                         cmsis_dap_state_move();
1350                 }
1351         }
1352
1353         cmsis_dap_end_state(cmd->cmd.scan->end_state);
1354
1355         struct scan_field *field = cmd->cmd.scan->fields;
1356         unsigned scan_size = 0;
1357
1358         for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
1359                 scan_size += field->num_bits;
1360                 LOG_DEBUG_IO("%s%s field %d/%d %d bits",
1361                         field->in_value ? "in" : "",
1362                         field->out_value ? "out" : "",
1363                         i,
1364                         cmd->cmd.scan->num_fields,
1365                         field->num_bits);
1366
1367                 if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
1368                         LOG_DEBUG_IO("Last field and have to move out of SHIFT state");
1369                         /* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
1370                          * movement. This last field can't have length zero, it was checked above. */
1371                         cmsis_dap_add_jtag_sequence(
1372                                 field->num_bits - 1, /* number of bits to clock */
1373                                 field->out_value, /* output sequence */
1374                                 0, /* output offset */
1375                                 false, /* TMS low */
1376                                 field->in_value,
1377                                 0);
1378
1379                         /* Clock the last bit out, with TMS high */
1380                         uint8_t last_bit = 0;
1381                         if (field->out_value)
1382                                 bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
1383                         cmsis_dap_add_jtag_sequence(
1384                                 1,
1385                                 &last_bit,
1386                                 0,
1387                                 true,
1388                                 field->in_value,
1389                                 field->num_bits - 1);
1390                         tap_set_state(tap_state_transition(tap_get_state(), 1));
1391
1392                         /* Now clock one more cycle, with TMS low, to get us into a PAUSE state */
1393                         cmsis_dap_add_jtag_sequence(
1394                                 1,
1395                                 &last_bit,
1396                                 0,
1397                                 false,
1398                                 NULL,
1399                                 0);
1400                         tap_set_state(tap_state_transition(tap_get_state(), 0));
1401                 } else {
1402                         LOG_DEBUG_IO("Internal field, staying in SHIFT state afterwards");
1403                         /* Clocking part of a sequence into DR or IR with TMS=0,
1404                            leaving TMS=0 at the end so we can continue later */
1405                         cmsis_dap_add_jtag_sequence(
1406                                 field->num_bits,
1407                                 field->out_value,
1408                                 0,
1409                                 false,
1410                                 field->in_value,
1411                                 0);
1412                 }
1413         }
1414
1415         if (tap_get_state() != tap_get_end_state()) {
1416                 cmsis_dap_end_state(tap_get_end_state());
1417                 cmsis_dap_state_move();
1418         }
1419
1420         LOG_DEBUG_IO("%s scan, %i bits, end in %s",
1421                 (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1422                 tap_state_name(tap_get_end_state()));
1423 }
1424
1425 static void cmsis_dap_pathmove(int num_states, tap_state_t *path)
1426 {
1427         int i;
1428         uint8_t tms0 = 0x00;
1429         uint8_t tms1 = 0xff;
1430
1431         for (i = 0; i < num_states; i++) {
1432                 if (path[i] == tap_state_transition(tap_get_state(), false))
1433                         cmsis_dap_add_tms_sequence(&tms0, 1);
1434                 else if (path[i] == tap_state_transition(tap_get_state(), true))
1435                         cmsis_dap_add_tms_sequence(&tms1, 1);
1436                 else {
1437                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
1438                                   tap_state_name(tap_get_state()), tap_state_name(path[i]));
1439                         exit(-1);
1440                 }
1441
1442                 tap_set_state(path[i]);
1443         }
1444
1445         cmsis_dap_end_state(tap_get_state());
1446 }
1447
1448 static void cmsis_dap_execute_pathmove(struct jtag_command *cmd)
1449 {
1450         LOG_DEBUG_IO("pathmove: %i states, end in %i",
1451                       cmd->cmd.pathmove->num_states,
1452                cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
1453
1454         cmsis_dap_pathmove(cmd->cmd.pathmove->num_states, cmd->cmd.pathmove->path);
1455 }
1456
1457 static void cmsis_dap_stableclocks(int num_cycles)
1458 {
1459         int i;
1460
1461         uint8_t tms = tap_get_state() == TAP_RESET;
1462         /* TODO: Perform optimizations? */
1463         /* Execute num_cycles. */
1464         for (i = 0; i < num_cycles; i++)
1465                 cmsis_dap_add_tms_sequence(&tms, 1);
1466 }
1467
1468 static void cmsis_dap_runtest(int num_cycles)
1469 {
1470         tap_state_t saved_end_state = tap_get_end_state();
1471
1472         /* Only do a state_move when we're not already in IDLE. */
1473         if (tap_get_state() != TAP_IDLE) {
1474                 cmsis_dap_end_state(TAP_IDLE);
1475                 cmsis_dap_state_move();
1476         }
1477         cmsis_dap_stableclocks(num_cycles);
1478
1479         /* Finish in end_state. */
1480         cmsis_dap_end_state(saved_end_state);
1481
1482         if (tap_get_state() != tap_get_end_state())
1483                 cmsis_dap_state_move();
1484 }
1485
1486 static void cmsis_dap_execute_runtest(struct jtag_command *cmd)
1487 {
1488         LOG_DEBUG_IO("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles,
1489                       cmd->cmd.runtest->end_state);
1490
1491         cmsis_dap_end_state(cmd->cmd.runtest->end_state);
1492         cmsis_dap_runtest(cmd->cmd.runtest->num_cycles);
1493 }
1494
1495 static void cmsis_dap_execute_stableclocks(struct jtag_command *cmd)
1496 {
1497         LOG_DEBUG_IO("stableclocks %i cycles", cmd->cmd.runtest->num_cycles);
1498         cmsis_dap_stableclocks(cmd->cmd.runtest->num_cycles);
1499 }
1500
1501 static void cmsis_dap_execute_tms(struct jtag_command *cmd)
1502 {
1503         LOG_DEBUG_IO("TMS: %d bits", cmd->cmd.tms->num_bits);
1504         cmsis_dap_cmd_DAP_SWJ_Sequence(cmd->cmd.tms->num_bits, cmd->cmd.tms->bits);
1505 }
1506
1507 /* TODO: Is there need to call cmsis_dap_flush() for the JTAG_PATHMOVE,
1508  * JTAG_RUNTEST, JTAG_STABLECLOCKS? */
1509 static void cmsis_dap_execute_command(struct jtag_command *cmd)
1510 {
1511         switch (cmd->type) {
1512                 case JTAG_SLEEP:
1513                         cmsis_dap_flush();
1514                         cmsis_dap_execute_sleep(cmd);
1515                         break;
1516                 case JTAG_TLR_RESET:
1517                         cmsis_dap_flush();
1518                         cmsis_dap_execute_tlr_reset(cmd);
1519                         break;
1520                 case JTAG_SCAN:
1521                         cmsis_dap_execute_scan(cmd);
1522                         break;
1523                 case JTAG_PATHMOVE:
1524                         cmsis_dap_execute_pathmove(cmd);
1525                         break;
1526                 case JTAG_RUNTEST:
1527                         cmsis_dap_execute_runtest(cmd);
1528                         break;
1529                 case JTAG_STABLECLOCKS:
1530                         cmsis_dap_execute_stableclocks(cmd);
1531                         break;
1532                 case JTAG_TMS:
1533                         cmsis_dap_execute_tms(cmd);
1534                         break;
1535                 default:
1536                         LOG_ERROR("BUG: unknown JTAG command type 0x%X encountered", cmd->type);
1537                         exit(-1);
1538         }
1539 }
1540
1541 static int cmsis_dap_execute_queue(void)
1542 {
1543         struct jtag_command *cmd = jtag_command_queue;
1544
1545         while (cmd != NULL) {
1546                 cmsis_dap_execute_command(cmd);
1547                 cmd = cmd->next;
1548         }
1549
1550         cmsis_dap_flush();
1551
1552         return ERROR_OK;
1553 }
1554
1555 static int cmsis_dap_speed(int speed)
1556 {
1557         if (speed == 0) {
1558                 LOG_ERROR("RTCK not supported. Set nonzero \"adapter speed\".");
1559                 return ERROR_JTAG_NOT_IMPLEMENTED;
1560         }
1561
1562         return cmsis_dap_cmd_DAP_SWJ_Clock(speed);
1563 }
1564
1565 static int cmsis_dap_speed_div(int speed, int *khz)
1566 {
1567         *khz = speed;
1568         return ERROR_OK;
1569 }
1570
1571 static int cmsis_dap_khz(int khz, int *jtag_speed)
1572 {
1573         *jtag_speed = khz;
1574         return ERROR_OK;
1575 }
1576
1577 COMMAND_HANDLER(cmsis_dap_handle_info_command)
1578 {
1579         if (cmsis_dap_get_version_info() == ERROR_OK)
1580                 cmsis_dap_get_status();
1581
1582         return ERROR_OK;
1583 }
1584
1585 COMMAND_HANDLER(cmsis_dap_handle_cmd_command)
1586 {
1587         int retval;
1588         unsigned i;
1589         uint8_t *command = cmsis_dap_handle->command;
1590
1591         for (i = 0; i < CMD_ARGC; i++)
1592                 command[i] = strtoul(CMD_ARGV[i], NULL, 16);
1593
1594         retval = cmsis_dap_xfer(cmsis_dap_handle, CMD_ARGC);
1595
1596         if (retval != ERROR_OK) {
1597                 LOG_ERROR("CMSIS-DAP command failed.");
1598                 return ERROR_JTAG_DEVICE_ERROR;
1599         }
1600
1601         uint8_t *resp = cmsis_dap_handle->response;
1602         LOG_INFO("Returned data %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8,
1603                 resp[1], resp[2], resp[3], resp[4]);
1604
1605         return ERROR_OK;
1606 }
1607
1608 COMMAND_HANDLER(cmsis_dap_handle_vid_pid_command)
1609 {
1610         if (CMD_ARGC > MAX_USB_IDS * 2) {
1611                 LOG_WARNING("ignoring extra IDs in cmsis_dap_vid_pid "
1612                         "(maximum is %d pairs)", MAX_USB_IDS);
1613                 CMD_ARGC = MAX_USB_IDS * 2;
1614         }
1615         if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
1616                 LOG_WARNING("incomplete cmsis_dap_vid_pid configuration directive");
1617                 if (CMD_ARGC < 2)
1618                         return ERROR_COMMAND_SYNTAX_ERROR;
1619                 /* remove the incomplete trailing id */
1620                 CMD_ARGC -= 1;
1621         }
1622
1623         unsigned i;
1624         for (i = 0; i < CMD_ARGC; i += 2) {
1625                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], cmsis_dap_vid[i >> 1]);
1626                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], cmsis_dap_pid[i >> 1]);
1627         }
1628
1629         /*
1630          * Explicitly terminate, in case there are multiples instances of
1631          * cmsis_dap_vid_pid.
1632          */
1633         cmsis_dap_vid[i >> 1] = cmsis_dap_pid[i >> 1] = 0;
1634
1635         return ERROR_OK;
1636 }
1637
1638 COMMAND_HANDLER(cmsis_dap_handle_serial_command)
1639 {
1640         if (CMD_ARGC == 1)
1641                 cmsis_dap_serial = strdup(CMD_ARGV[0]);
1642         else
1643                 LOG_ERROR("expected exactly one argument to cmsis_dap_serial <serial-number>");
1644
1645         return ERROR_OK;
1646 }
1647
1648 COMMAND_HANDLER(cmsis_dap_handle_backend_command)
1649 {
1650         if (CMD_ARGC == 1) {
1651                 if (strcmp(CMD_ARGV[0], "auto") == 0) {
1652                         cmsis_dap_backend = -1; /* autoselect */
1653                 } else {
1654                         for (unsigned int i = 0; i < ARRAY_SIZE(cmsis_dap_backends); i++) {
1655                                 if (strcasecmp(cmsis_dap_backends[i]->name, CMD_ARGV[0]) == 0) {
1656                                         cmsis_dap_backend = i;
1657                                         return ERROR_OK;
1658                                 }
1659                         }
1660
1661                         LOG_ERROR("invalid backend argument to cmsis_dap_backend <backend>");
1662                 }
1663         } else {
1664                 LOG_ERROR("expected exactly one argument to cmsis_dap_backend <backend>");
1665         }
1666
1667         return ERROR_OK;
1668 }
1669
1670 static const struct command_registration cmsis_dap_subcommand_handlers[] = {
1671         {
1672                 .name = "info",
1673                 .handler = &cmsis_dap_handle_info_command,
1674                 .mode = COMMAND_EXEC,
1675                 .usage = "",
1676                 .help = "show cmsis-dap info",
1677         },
1678         {
1679                 .name = "cmd",
1680                 .handler = &cmsis_dap_handle_cmd_command,
1681                 .mode = COMMAND_EXEC,
1682                 .usage = "",
1683                 .help = "issue cmsis-dap command",
1684         },
1685         COMMAND_REGISTRATION_DONE
1686 };
1687
1688
1689 static const struct command_registration cmsis_dap_command_handlers[] = {
1690         {
1691                 .name = "cmsis-dap",
1692                 .mode = COMMAND_ANY,
1693                 .help = "perform CMSIS-DAP management",
1694                 .usage = "<cmd>",
1695                 .chain = cmsis_dap_subcommand_handlers,
1696         },
1697         {
1698                 .name = "cmsis_dap_vid_pid",
1699                 .handler = &cmsis_dap_handle_vid_pid_command,
1700                 .mode = COMMAND_CONFIG,
1701                 .help = "the vendor ID and product ID of the CMSIS-DAP device",
1702                 .usage = "(vid pid)* ",
1703         },
1704         {
1705                 .name = "cmsis_dap_serial",
1706                 .handler = &cmsis_dap_handle_serial_command,
1707                 .mode = COMMAND_CONFIG,
1708                 .help = "set the serial number of the adapter",
1709                 .usage = "serial_string",
1710         },
1711         {
1712                 .name = "cmsis_dap_backend",
1713                 .handler = &cmsis_dap_handle_backend_command,
1714                 .mode = COMMAND_CONFIG,
1715                 .help = "set the communication backend to use (USB bulk or HID).",
1716                 .usage = "(auto | usb_bulk | hid)",
1717         },
1718 #if BUILD_CMSIS_DAP_USB
1719         {
1720                 .name = "cmsis_dap_usb",
1721                 .chain = cmsis_dap_usb_subcommand_handlers,
1722                 .mode = COMMAND_ANY,
1723                 .help = "USB bulk backend-specific commands",
1724                 .usage = "<cmd>",
1725         },
1726 #endif
1727         COMMAND_REGISTRATION_DONE
1728 };
1729
1730 static const struct swd_driver cmsis_dap_swd_driver = {
1731         .init = cmsis_dap_swd_init,
1732         .switch_seq = cmsis_dap_swd_switch_seq,
1733         .read_reg = cmsis_dap_swd_read_reg,
1734         .write_reg = cmsis_dap_swd_write_reg,
1735         .run = cmsis_dap_swd_run_queue,
1736 };
1737
1738 static const char * const cmsis_dap_transport[] = { "swd", "jtag", NULL };
1739
1740 static struct jtag_interface cmsis_dap_interface = {
1741         .supported = DEBUG_CAP_TMS_SEQ,
1742         .execute_queue = cmsis_dap_execute_queue,
1743 };
1744
1745 struct adapter_driver cmsis_dap_adapter_driver = {
1746         .name = "cmsis-dap",
1747         .transports = cmsis_dap_transport,
1748         .commands = cmsis_dap_command_handlers,
1749
1750         .init = cmsis_dap_init,
1751         .quit = cmsis_dap_quit,
1752         .reset = cmsis_dap_reset,
1753         .speed = cmsis_dap_speed,
1754         .khz = cmsis_dap_khz,
1755         .speed_div = cmsis_dap_speed_div,
1756
1757         .jtag_ops = &cmsis_dap_interface,
1758         .swd_ops = &cmsis_dap_swd_driver,
1759 };