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