]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/cmsis_dap_usb.c
jtag: cmsis-dap: Issue disconnect before reconnecting
[openocd] / src / jtag / drivers / cmsis_dap_usb.c
1 /***************************************************************************
2  *   Copyright (C) 2014 by Paul Fertser                                    *
3  *   fercerpav@gmail.com                                                   *
4  *                                                                         *
5  *   Copyright (C) 2013 by mike brown                                      *
6  *   mike@theshedworks.org.uk                                              *
7  *                                                                         *
8  *   Copyright (C) 2013 by Spencer Oliver                                  *
9  *   spen@spen-soft.co.uk                                                  *
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program; if not, write to the                         *
23  *   Free Software Foundation, Inc.,                                       *
24  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
25  ***************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include <transport/transport.h>
32 #include <jtag/swd.h>
33 #include <jtag/interface.h>
34 #include <jtag/commands.h>
35 #include <jtag/tcl.h>
36
37 #include <hidapi.h>
38
39 /*
40  * See CMSIS-DAP documentation:
41  * Version 0.01 - Beta.
42  */
43
44 /* USB Config */
45
46 /* Known vid/pid pairs:
47  * VID 0xc251: Keil Software
48  * PID 0xf001: LPC-Link-II CMSIS_DAP
49  * PID 0xf002: OPEN-SDA CMSIS_DAP (Freedom Board)
50  * PID 0x2722: Keil ULINK2 CMSIS-DAP
51  *
52  * VID 0x0d28: mbed Software
53  * PID 0x0204: MBED CMSIS-DAP
54  */
55
56 #define MAX_USB_IDS 8
57 /* vid = pid = 0 marks the end of the list */
58 static uint16_t cmsis_dap_vid[MAX_USB_IDS + 1] = { 0 };
59 static uint16_t cmsis_dap_pid[MAX_USB_IDS + 1] = { 0 };
60 static wchar_t *cmsis_dap_serial;
61 static bool swd_mode;
62
63 #define PACKET_SIZE       (64 + 1)      /* 64 bytes plus report id */
64 #define USB_TIMEOUT       1000
65
66 /* CMSIS-DAP General Commands */
67 #define CMD_DAP_INFO              0x00
68 #define CMD_DAP_LED               0x01
69 #define CMD_DAP_CONNECT           0x02
70 #define CMD_DAP_DISCONNECT        0x03
71 #define CMD_DAP_WRITE_ABORT       0x08
72 #define CMD_DAP_DELAY             0x09
73 #define CMD_DAP_RESET_TARGET      0x0A
74
75 /* CMD_INFO */
76 #define INFO_ID_VID               0x00      /* string */
77 #define INFO_ID_PID               0x02      /* string */
78 #define INFO_ID_SERNUM            0x03      /* string */
79 #define INFO_ID_FW_VER            0x04      /* string */
80 #define INFO_ID_TD_VEND           0x05      /* string */
81 #define INFO_ID_TD_NAME           0x06      /* string */
82 #define INFO_ID_CAPS              0xf0      /* byte */
83 #define INFO_ID_PKT_CNT           0xfe      /* byte */
84 #define INFO_ID_PKT_SZ            0xff      /* short */
85
86 #define INFO_CAPS_SWD             0x01
87 #define INFO_CAPS_JTAG            0x02
88
89 /* CMD_LED */
90 #define LED_ID_CONNECT            0x00
91 #define LED_ID_RUN                0x01
92
93 #define LED_OFF                   0x00
94 #define LED_ON                    0x01
95
96 /* CMD_CONNECT */
97 #define CONNECT_DEFAULT           0x00
98 #define CONNECT_SWD               0x01
99 #define CONNECT_JTAG              0x02
100
101 /* CMSIS-DAP Common SWD/JTAG Commands */
102 #define CMD_DAP_DELAY             0x09
103 #define CMD_DAP_SWJ_PINS          0x10
104 #define CMD_DAP_SWJ_CLOCK         0x11
105 #define CMD_DAP_SWJ_SEQ           0x12
106
107 /*
108  * PINS
109  * Bit 0: SWCLK/TCK
110  * Bit 1: SWDIO/TMS
111  * Bit 2: TDI
112  * Bit 3: TDO
113  * Bit 5: nTRST
114  * Bit 7: nRESET
115  */
116
117 /* CMSIS-DAP SWD Commands */
118 #define CMD_DAP_SWD_CONFIGURE     0x13
119
120 /* CMSIS-DAP JTAG Commands */
121 #define CMD_DAP_JTAG_SEQ          0x14
122 #define CMD_DAP_JTAG_CONFIGURE    0x15
123 #define CMD_DAP_JTAG_IDCODE       0x16
124
125 /* CMSIS-DAP Transfer Commands */
126 #define CMD_DAP_TFER_CONFIGURE    0x04
127 #define CMD_DAP_TFER              0x05
128 #define CMD_DAP_TFER_BLOCK        0x06
129 #define CMD_DAP_TFER_ABORT        0x07
130
131 /* DAP Status Code */
132 #define DAP_OK                    0
133 #define DAP_ERROR                 0xFF
134
135 /* CMSIS-DAP Vendor Commands
136  * None as yet... */
137
138 static const char * const info_caps_str[] = {
139         "SWD  Supported",
140         "JTAG Supported"
141 };
142
143 /* max clock speed (kHz) */
144 #define DAP_MAX_CLOCK             5000
145
146 struct cmsis_dap {
147         hid_device *dev_handle;
148         uint16_t packet_size;
149         uint16_t packet_count;
150         uint8_t *packet_buffer;
151         uint8_t caps;
152         uint8_t mode;
153 };
154
155 struct pending_transfer_result {
156         uint8_t cmd;
157         uint32_t data;
158         void *buffer;
159 };
160
161 static int pending_transfer_count, pending_queue_len;
162 static struct pending_transfer_result *pending_transfers;
163
164 static int queued_retval;
165
166 static struct cmsis_dap *cmsis_dap_handle;
167
168 static int cmsis_dap_usb_open(void)
169 {
170         hid_device *dev = NULL;
171         int i;
172         struct hid_device_info *devs, *cur_dev;
173         unsigned short target_vid, target_pid;
174         wchar_t *target_serial = NULL;
175
176         bool found = false;
177         bool serial_found = false;
178
179         target_vid = 0;
180         target_pid = 0;
181
182         /*
183          * The CMSIS-DAP specification stipulates:
184          * "The Product String must contain "CMSIS-DAP" somewhere in the string. This is used by the
185          * debuggers to identify a CMSIS-DAP compliant Debug Unit that is connected to a host computer."
186          */
187         devs = hid_enumerate(0x0, 0x0);
188         cur_dev = devs;
189         while (NULL != cur_dev) {
190                 if (0 == cmsis_dap_vid[0]) {
191                         if (NULL == cur_dev->product_string) {
192                                 LOG_DEBUG("Cannot read product string of device 0x%x:0x%x",
193                                           cur_dev->vendor_id, cur_dev->product_id);
194                         } else {
195                                 if (wcsstr(cur_dev->product_string, L"CMSIS-DAP")) {
196                                         /* if the user hasn't specified VID:PID *and*
197                                          * product string contains "CMSIS-DAP", pick it
198                                          */
199                                         found = true;
200                                 }
201                         }
202                 } else {
203                         /* otherwise, exhaustively compare against all VID:PID in list */
204                         for (i = 0; cmsis_dap_vid[i] || cmsis_dap_pid[i]; i++) {
205                                 if ((cmsis_dap_vid[i] == cur_dev->vendor_id) && (cmsis_dap_pid[i] == cur_dev->product_id))
206                                         found = true;
207                         }
208
209                         if (cmsis_dap_vid[i] || cmsis_dap_pid[i])
210                                 found = true;
211                 }
212
213                 if (found) {
214                         /* we have found an adapter, so exit further checks */
215                         /* check serial number matches if given */
216                         if (cmsis_dap_serial != NULL) {
217                                 if (wcscmp(cmsis_dap_serial, cur_dev->serial_number) == 0) {
218                                         serial_found = true;
219                                         break;
220                                 }
221                         } else
222                                 break;
223                 }
224
225                 cur_dev = cur_dev->next;
226         }
227
228         if (NULL != cur_dev) {
229                 target_vid = cur_dev->vendor_id;
230                 target_pid = cur_dev->product_id;
231                 if (serial_found)
232                         target_serial = cmsis_dap_serial;
233         }
234
235         hid_free_enumeration(devs);
236
237         if (target_vid == 0 && target_pid == 0) {
238                 LOG_ERROR("unable to find CMSIS-DAP device");
239                 return ERROR_FAIL;
240         }
241
242         if (hid_init() != 0) {
243                 LOG_ERROR("unable to open HIDAPI");
244                 return ERROR_FAIL;
245         }
246
247         dev = hid_open(target_vid, target_pid, target_serial);
248
249         if (dev == NULL) {
250                 LOG_ERROR("unable to open CMSIS-DAP device 0x%x:0x%x", target_vid, target_pid);
251                 return ERROR_FAIL;
252         }
253
254         struct cmsis_dap *dap = malloc(sizeof(struct cmsis_dap));
255         if (dap == NULL) {
256                 LOG_ERROR("unable to allocate memory");
257                 return ERROR_FAIL;
258         }
259
260         dap->dev_handle = dev;
261         dap->caps = 0;
262         dap->mode = 0;
263
264         cmsis_dap_handle = dap;
265
266         /* allocate default packet buffer, may be changed later.
267          * currently with HIDAPI we have no way of getting the output report length
268          * without this info we cannot communicate with the adapter.
269          * For the moment we ahve to hard code the packet size */
270
271         int packet_size = PACKET_SIZE;
272
273         /* atmel cmsis-dap uses 512 byte reports */
274         /* TODO: HID report descriptor should be parsed instead of
275          * hardcoding a match by VID */
276         if (target_vid == 0x03eb)
277                 packet_size = 512 + 1;
278
279         cmsis_dap_handle->packet_buffer = malloc(packet_size);
280         cmsis_dap_handle->packet_size = packet_size;
281
282         if (cmsis_dap_handle->packet_buffer == NULL) {
283                 LOG_ERROR("unable to allocate memory");
284                 return ERROR_FAIL;
285         }
286
287         return ERROR_OK;
288 }
289
290 static void cmsis_dap_usb_close(struct cmsis_dap *dap)
291 {
292         hid_close(dap->dev_handle);
293         hid_exit();
294
295         free(cmsis_dap_handle->packet_buffer);
296         free(cmsis_dap_handle);
297         cmsis_dap_handle = NULL;
298         free(cmsis_dap_serial);
299         cmsis_dap_serial = NULL;
300         free(pending_transfers);
301         pending_transfers = NULL;
302
303         return;
304 }
305
306 /* Send a message and receive the reply */
307 static int cmsis_dap_usb_xfer(struct cmsis_dap *dap, int txlen)
308 {
309         /* Pad the rest of the TX buffer with 0's */
310         memset(dap->packet_buffer + txlen, 0, dap->packet_size - txlen);
311
312         /* write data to device */
313         int retval = hid_write(dap->dev_handle, dap->packet_buffer, dap->packet_size);
314         if (retval == -1) {
315                 LOG_ERROR("error writing data: %ls", hid_error(dap->dev_handle));
316                 return ERROR_FAIL;
317         }
318
319         /* get reply */
320         retval = hid_read_timeout(dap->dev_handle, dap->packet_buffer, dap->packet_size, USB_TIMEOUT);
321         if (retval == -1 || retval == 0) {
322                 LOG_DEBUG("error reading data: %ls", hid_error(dap->dev_handle));
323                 return ERROR_FAIL;
324         }
325
326         return ERROR_OK;
327 }
328
329 static int cmsis_dap_cmd_DAP_SWJ_Pins(uint8_t pins, uint8_t mask, uint32_t delay, uint8_t *input)
330 {
331         int retval;
332         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
333
334         buffer[0] = 0;  /* report number */
335         buffer[1] = CMD_DAP_SWJ_PINS;
336         buffer[2] = pins;
337         buffer[3] = mask;
338         buffer[4] = delay & 0xff;
339         buffer[5] = (delay >> 8) & 0xff;
340         buffer[6] = (delay >> 16) & 0xff;
341         buffer[7] = (delay >> 24) & 0xff;
342         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 8);
343
344         if (retval != ERROR_OK) {
345                 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_PINS failed.");
346                 return ERROR_JTAG_DEVICE_ERROR;
347         }
348
349         if (input)
350                 *input = buffer[1];
351
352         return ERROR_OK;
353 }
354
355 static int cmsis_dap_cmd_DAP_SWJ_Clock(uint32_t swj_clock)
356 {
357         int retval;
358         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
359
360         /* set clock in Hz */
361         swj_clock *= 1000;
362         buffer[0] = 0;  /* report number */
363         buffer[1] = CMD_DAP_SWJ_CLOCK;
364         buffer[2] = swj_clock & 0xff;
365         buffer[3] = (swj_clock >> 8) & 0xff;
366         buffer[4] = (swj_clock >> 16) & 0xff;
367         buffer[5] = (swj_clock >> 24) & 0xff;
368         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 6);
369
370         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
371                 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_CLOCK failed.");
372                 return ERROR_JTAG_DEVICE_ERROR;
373         }
374
375         return ERROR_OK;
376 }
377
378 static int cmsis_dap_cmd_DAP_Info(uint8_t info, uint8_t **data)
379 {
380         int retval;
381         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
382
383         buffer[0] = 0;  /* report number */
384         buffer[1] = CMD_DAP_INFO;
385         buffer[2] = info;
386         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 3);
387
388         if (retval != ERROR_OK) {
389                 LOG_ERROR("CMSIS-DAP command CMD_INFO failed.");
390                 return ERROR_JTAG_DEVICE_ERROR;
391         }
392
393         *data = &(buffer[1]);
394
395         return ERROR_OK;
396 }
397
398 static int cmsis_dap_cmd_DAP_LED(uint8_t leds)
399 {
400         int retval;
401         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
402
403         buffer[0] = 0;  /* report number */
404         buffer[1] = CMD_DAP_LED;
405         buffer[2] = 0x00;
406         buffer[3] = leds;
407         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 4);
408
409         if (retval != ERROR_OK || buffer[1] != 0x00) {
410                 LOG_ERROR("CMSIS-DAP command CMD_LED failed.");
411                 return ERROR_JTAG_DEVICE_ERROR;
412         }
413
414         return ERROR_OK;
415 }
416
417 static int cmsis_dap_cmd_DAP_Connect(uint8_t mode)
418 {
419         int retval;
420         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
421
422         buffer[0] = 0;  /* report number */
423         buffer[1] = CMD_DAP_CONNECT;
424         buffer[2] = mode;
425         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 3);
426
427         if (retval != ERROR_OK) {
428                 LOG_ERROR("CMSIS-DAP command CMD_CONNECT failed.");
429                 return ERROR_JTAG_DEVICE_ERROR;
430         }
431
432         if (buffer[1] != mode) {
433                 LOG_ERROR("CMSIS-DAP failed to connect in mode (%d)", mode);
434                 return ERROR_JTAG_DEVICE_ERROR;
435         }
436
437         return ERROR_OK;
438 }
439
440 static int cmsis_dap_cmd_DAP_Disconnect(void)
441 {
442         int retval;
443         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
444
445         buffer[0] = 0;  /* report number */
446         buffer[1] = CMD_DAP_DISCONNECT;
447         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 2);
448
449         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
450                 LOG_ERROR("CMSIS-DAP command CMD_DISCONNECT failed.");
451                 return ERROR_JTAG_DEVICE_ERROR;
452         }
453
454         return ERROR_OK;
455 }
456
457 static int cmsis_dap_cmd_DAP_TFER_Configure(uint8_t idle, uint16_t retry_count, uint16_t match_retry)
458 {
459         int retval;
460         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
461
462         buffer[0] = 0;  /* report number */
463         buffer[1] = CMD_DAP_TFER_CONFIGURE;
464         buffer[2] = idle;
465         buffer[3] = retry_count & 0xff;
466         buffer[4] = (retry_count >> 8) & 0xff;
467         buffer[5] = match_retry & 0xff;
468         buffer[6] = (match_retry >> 8) & 0xff;
469         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 7);
470
471         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
472                 LOG_ERROR("CMSIS-DAP command CMD_TFER_Configure failed.");
473                 return ERROR_JTAG_DEVICE_ERROR;
474         }
475
476         return ERROR_OK;
477 }
478
479 static int cmsis_dap_cmd_DAP_SWD_Configure(uint8_t cfg)
480 {
481         int retval;
482         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
483
484         buffer[0] = 0;  /* report number */
485         buffer[1] = CMD_DAP_SWD_CONFIGURE;
486         buffer[2] = cfg;
487         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 3);
488
489         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
490                 LOG_ERROR("CMSIS-DAP command CMD_SWD_Configure failed.");
491                 return ERROR_JTAG_DEVICE_ERROR;
492         }
493
494         return ERROR_OK;
495 }
496
497 #if 0
498 static int cmsis_dap_cmd_DAP_Delay(uint16_t delay_us)
499 {
500         int retval;
501         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
502
503         buffer[0] = 0;  /* report number */
504         buffer[1] = CMD_DAP_DELAY;
505         buffer[2] = delay_us & 0xff;
506         buffer[3] = (delay_us >> 8) & 0xff;
507         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 4);
508
509         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
510                 LOG_ERROR("CMSIS-DAP command CMD_Delay failed.");
511                 return ERROR_JTAG_DEVICE_ERROR;
512         }
513
514         return ERROR_OK;
515 }
516 #endif
517
518 static int cmsis_dap_swd_run_queue(struct adiv5_dap *dap)
519 {
520         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
521
522         LOG_DEBUG("Executing %d queued transactions", pending_transfer_count);
523
524         if (queued_retval != ERROR_OK) {
525                 LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
526                 goto skip;
527         }
528
529         if (!pending_transfer_count)
530                 goto skip;
531
532         size_t idx = 0;
533         buffer[idx++] = 0;      /* report number */
534         buffer[idx++] = CMD_DAP_TFER;
535         buffer[idx++] = 0x00;   /* DAP Index */
536         buffer[idx++] = pending_transfer_count;
537
538         for (int i = 0; i < pending_transfer_count; i++) {
539                 uint8_t cmd = pending_transfers[i].cmd;
540                 uint32_t data = pending_transfers[i].data;
541
542                 LOG_DEBUG("%s %s reg %x %"PRIx32,
543                                 cmd & SWD_CMD_APnDP ? "AP" : "DP",
544                                 cmd & SWD_CMD_RnW ? "read" : "write",
545                           (cmd & SWD_CMD_A32) >> 1, data);
546
547                 /* When proper WAIT handling is implemented in the
548                  * common SWD framework, this kludge can be
549                  * removed. However, this might lead to minor
550                  * performance degradation as the adapter wouldn't be
551                  * able to automatically retry anything (because ARM
552                  * has forgotten to implement sticky error flags
553                  * clearing). See also comments regarding
554                  * cmsis_dap_cmd_DAP_TFER_Configure() and
555                  * cmsis_dap_cmd_DAP_SWD_Configure() in
556                  * cmsis_dap_init().
557                  */
558                 if (!(cmd & SWD_CMD_RnW) &&
559                     !(cmd & SWD_CMD_APnDP) &&
560                     (cmd & SWD_CMD_A32) >> 1 == DP_CTRL_STAT &&
561                     (data & CORUNDETECT)) {
562                         LOG_DEBUG("refusing to enable sticky overrun detection");
563                         data &= ~CORUNDETECT;
564                 }
565
566                 buffer[idx++] = (cmd >> 1) & 0x0f;
567                 if (!(cmd & SWD_CMD_RnW)) {
568                         buffer[idx++] = (data) & 0xff;
569                         buffer[idx++] = (data >> 8) & 0xff;
570                         buffer[idx++] = (data >> 16) & 0xff;
571                         buffer[idx++] = (data >> 24) & 0xff;
572                 }
573         }
574
575         queued_retval = cmsis_dap_usb_xfer(cmsis_dap_handle, idx);
576         if (queued_retval != ERROR_OK)
577                 goto skip;
578
579         idx = 2;
580         uint8_t ack = buffer[idx] & 0x07;
581         if (ack != SWD_ACK_OK || (buffer[idx] & 0x08)) {
582                 LOG_DEBUG("SWD ack not OK: %d %s", buffer[idx-1],
583                           ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
584                 queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
585                 goto skip;
586         }
587         idx++;
588
589         if (pending_transfer_count != buffer[1])
590                 LOG_ERROR("CMSIS-DAP transfer count mismatch: expected %d, got %d",
591                           pending_transfer_count, buffer[1]);
592
593         for (int i = 0; i < buffer[1]; i++) {
594                 if (pending_transfers[i].cmd & SWD_CMD_RnW) {
595                         static uint32_t last_read;
596                         uint32_t data = le_to_h_u32(&buffer[idx]);
597                         uint32_t tmp = data;
598                         idx += 4;
599
600                         LOG_DEBUG("Read result: %"PRIx32, data);
601
602                         /* Imitate posted AP reads */
603                         if ((pending_transfers[i].cmd & SWD_CMD_APnDP) ||
604                             ((pending_transfers[i].cmd & SWD_CMD_A32) >> 1 == DP_RDBUFF)) {
605                                 tmp = last_read;
606                                 last_read = data;
607                         }
608
609                         if (pending_transfers[i].buffer)
610                                 *(uint32_t *)pending_transfers[i].buffer = tmp;
611                 }
612         }
613
614 skip:
615         pending_transfer_count = 0;
616         int retval = queued_retval;
617         queued_retval = ERROR_OK;
618
619         return retval;
620 }
621
622 static void cmsis_dap_swd_queue_cmd(struct adiv5_dap *dap, uint8_t cmd, uint32_t *dst, uint32_t data)
623 {
624         if (pending_transfer_count == pending_queue_len) {
625                 /* Not enough room in the queue. Run the queue. */
626                 queued_retval = cmsis_dap_swd_run_queue(dap);
627         }
628
629         if (queued_retval != ERROR_OK)
630                 return;
631
632         pending_transfers[pending_transfer_count].data = data;
633         pending_transfers[pending_transfer_count].cmd = cmd;
634         if (cmd & SWD_CMD_RnW) {
635                 /* Queue a read transaction */
636                 pending_transfers[pending_transfer_count].buffer = dst;
637         }
638         pending_transfer_count++;
639 }
640
641 static void cmsis_dap_swd_write_reg(struct adiv5_dap *dap, uint8_t cmd, uint32_t value)
642 {
643         assert(!(cmd & SWD_CMD_RnW));
644         cmsis_dap_swd_queue_cmd(dap, cmd, NULL, value);
645 }
646
647 static void cmsis_dap_swd_read_reg(struct adiv5_dap *dap, uint8_t cmd, uint32_t *value)
648 {
649         assert(cmd & SWD_CMD_RnW);
650         cmsis_dap_swd_queue_cmd(dap, cmd, value, 0);
651 }
652
653 static int cmsis_dap_get_version_info(void)
654 {
655         uint8_t *data;
656
657         /* INFO_ID_FW_VER - string */
658         int retval = cmsis_dap_cmd_DAP_Info(INFO_ID_FW_VER, &data);
659         if (retval != ERROR_OK)
660                 return retval;
661
662         if (data[0]) /* strlen */
663                 LOG_INFO("CMSIS-DAP: FW Version = %s", &data[1]);
664
665         return ERROR_OK;
666 }
667
668 static int cmsis_dap_get_caps_info(void)
669 {
670         uint8_t *data;
671
672         /* INFO_ID_CAPS - byte */
673         int retval = cmsis_dap_cmd_DAP_Info(INFO_ID_CAPS, &data);
674         if (retval != ERROR_OK)
675                 return retval;
676
677         if (data[0] == 1) {
678                 uint8_t caps = data[1];
679
680                 cmsis_dap_handle->caps = caps;
681
682                 if (caps & INFO_CAPS_SWD)
683                         LOG_INFO("CMSIS-DAP: %s", info_caps_str[0]);
684                 if (caps & INFO_CAPS_JTAG)
685                         LOG_INFO("CMSIS-DAP: %s", info_caps_str[1]);
686         }
687
688         return ERROR_OK;
689 }
690
691 static int cmsis_dap_get_status(void)
692 {
693         uint8_t d;
694
695         int retval = cmsis_dap_cmd_DAP_SWJ_Pins(0, 0, 0, &d);
696
697         if (retval == ERROR_OK) {
698                 LOG_INFO("SWCLK/TCK = %d SWDIO/TMS = %d TDI = %d TDO = %d nTRST = %d nRESET = %d",
699                         (d & (0x01 << 0)) ? 1 : 0,      /* Bit 0: SWCLK/TCK */
700                         (d & (0x01 << 1)) ? 1 : 0,      /* Bit 1: SWDIO/TMS */
701                         (d & (0x01 << 2)) ? 1 : 0,      /* Bit 2: TDI */
702                         (d & (0x01 << 3)) ? 1 : 0,      /* Bit 3: TDO */
703                         (d & (0x01 << 5)) ? 1 : 0,      /* Bit 5: nTRST */
704                         (d & (0x01 << 7)) ? 1 : 0);     /* Bit 7: nRESET */
705         }
706
707         return retval;
708 }
709
710 static int cmsis_dap_swd_switch_seq(struct adiv5_dap *dap, enum swd_special_seq seq)
711 {
712         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
713         const uint8_t *s;
714         unsigned int s_len;
715         int retval;
716
717         /* First disconnect before connecting, Atmel EDBG needs it for SAMD/R/L/C */
718         cmsis_dap_cmd_DAP_Disconnect();
719
720         /* When we are reconnecting, DAP_Connect needs to be rerun, at
721          * least on Keil ULINK-ME */
722         retval = cmsis_dap_cmd_DAP_Connect(seq == LINE_RESET || seq == JTAG_TO_SWD ?
723                                            CONNECT_SWD : CONNECT_JTAG);
724         if (retval != ERROR_OK)
725                 return retval;
726
727         switch (seq) {
728         case LINE_RESET:
729                 LOG_DEBUG("SWD line reset");
730                 s = swd_seq_line_reset;
731                 s_len = swd_seq_line_reset_len;
732                 break;
733         case JTAG_TO_SWD:
734                 LOG_DEBUG("JTAG-to-SWD");
735                 s = swd_seq_jtag_to_swd;
736                 s_len = swd_seq_jtag_to_swd_len;
737                 break;
738         case SWD_TO_JTAG:
739                 LOG_DEBUG("SWD-to-JTAG");
740                 s = swd_seq_swd_to_jtag;
741                 s_len = swd_seq_swd_to_jtag_len;
742                 break;
743         default:
744                 LOG_ERROR("Sequence %d not supported", seq);
745                 return ERROR_FAIL;
746         }
747
748         buffer[0] = 0;  /* report number */
749         buffer[1] = CMD_DAP_SWJ_SEQ;
750         buffer[2] = s_len;
751         bit_copy(&buffer[3], 0, s, 0, s_len);
752
753         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, DIV_ROUND_UP(s_len, 8) + 3);
754
755         if (retval != ERROR_OK || buffer[1] != DAP_OK)
756                 return ERROR_FAIL;
757
758         return ERROR_OK;
759 }
760
761 static int cmsis_dap_swd_open(void)
762 {
763         int retval;
764
765         if (cmsis_dap_handle == NULL) {
766                 /* SWD init */
767                 retval = cmsis_dap_usb_open();
768                 if (retval != ERROR_OK)
769                         return retval;
770
771                 retval = cmsis_dap_get_caps_info();
772                 if (retval != ERROR_OK)
773                         return retval;
774         }
775
776         if (!(cmsis_dap_handle->caps & INFO_CAPS_SWD)) {
777                 LOG_ERROR("CMSIS-DAP: SWD not supported");
778                 return ERROR_JTAG_DEVICE_ERROR;
779         }
780
781         retval = cmsis_dap_cmd_DAP_Connect(CONNECT_SWD);
782         if (retval != ERROR_OK)
783                 return retval;
784
785         /* Add more setup here.??... */
786
787         LOG_INFO("CMSIS-DAP: Interface Initialised (SWD)");
788         return ERROR_OK;
789 }
790
791 static int cmsis_dap_init(void)
792 {
793         int retval;
794         uint8_t *data;
795
796         if (swd_mode) {
797                 retval = cmsis_dap_swd_open();
798                 if (retval != ERROR_OK)
799                         return retval;
800         }
801
802         if (cmsis_dap_handle == NULL) {
803
804                 /* JTAG init */
805                 retval = cmsis_dap_usb_open();
806                 if (retval != ERROR_OK)
807                         return retval;
808
809                 retval = cmsis_dap_get_caps_info();
810                 if (retval != ERROR_OK)
811                         return retval;
812
813                 /* Connect in JTAG mode */
814                 if (!(cmsis_dap_handle->caps & INFO_CAPS_JTAG)) {
815                         LOG_ERROR("CMSIS-DAP: JTAG not supported");
816                         return ERROR_JTAG_DEVICE_ERROR;
817                 }
818
819                 retval = cmsis_dap_cmd_DAP_Connect(CONNECT_JTAG);
820                 if (retval != ERROR_OK)
821                         return retval;
822
823                 LOG_INFO("CMSIS-DAP: Interface Initialised (JTAG)");
824         }
825
826         retval = cmsis_dap_get_version_info();
827         if (retval != ERROR_OK)
828                 return retval;
829
830         /* INFO_ID_PKT_SZ - short */
831         retval = cmsis_dap_cmd_DAP_Info(INFO_ID_PKT_SZ, &data);
832         if (retval != ERROR_OK)
833                 return retval;
834
835         if (data[0] == 2) {  /* short */
836                 uint16_t pkt_sz = data[1] + (data[2] << 8);
837
838                 /* 4 bytes of command header + 5 bytes per register
839                  * write. For bulk read sequences just 4 bytes are
840                  * needed per transfer, so this is suboptimal. */
841                 pending_queue_len = (pkt_sz - 4) / 5;
842                 pending_transfers = malloc(pending_queue_len * sizeof(*pending_transfers));
843                 if (!pending_transfers) {
844                         LOG_ERROR("Unable to allocate memory for CMSIS-DAP queue");
845                         return ERROR_FAIL;
846                 }
847
848                 if (cmsis_dap_handle->packet_size != pkt_sz + 1) {
849                         /* reallocate buffer */
850                         cmsis_dap_handle->packet_size = pkt_sz + 1;
851                         cmsis_dap_handle->packet_buffer = realloc(cmsis_dap_handle->packet_buffer,
852                                         cmsis_dap_handle->packet_size);
853                         if (cmsis_dap_handle->packet_buffer == NULL) {
854                                 LOG_ERROR("unable to reallocate memory");
855                                 return ERROR_FAIL;
856                         }
857                 }
858
859                 LOG_DEBUG("CMSIS-DAP: Packet Size = %" PRId16, pkt_sz);
860         }
861
862         /* INFO_ID_PKT_CNT - byte */
863         retval = cmsis_dap_cmd_DAP_Info(INFO_ID_PKT_CNT, &data);
864         if (retval != ERROR_OK)
865                 return retval;
866
867         if (data[0] == 1) { /* byte */
868                 uint16_t pkt_cnt = data[1];
869                 cmsis_dap_handle->packet_count = pkt_cnt;
870                 LOG_DEBUG("CMSIS-DAP: Packet Count = %" PRId16, pkt_cnt);
871         }
872
873         retval = cmsis_dap_get_status();
874         if (retval != ERROR_OK)
875                 return ERROR_FAIL;
876
877         /* Now try to connect to the target
878          * TODO: This is all SWD only @ present */
879         retval = cmsis_dap_cmd_DAP_SWJ_Clock(jtag_get_speed_khz());
880         if (retval != ERROR_OK)
881                 return ERROR_FAIL;
882
883         /* Ask CMSIS-DAP to automatically retry on receiving WAIT for
884          * up to 64 times. This must be changed to 0 if sticky
885          * overrun detection is enabled. */
886         retval = cmsis_dap_cmd_DAP_TFER_Configure(0, 64, 0);
887         if (retval != ERROR_OK)
888                 return ERROR_FAIL;
889         /* Data Phase (bit 2) must be set to 1 if sticky overrun
890          * detection is enabled */
891         retval = cmsis_dap_cmd_DAP_SWD_Configure(0);    /* 1 TRN, no Data Phase */
892         if (retval != ERROR_OK)
893                 return ERROR_FAIL;
894
895         retval = cmsis_dap_cmd_DAP_LED(0x03);           /* Both LEDs on */
896         if (retval != ERROR_OK)
897                 return ERROR_FAIL;
898
899         /* support connecting with srst asserted */
900         enum reset_types jtag_reset_config = jtag_get_reset_config();
901
902         if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
903                 if (jtag_reset_config & RESET_SRST_NO_GATING) {
904                         retval = cmsis_dap_cmd_DAP_SWJ_Pins(0, (1 << 7), 0, NULL);
905                         if (retval != ERROR_OK)
906                                 return ERROR_FAIL;
907                         LOG_INFO("Connecting under reset");
908                 }
909         }
910
911         cmsis_dap_cmd_DAP_LED(0x00);                    /* Both LEDs off */
912
913         LOG_INFO("CMSIS-DAP: Interface ready");
914
915         return ERROR_OK;
916 }
917
918 static int cmsis_dap_swd_init(void)
919 {
920         swd_mode = true;
921         return ERROR_OK;
922 }
923
924 static int cmsis_dap_quit(void)
925 {
926         cmsis_dap_cmd_DAP_Disconnect();
927         cmsis_dap_cmd_DAP_LED(0x00);            /* Both LEDs off */
928
929         cmsis_dap_usb_close(cmsis_dap_handle);
930
931         return ERROR_OK;
932 }
933
934 static void cmsis_dap_execute_reset(struct jtag_command *cmd)
935 {
936         int retval = cmsis_dap_cmd_DAP_SWJ_Pins(cmd->cmd.reset->srst ? 0 : (1 << 7), \
937                         (1 << 7), 0, NULL);
938         if (retval != ERROR_OK)
939                 LOG_ERROR("CMSIS-DAP: Interface reset failed");
940 }
941
942 static void cmsis_dap_execute_sleep(struct jtag_command *cmd)
943 {
944 #if 0
945         int retval = cmsis_dap_cmd_DAP_Delay(cmd->cmd.sleep->us);
946         if (retval != ERROR_OK)
947 #endif
948                 jtag_sleep(cmd->cmd.sleep->us);
949 }
950
951 static void cmsis_dap_execute_command(struct jtag_command *cmd)
952 {
953         switch (cmd->type) {
954                 case JTAG_RESET:
955                         cmsis_dap_execute_reset(cmd);
956                         break;
957                 case JTAG_SLEEP:
958                         cmsis_dap_execute_sleep(cmd);
959                         break;
960                 default:
961                         LOG_ERROR("BUG: unknown JTAG command type encountered");
962                         exit(-1);
963         }
964 }
965
966 static int cmsis_dap_execute_queue(void)
967 {
968         struct jtag_command *cmd = jtag_command_queue;
969
970         while (cmd != NULL) {
971                 cmsis_dap_execute_command(cmd);
972                 cmd = cmd->next;
973         }
974
975         return ERROR_OK;
976 }
977
978 static int cmsis_dap_speed(int speed)
979 {
980         if (speed > DAP_MAX_CLOCK) {
981                 LOG_INFO("reduce speed request: %dkHz to %dkHz maximum", speed, DAP_MAX_CLOCK);
982                 speed = DAP_MAX_CLOCK;
983         }
984
985         if (speed == 0) {
986                 LOG_INFO("RTCK not supported");
987                 return ERROR_JTAG_NOT_IMPLEMENTED;
988         }
989
990         return cmsis_dap_cmd_DAP_SWJ_Clock(speed);
991 }
992
993 static int cmsis_dap_speed_div(int speed, int *khz)
994 {
995         *khz = speed;
996         return ERROR_OK;
997 }
998
999 static int cmsis_dap_khz(int khz, int *jtag_speed)
1000 {
1001         *jtag_speed = khz;
1002         return ERROR_OK;
1003 }
1004
1005 static int_least32_t cmsis_dap_swd_frequency(struct adiv5_dap *dap, int_least32_t hz)
1006 {
1007         if (hz > 0)
1008                 cmsis_dap_speed(hz / 1000);
1009
1010         return hz;
1011 }
1012
1013 COMMAND_HANDLER(cmsis_dap_handle_info_command)
1014 {
1015         if (cmsis_dap_get_version_info() == ERROR_OK)
1016                 cmsis_dap_get_status();
1017
1018         return ERROR_OK;
1019 }
1020
1021 COMMAND_HANDLER(cmsis_dap_handle_vid_pid_command)
1022 {
1023         if (CMD_ARGC > MAX_USB_IDS * 2) {
1024                 LOG_WARNING("ignoring extra IDs in cmsis_dap_vid_pid "
1025                         "(maximum is %d pairs)", MAX_USB_IDS);
1026                 CMD_ARGC = MAX_USB_IDS * 2;
1027         }
1028         if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
1029                 LOG_WARNING("incomplete cmsis_dap_vid_pid configuration directive");
1030                 if (CMD_ARGC < 2)
1031                         return ERROR_COMMAND_SYNTAX_ERROR;
1032                 /* remove the incomplete trailing id */
1033                 CMD_ARGC -= 1;
1034         }
1035
1036         unsigned i;
1037         for (i = 0; i < CMD_ARGC; i += 2) {
1038                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], cmsis_dap_vid[i >> 1]);
1039                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], cmsis_dap_pid[i >> 1]);
1040         }
1041
1042         /*
1043          * Explicitly terminate, in case there are multiples instances of
1044          * cmsis_dap_vid_pid.
1045          */
1046         cmsis_dap_vid[i >> 1] = cmsis_dap_pid[i >> 1] = 0;
1047
1048         return ERROR_OK;
1049 }
1050
1051 COMMAND_HANDLER(cmsis_dap_handle_serial_command)
1052 {
1053         if (CMD_ARGC == 1) {
1054                 size_t len = mbstowcs(NULL, CMD_ARGV[0], 0);
1055                 cmsis_dap_serial = calloc(len + 1, sizeof(wchar_t));
1056                 if (cmsis_dap_serial == NULL) {
1057                         LOG_ERROR("unable to allocate memory");
1058                         return ERROR_OK;
1059                 }
1060                 if (mbstowcs(cmsis_dap_serial, CMD_ARGV[0], len + 1) == (size_t)-1) {
1061                         free(cmsis_dap_serial);
1062                         cmsis_dap_serial = NULL;
1063                         LOG_ERROR("unable to convert serial");
1064                 }
1065         } else {
1066                 LOG_ERROR("expected exactly one argument to cmsis_dap_serial <serial-number>");
1067         }
1068
1069         return ERROR_OK;
1070 }
1071
1072 static const struct command_registration cmsis_dap_subcommand_handlers[] = {
1073         {
1074                 .name = "info",
1075                 .handler = &cmsis_dap_handle_info_command,
1076                 .mode = COMMAND_EXEC,
1077                 .usage = "",
1078                 .help = "show cmsis-dap info",
1079         },
1080         COMMAND_REGISTRATION_DONE
1081 };
1082
1083 static const struct command_registration cmsis_dap_command_handlers[] = {
1084         {
1085                 .name = "cmsis-dap",
1086                 .mode = COMMAND_ANY,
1087                 .help = "perform CMSIS-DAP management",
1088                 .usage = "<cmd>",
1089                 .chain = cmsis_dap_subcommand_handlers,
1090         },
1091         {
1092                 .name = "cmsis_dap_vid_pid",
1093                 .handler = &cmsis_dap_handle_vid_pid_command,
1094                 .mode = COMMAND_CONFIG,
1095                 .help = "the vendor ID and product ID of the CMSIS-DAP device",
1096                 .usage = "(vid pid)* ",
1097         },
1098         {
1099                 .name = "cmsis_dap_serial",
1100                 .handler = &cmsis_dap_handle_serial_command,
1101                 .mode = COMMAND_CONFIG,
1102                 .help = "set the serial number of the adapter",
1103                 .usage = "serial_string",
1104         },
1105         COMMAND_REGISTRATION_DONE
1106 };
1107
1108 static const struct swd_driver cmsis_dap_swd_driver = {
1109         .init = cmsis_dap_swd_init,
1110         .frequency = cmsis_dap_swd_frequency,
1111         .switch_seq = cmsis_dap_swd_switch_seq,
1112         .read_reg = cmsis_dap_swd_read_reg,
1113         .write_reg = cmsis_dap_swd_write_reg,
1114         .run = cmsis_dap_swd_run_queue,
1115 };
1116
1117 static const char * const cmsis_dap_transport[] = { "swd", NULL };
1118
1119 struct jtag_interface cmsis_dap_interface = {
1120         .name = "cmsis-dap",
1121         .commands = cmsis_dap_command_handlers,
1122         .swd = &cmsis_dap_swd_driver,
1123         .transports = cmsis_dap_transport,
1124
1125         .execute_queue = cmsis_dap_execute_queue,
1126         .speed = cmsis_dap_speed,
1127         .speed_div = cmsis_dap_speed_div,
1128         .khz = cmsis_dap_khz,
1129         .init = cmsis_dap_init,
1130         .quit = cmsis_dap_quit,
1131 };