]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/cmsis_dap_usb.c
cmsis-dap: Fix CMSIS-DAP serial number processing.
[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 ((cur_dev->serial_number != NULL) && wcscmp(cmsis_dap_serial, cur_dev->serial_number) == 0) {
218                                         serial_found = true;
219                                         break;
220                                 }
221                         } else
222                                 break;
223
224                         found = false;
225                 }
226
227                 cur_dev = cur_dev->next;
228         }
229
230         if (NULL != cur_dev) {
231                 target_vid = cur_dev->vendor_id;
232                 target_pid = cur_dev->product_id;
233                 if (serial_found)
234                         target_serial = cmsis_dap_serial;
235         }
236
237         hid_free_enumeration(devs);
238
239         if (target_vid == 0 && target_pid == 0) {
240                 LOG_ERROR("unable to find CMSIS-DAP device");
241                 return ERROR_FAIL;
242         }
243
244         if (hid_init() != 0) {
245                 LOG_ERROR("unable to open HIDAPI");
246                 return ERROR_FAIL;
247         }
248
249         dev = hid_open(target_vid, target_pid, target_serial);
250
251         if (dev == NULL) {
252                 LOG_ERROR("unable to open CMSIS-DAP device 0x%x:0x%x", target_vid, target_pid);
253                 return ERROR_FAIL;
254         }
255
256         struct cmsis_dap *dap = malloc(sizeof(struct cmsis_dap));
257         if (dap == NULL) {
258                 LOG_ERROR("unable to allocate memory");
259                 return ERROR_FAIL;
260         }
261
262         dap->dev_handle = dev;
263         dap->caps = 0;
264         dap->mode = 0;
265
266         cmsis_dap_handle = dap;
267
268         /* allocate default packet buffer, may be changed later.
269          * currently with HIDAPI we have no way of getting the output report length
270          * without this info we cannot communicate with the adapter.
271          * For the moment we ahve to hard code the packet size */
272
273         int packet_size = PACKET_SIZE;
274
275         /* atmel cmsis-dap uses 512 byte reports */
276         /* TODO: HID report descriptor should be parsed instead of
277          * hardcoding a match by VID */
278         if (target_vid == 0x03eb)
279                 packet_size = 512 + 1;
280
281         cmsis_dap_handle->packet_buffer = malloc(packet_size);
282         cmsis_dap_handle->packet_size = packet_size;
283
284         if (cmsis_dap_handle->packet_buffer == NULL) {
285                 LOG_ERROR("unable to allocate memory");
286                 return ERROR_FAIL;
287         }
288
289         return ERROR_OK;
290 }
291
292 static void cmsis_dap_usb_close(struct cmsis_dap *dap)
293 {
294         hid_close(dap->dev_handle);
295         hid_exit();
296
297         free(cmsis_dap_handle->packet_buffer);
298         free(cmsis_dap_handle);
299         cmsis_dap_handle = NULL;
300         free(cmsis_dap_serial);
301         cmsis_dap_serial = NULL;
302         free(pending_transfers);
303         pending_transfers = NULL;
304
305         return;
306 }
307
308 /* Send a message and receive the reply */
309 static int cmsis_dap_usb_xfer(struct cmsis_dap *dap, int txlen)
310 {
311         /* Pad the rest of the TX buffer with 0's */
312         memset(dap->packet_buffer + txlen, 0, dap->packet_size - txlen);
313
314         /* write data to device */
315         int retval = hid_write(dap->dev_handle, dap->packet_buffer, dap->packet_size);
316         if (retval == -1) {
317                 LOG_ERROR("error writing data: %ls", hid_error(dap->dev_handle));
318                 return ERROR_FAIL;
319         }
320
321         /* get reply */
322         retval = hid_read_timeout(dap->dev_handle, dap->packet_buffer, dap->packet_size, USB_TIMEOUT);
323         if (retval == -1 || retval == 0) {
324                 LOG_DEBUG("error reading data: %ls", hid_error(dap->dev_handle));
325                 return ERROR_FAIL;
326         }
327
328         return ERROR_OK;
329 }
330
331 static int cmsis_dap_cmd_DAP_SWJ_Pins(uint8_t pins, uint8_t mask, uint32_t delay, uint8_t *input)
332 {
333         int retval;
334         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
335
336         buffer[0] = 0;  /* report number */
337         buffer[1] = CMD_DAP_SWJ_PINS;
338         buffer[2] = pins;
339         buffer[3] = mask;
340         buffer[4] = delay & 0xff;
341         buffer[5] = (delay >> 8) & 0xff;
342         buffer[6] = (delay >> 16) & 0xff;
343         buffer[7] = (delay >> 24) & 0xff;
344         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 8);
345
346         if (retval != ERROR_OK) {
347                 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_PINS failed.");
348                 return ERROR_JTAG_DEVICE_ERROR;
349         }
350
351         if (input)
352                 *input = buffer[1];
353
354         return ERROR_OK;
355 }
356
357 static int cmsis_dap_cmd_DAP_SWJ_Clock(uint32_t swj_clock)
358 {
359         int retval;
360         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
361
362         /* set clock in Hz */
363         swj_clock *= 1000;
364         buffer[0] = 0;  /* report number */
365         buffer[1] = CMD_DAP_SWJ_CLOCK;
366         buffer[2] = swj_clock & 0xff;
367         buffer[3] = (swj_clock >> 8) & 0xff;
368         buffer[4] = (swj_clock >> 16) & 0xff;
369         buffer[5] = (swj_clock >> 24) & 0xff;
370         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 6);
371
372         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
373                 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_CLOCK failed.");
374                 return ERROR_JTAG_DEVICE_ERROR;
375         }
376
377         return ERROR_OK;
378 }
379
380 static int cmsis_dap_cmd_DAP_Info(uint8_t info, uint8_t **data)
381 {
382         int retval;
383         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
384
385         buffer[0] = 0;  /* report number */
386         buffer[1] = CMD_DAP_INFO;
387         buffer[2] = info;
388         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 3);
389
390         if (retval != ERROR_OK) {
391                 LOG_ERROR("CMSIS-DAP command CMD_INFO failed.");
392                 return ERROR_JTAG_DEVICE_ERROR;
393         }
394
395         *data = &(buffer[1]);
396
397         return ERROR_OK;
398 }
399
400 static int cmsis_dap_cmd_DAP_LED(uint8_t leds)
401 {
402         int retval;
403         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
404
405         buffer[0] = 0;  /* report number */
406         buffer[1] = CMD_DAP_LED;
407         buffer[2] = 0x00;
408         buffer[3] = leds;
409         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 4);
410
411         if (retval != ERROR_OK || buffer[1] != 0x00) {
412                 LOG_ERROR("CMSIS-DAP command CMD_LED failed.");
413                 return ERROR_JTAG_DEVICE_ERROR;
414         }
415
416         return ERROR_OK;
417 }
418
419 static int cmsis_dap_cmd_DAP_Connect(uint8_t mode)
420 {
421         int retval;
422         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
423
424         buffer[0] = 0;  /* report number */
425         buffer[1] = CMD_DAP_CONNECT;
426         buffer[2] = mode;
427         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 3);
428
429         if (retval != ERROR_OK) {
430                 LOG_ERROR("CMSIS-DAP command CMD_CONNECT failed.");
431                 return ERROR_JTAG_DEVICE_ERROR;
432         }
433
434         if (buffer[1] != mode) {
435                 LOG_ERROR("CMSIS-DAP failed to connect in mode (%d)", mode);
436                 return ERROR_JTAG_DEVICE_ERROR;
437         }
438
439         return ERROR_OK;
440 }
441
442 static int cmsis_dap_cmd_DAP_Disconnect(void)
443 {
444         int retval;
445         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
446
447         buffer[0] = 0;  /* report number */
448         buffer[1] = CMD_DAP_DISCONNECT;
449         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 2);
450
451         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
452                 LOG_ERROR("CMSIS-DAP command CMD_DISCONNECT failed.");
453                 return ERROR_JTAG_DEVICE_ERROR;
454         }
455
456         return ERROR_OK;
457 }
458
459 static int cmsis_dap_cmd_DAP_TFER_Configure(uint8_t idle, uint16_t retry_count, uint16_t match_retry)
460 {
461         int retval;
462         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
463
464         buffer[0] = 0;  /* report number */
465         buffer[1] = CMD_DAP_TFER_CONFIGURE;
466         buffer[2] = idle;
467         buffer[3] = retry_count & 0xff;
468         buffer[4] = (retry_count >> 8) & 0xff;
469         buffer[5] = match_retry & 0xff;
470         buffer[6] = (match_retry >> 8) & 0xff;
471         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 7);
472
473         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
474                 LOG_ERROR("CMSIS-DAP command CMD_TFER_Configure failed.");
475                 return ERROR_JTAG_DEVICE_ERROR;
476         }
477
478         return ERROR_OK;
479 }
480
481 static int cmsis_dap_cmd_DAP_SWD_Configure(uint8_t cfg)
482 {
483         int retval;
484         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
485
486         buffer[0] = 0;  /* report number */
487         buffer[1] = CMD_DAP_SWD_CONFIGURE;
488         buffer[2] = cfg;
489         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 3);
490
491         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
492                 LOG_ERROR("CMSIS-DAP command CMD_SWD_Configure failed.");
493                 return ERROR_JTAG_DEVICE_ERROR;
494         }
495
496         return ERROR_OK;
497 }
498
499 #if 0
500 static int cmsis_dap_cmd_DAP_Delay(uint16_t delay_us)
501 {
502         int retval;
503         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
504
505         buffer[0] = 0;  /* report number */
506         buffer[1] = CMD_DAP_DELAY;
507         buffer[2] = delay_us & 0xff;
508         buffer[3] = (delay_us >> 8) & 0xff;
509         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 4);
510
511         if (retval != ERROR_OK || buffer[1] != DAP_OK) {
512                 LOG_ERROR("CMSIS-DAP command CMD_Delay failed.");
513                 return ERROR_JTAG_DEVICE_ERROR;
514         }
515
516         return ERROR_OK;
517 }
518 #endif
519
520 static int cmsis_dap_swd_run_queue(void)
521 {
522         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
523
524         LOG_DEBUG("Executing %d queued transactions", pending_transfer_count);
525
526         if (queued_retval != ERROR_OK) {
527                 LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
528                 goto skip;
529         }
530
531         if (!pending_transfer_count)
532                 goto skip;
533
534         size_t idx = 0;
535         buffer[idx++] = 0;      /* report number */
536         buffer[idx++] = CMD_DAP_TFER;
537         buffer[idx++] = 0x00;   /* DAP Index */
538         buffer[idx++] = pending_transfer_count;
539
540         for (int i = 0; i < pending_transfer_count; i++) {
541                 uint8_t cmd = pending_transfers[i].cmd;
542                 uint32_t data = pending_transfers[i].data;
543
544                 LOG_DEBUG("%s %s reg %x %"PRIx32,
545                                 cmd & SWD_CMD_APnDP ? "AP" : "DP",
546                                 cmd & SWD_CMD_RnW ? "read" : "write",
547                           (cmd & SWD_CMD_A32) >> 1, data);
548
549                 /* When proper WAIT handling is implemented in the
550                  * common SWD framework, this kludge can be
551                  * removed. However, this might lead to minor
552                  * performance degradation as the adapter wouldn't be
553                  * able to automatically retry anything (because ARM
554                  * has forgotten to implement sticky error flags
555                  * clearing). See also comments regarding
556                  * cmsis_dap_cmd_DAP_TFER_Configure() and
557                  * cmsis_dap_cmd_DAP_SWD_Configure() in
558                  * cmsis_dap_init().
559                  */
560                 if (!(cmd & SWD_CMD_RnW) &&
561                     !(cmd & SWD_CMD_APnDP) &&
562                     (cmd & SWD_CMD_A32) >> 1 == DP_CTRL_STAT &&
563                     (data & CORUNDETECT)) {
564                         LOG_DEBUG("refusing to enable sticky overrun detection");
565                         data &= ~CORUNDETECT;
566                 }
567
568                 buffer[idx++] = (cmd >> 1) & 0x0f;
569                 if (!(cmd & SWD_CMD_RnW)) {
570                         buffer[idx++] = (data) & 0xff;
571                         buffer[idx++] = (data >> 8) & 0xff;
572                         buffer[idx++] = (data >> 16) & 0xff;
573                         buffer[idx++] = (data >> 24) & 0xff;
574                 }
575         }
576
577         queued_retval = cmsis_dap_usb_xfer(cmsis_dap_handle, idx);
578         if (queued_retval != ERROR_OK)
579                 goto skip;
580
581         idx = 2;
582         uint8_t ack = buffer[idx] & 0x07;
583         if (ack != SWD_ACK_OK || (buffer[idx] & 0x08)) {
584                 LOG_DEBUG("SWD ack not OK: %d %s", buffer[idx-1],
585                           ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
586                 queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
587                 goto skip;
588         }
589         idx++;
590
591         if (pending_transfer_count != buffer[1])
592                 LOG_ERROR("CMSIS-DAP transfer count mismatch: expected %d, got %d",
593                           pending_transfer_count, buffer[1]);
594
595         for (int i = 0; i < buffer[1]; i++) {
596                 if (pending_transfers[i].cmd & SWD_CMD_RnW) {
597                         static uint32_t last_read;
598                         uint32_t data = le_to_h_u32(&buffer[idx]);
599                         uint32_t tmp = data;
600                         idx += 4;
601
602                         LOG_DEBUG("Read result: %"PRIx32, data);
603
604                         /* Imitate posted AP reads */
605                         if ((pending_transfers[i].cmd & SWD_CMD_APnDP) ||
606                             ((pending_transfers[i].cmd & SWD_CMD_A32) >> 1 == DP_RDBUFF)) {
607                                 tmp = last_read;
608                                 last_read = data;
609                         }
610
611                         if (pending_transfers[i].buffer)
612                                 *(uint32_t *)pending_transfers[i].buffer = tmp;
613                 }
614         }
615
616 skip:
617         pending_transfer_count = 0;
618         int retval = queued_retval;
619         queued_retval = ERROR_OK;
620
621         return retval;
622 }
623
624 static void cmsis_dap_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data)
625 {
626         if (pending_transfer_count == pending_queue_len) {
627                 /* Not enough room in the queue. Run the queue. */
628                 queued_retval = cmsis_dap_swd_run_queue();
629         }
630
631         if (queued_retval != ERROR_OK)
632                 return;
633
634         pending_transfers[pending_transfer_count].data = data;
635         pending_transfers[pending_transfer_count].cmd = cmd;
636         if (cmd & SWD_CMD_RnW) {
637                 /* Queue a read transaction */
638                 pending_transfers[pending_transfer_count].buffer = dst;
639         }
640         pending_transfer_count++;
641 }
642
643 static void cmsis_dap_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
644 {
645         assert(!(cmd & SWD_CMD_RnW));
646         cmsis_dap_swd_queue_cmd(cmd, NULL, value);
647 }
648
649 static void cmsis_dap_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
650 {
651         assert(cmd & SWD_CMD_RnW);
652         cmsis_dap_swd_queue_cmd(cmd, value, 0);
653 }
654
655 static int cmsis_dap_get_version_info(void)
656 {
657         uint8_t *data;
658
659         /* INFO_ID_FW_VER - string */
660         int retval = cmsis_dap_cmd_DAP_Info(INFO_ID_FW_VER, &data);
661         if (retval != ERROR_OK)
662                 return retval;
663
664         if (data[0]) /* strlen */
665                 LOG_INFO("CMSIS-DAP: FW Version = %s", &data[1]);
666
667         return ERROR_OK;
668 }
669
670 static int cmsis_dap_get_caps_info(void)
671 {
672         uint8_t *data;
673
674         /* INFO_ID_CAPS - byte */
675         int retval = cmsis_dap_cmd_DAP_Info(INFO_ID_CAPS, &data);
676         if (retval != ERROR_OK)
677                 return retval;
678
679         if (data[0] == 1) {
680                 uint8_t caps = data[1];
681
682                 cmsis_dap_handle->caps = caps;
683
684                 if (caps & INFO_CAPS_SWD)
685                         LOG_INFO("CMSIS-DAP: %s", info_caps_str[0]);
686                 if (caps & INFO_CAPS_JTAG)
687                         LOG_INFO("CMSIS-DAP: %s", info_caps_str[1]);
688         }
689
690         return ERROR_OK;
691 }
692
693 static int cmsis_dap_get_status(void)
694 {
695         uint8_t d;
696
697         int retval = cmsis_dap_cmd_DAP_SWJ_Pins(0, 0, 0, &d);
698
699         if (retval == ERROR_OK) {
700                 LOG_INFO("SWCLK/TCK = %d SWDIO/TMS = %d TDI = %d TDO = %d nTRST = %d nRESET = %d",
701                         (d & (0x01 << 0)) ? 1 : 0,      /* Bit 0: SWCLK/TCK */
702                         (d & (0x01 << 1)) ? 1 : 0,      /* Bit 1: SWDIO/TMS */
703                         (d & (0x01 << 2)) ? 1 : 0,      /* Bit 2: TDI */
704                         (d & (0x01 << 3)) ? 1 : 0,      /* Bit 3: TDO */
705                         (d & (0x01 << 5)) ? 1 : 0,      /* Bit 5: nTRST */
706                         (d & (0x01 << 7)) ? 1 : 0);     /* Bit 7: nRESET */
707         }
708
709         return retval;
710 }
711
712 static int cmsis_dap_swd_switch_seq(enum swd_special_seq seq)
713 {
714         uint8_t *buffer = cmsis_dap_handle->packet_buffer;
715         const uint8_t *s;
716         unsigned int s_len;
717         int retval;
718
719         /* First disconnect before connecting, Atmel EDBG needs it for SAMD/R/L/C */
720         cmsis_dap_cmd_DAP_Disconnect();
721
722         /* When we are reconnecting, DAP_Connect needs to be rerun, at
723          * least on Keil ULINK-ME */
724         retval = cmsis_dap_cmd_DAP_Connect(seq == LINE_RESET || seq == JTAG_TO_SWD ?
725                                            CONNECT_SWD : CONNECT_JTAG);
726         if (retval != ERROR_OK)
727                 return retval;
728
729         switch (seq) {
730         case LINE_RESET:
731                 LOG_DEBUG("SWD line reset");
732                 s = swd_seq_line_reset;
733                 s_len = swd_seq_line_reset_len;
734                 break;
735         case JTAG_TO_SWD:
736                 LOG_DEBUG("JTAG-to-SWD");
737                 s = swd_seq_jtag_to_swd;
738                 s_len = swd_seq_jtag_to_swd_len;
739                 break;
740         case SWD_TO_JTAG:
741                 LOG_DEBUG("SWD-to-JTAG");
742                 s = swd_seq_swd_to_jtag;
743                 s_len = swd_seq_swd_to_jtag_len;
744                 break;
745         default:
746                 LOG_ERROR("Sequence %d not supported", seq);
747                 return ERROR_FAIL;
748         }
749
750         buffer[0] = 0;  /* report number */
751         buffer[1] = CMD_DAP_SWJ_SEQ;
752         buffer[2] = s_len;
753         bit_copy(&buffer[3], 0, s, 0, s_len);
754
755         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, DIV_ROUND_UP(s_len, 8) + 3);
756
757         if (retval != ERROR_OK || buffer[1] != DAP_OK)
758                 return ERROR_FAIL;
759
760         return ERROR_OK;
761 }
762
763 static int cmsis_dap_swd_open(void)
764 {
765         int retval;
766
767         if (cmsis_dap_handle == NULL) {
768                 /* SWD init */
769                 retval = cmsis_dap_usb_open();
770                 if (retval != ERROR_OK)
771                         return retval;
772
773                 retval = cmsis_dap_get_caps_info();
774                 if (retval != ERROR_OK)
775                         return retval;
776         }
777
778         if (!(cmsis_dap_handle->caps & INFO_CAPS_SWD)) {
779                 LOG_ERROR("CMSIS-DAP: SWD not supported");
780                 return ERROR_JTAG_DEVICE_ERROR;
781         }
782
783         retval = cmsis_dap_cmd_DAP_Connect(CONNECT_SWD);
784         if (retval != ERROR_OK)
785                 return retval;
786
787         /* Add more setup here.??... */
788
789         LOG_INFO("CMSIS-DAP: Interface Initialised (SWD)");
790         return ERROR_OK;
791 }
792
793 static int cmsis_dap_init(void)
794 {
795         int retval;
796         uint8_t *data;
797
798         if (swd_mode) {
799                 retval = cmsis_dap_swd_open();
800                 if (retval != ERROR_OK)
801                         return retval;
802         }
803
804         if (cmsis_dap_handle == NULL) {
805
806                 /* JTAG init */
807                 retval = cmsis_dap_usb_open();
808                 if (retval != ERROR_OK)
809                         return retval;
810
811                 retval = cmsis_dap_get_caps_info();
812                 if (retval != ERROR_OK)
813                         return retval;
814
815                 /* Connect in JTAG mode */
816                 if (!(cmsis_dap_handle->caps & INFO_CAPS_JTAG)) {
817                         LOG_ERROR("CMSIS-DAP: JTAG not supported");
818                         return ERROR_JTAG_DEVICE_ERROR;
819                 }
820
821                 retval = cmsis_dap_cmd_DAP_Connect(CONNECT_JTAG);
822                 if (retval != ERROR_OK)
823                         return retval;
824
825                 LOG_INFO("CMSIS-DAP: Interface Initialised (JTAG)");
826         }
827
828         retval = cmsis_dap_get_version_info();
829         if (retval != ERROR_OK)
830                 return retval;
831
832         /* INFO_ID_PKT_SZ - short */
833         retval = cmsis_dap_cmd_DAP_Info(INFO_ID_PKT_SZ, &data);
834         if (retval != ERROR_OK)
835                 return retval;
836
837         if (data[0] == 2) {  /* short */
838                 uint16_t pkt_sz = data[1] + (data[2] << 8);
839
840                 /* 4 bytes of command header + 5 bytes per register
841                  * write. For bulk read sequences just 4 bytes are
842                  * needed per transfer, so this is suboptimal. */
843                 pending_queue_len = (pkt_sz - 4) / 5;
844                 pending_transfers = malloc(pending_queue_len * sizeof(*pending_transfers));
845                 if (!pending_transfers) {
846                         LOG_ERROR("Unable to allocate memory for CMSIS-DAP queue");
847                         return ERROR_FAIL;
848                 }
849
850                 if (cmsis_dap_handle->packet_size != pkt_sz + 1) {
851                         /* reallocate buffer */
852                         cmsis_dap_handle->packet_size = pkt_sz + 1;
853                         cmsis_dap_handle->packet_buffer = realloc(cmsis_dap_handle->packet_buffer,
854                                         cmsis_dap_handle->packet_size);
855                         if (cmsis_dap_handle->packet_buffer == NULL) {
856                                 LOG_ERROR("unable to reallocate memory");
857                                 return ERROR_FAIL;
858                         }
859                 }
860
861                 LOG_DEBUG("CMSIS-DAP: Packet Size = %" PRId16, pkt_sz);
862         }
863
864         /* INFO_ID_PKT_CNT - byte */
865         retval = cmsis_dap_cmd_DAP_Info(INFO_ID_PKT_CNT, &data);
866         if (retval != ERROR_OK)
867                 return retval;
868
869         if (data[0] == 1) { /* byte */
870                 uint16_t pkt_cnt = data[1];
871                 cmsis_dap_handle->packet_count = pkt_cnt;
872                 LOG_DEBUG("CMSIS-DAP: Packet Count = %" PRId16, pkt_cnt);
873         }
874
875         retval = cmsis_dap_get_status();
876         if (retval != ERROR_OK)
877                 return ERROR_FAIL;
878
879         /* Now try to connect to the target
880          * TODO: This is all SWD only @ present */
881         retval = cmsis_dap_cmd_DAP_SWJ_Clock(jtag_get_speed_khz());
882         if (retval != ERROR_OK)
883                 return ERROR_FAIL;
884
885         /* Ask CMSIS-DAP to automatically retry on receiving WAIT for
886          * up to 64 times. This must be changed to 0 if sticky
887          * overrun detection is enabled. */
888         retval = cmsis_dap_cmd_DAP_TFER_Configure(0, 64, 0);
889         if (retval != ERROR_OK)
890                 return ERROR_FAIL;
891         /* Data Phase (bit 2) must be set to 1 if sticky overrun
892          * detection is enabled */
893         retval = cmsis_dap_cmd_DAP_SWD_Configure(0);    /* 1 TRN, no Data Phase */
894         if (retval != ERROR_OK)
895                 return ERROR_FAIL;
896
897         retval = cmsis_dap_cmd_DAP_LED(0x03);           /* Both LEDs on */
898         if (retval != ERROR_OK)
899                 return ERROR_FAIL;
900
901         /* support connecting with srst asserted */
902         enum reset_types jtag_reset_config = jtag_get_reset_config();
903
904         if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
905                 if (jtag_reset_config & RESET_SRST_NO_GATING) {
906                         retval = cmsis_dap_cmd_DAP_SWJ_Pins(0, (1 << 7), 0, NULL);
907                         if (retval != ERROR_OK)
908                                 return ERROR_FAIL;
909                         LOG_INFO("Connecting under reset");
910                 }
911         }
912
913         cmsis_dap_cmd_DAP_LED(0x00);                    /* Both LEDs off */
914
915         LOG_INFO("CMSIS-DAP: Interface ready");
916
917         return ERROR_OK;
918 }
919
920 static int cmsis_dap_swd_init(void)
921 {
922         swd_mode = true;
923         return ERROR_OK;
924 }
925
926 static int cmsis_dap_quit(void)
927 {
928         cmsis_dap_cmd_DAP_Disconnect();
929         cmsis_dap_cmd_DAP_LED(0x00);            /* Both LEDs off */
930
931         cmsis_dap_usb_close(cmsis_dap_handle);
932
933         return ERROR_OK;
934 }
935
936 static void cmsis_dap_execute_reset(struct jtag_command *cmd)
937 {
938         int retval = cmsis_dap_cmd_DAP_SWJ_Pins(cmd->cmd.reset->srst ? 0 : (1 << 7), \
939                         (1 << 7), 0, NULL);
940         if (retval != ERROR_OK)
941                 LOG_ERROR("CMSIS-DAP: Interface reset failed");
942 }
943
944 static void cmsis_dap_execute_sleep(struct jtag_command *cmd)
945 {
946 #if 0
947         int retval = cmsis_dap_cmd_DAP_Delay(cmd->cmd.sleep->us);
948         if (retval != ERROR_OK)
949 #endif
950                 jtag_sleep(cmd->cmd.sleep->us);
951 }
952
953 static void cmsis_dap_execute_command(struct jtag_command *cmd)
954 {
955         switch (cmd->type) {
956                 case JTAG_RESET:
957                         cmsis_dap_execute_reset(cmd);
958                         break;
959                 case JTAG_SLEEP:
960                         cmsis_dap_execute_sleep(cmd);
961                         break;
962                 default:
963                         LOG_ERROR("BUG: unknown JTAG command type encountered");
964                         exit(-1);
965         }
966 }
967
968 static int cmsis_dap_execute_queue(void)
969 {
970         struct jtag_command *cmd = jtag_command_queue;
971
972         while (cmd != NULL) {
973                 cmsis_dap_execute_command(cmd);
974                 cmd = cmd->next;
975         }
976
977         return ERROR_OK;
978 }
979
980 static int cmsis_dap_speed(int speed)
981 {
982         if (speed > DAP_MAX_CLOCK) {
983                 LOG_INFO("reduce speed request: %dkHz to %dkHz maximum", speed, DAP_MAX_CLOCK);
984                 speed = DAP_MAX_CLOCK;
985         }
986
987         if (speed == 0) {
988                 LOG_INFO("RTCK not supported");
989                 return ERROR_JTAG_NOT_IMPLEMENTED;
990         }
991
992         return cmsis_dap_cmd_DAP_SWJ_Clock(speed);
993 }
994
995 static int cmsis_dap_speed_div(int speed, int *khz)
996 {
997         *khz = speed;
998         return ERROR_OK;
999 }
1000
1001 static int cmsis_dap_khz(int khz, int *jtag_speed)
1002 {
1003         *jtag_speed = khz;
1004         return ERROR_OK;
1005 }
1006
1007 static int_least32_t cmsis_dap_swd_frequency(int_least32_t hz)
1008 {
1009         if (hz > 0)
1010                 cmsis_dap_speed(hz / 1000);
1011
1012         return hz;
1013 }
1014
1015 COMMAND_HANDLER(cmsis_dap_handle_info_command)
1016 {
1017         if (cmsis_dap_get_version_info() == ERROR_OK)
1018                 cmsis_dap_get_status();
1019
1020         return ERROR_OK;
1021 }
1022
1023 COMMAND_HANDLER(cmsis_dap_handle_vid_pid_command)
1024 {
1025         if (CMD_ARGC > MAX_USB_IDS * 2) {
1026                 LOG_WARNING("ignoring extra IDs in cmsis_dap_vid_pid "
1027                         "(maximum is %d pairs)", MAX_USB_IDS);
1028                 CMD_ARGC = MAX_USB_IDS * 2;
1029         }
1030         if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
1031                 LOG_WARNING("incomplete cmsis_dap_vid_pid configuration directive");
1032                 if (CMD_ARGC < 2)
1033                         return ERROR_COMMAND_SYNTAX_ERROR;
1034                 /* remove the incomplete trailing id */
1035                 CMD_ARGC -= 1;
1036         }
1037
1038         unsigned i;
1039         for (i = 0; i < CMD_ARGC; i += 2) {
1040                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], cmsis_dap_vid[i >> 1]);
1041                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], cmsis_dap_pid[i >> 1]);
1042         }
1043
1044         /*
1045          * Explicitly terminate, in case there are multiples instances of
1046          * cmsis_dap_vid_pid.
1047          */
1048         cmsis_dap_vid[i >> 1] = cmsis_dap_pid[i >> 1] = 0;
1049
1050         return ERROR_OK;
1051 }
1052
1053 COMMAND_HANDLER(cmsis_dap_handle_serial_command)
1054 {
1055         if (CMD_ARGC == 1) {
1056                 size_t len = mbstowcs(NULL, CMD_ARGV[0], 0);
1057                 cmsis_dap_serial = calloc(len + 1, sizeof(wchar_t));
1058                 if (cmsis_dap_serial == NULL) {
1059                         LOG_ERROR("unable to allocate memory");
1060                         return ERROR_OK;
1061                 }
1062                 if (mbstowcs(cmsis_dap_serial, CMD_ARGV[0], len + 1) == (size_t)-1) {
1063                         free(cmsis_dap_serial);
1064                         cmsis_dap_serial = NULL;
1065                         LOG_ERROR("unable to convert serial");
1066                 }
1067         } else {
1068                 LOG_ERROR("expected exactly one argument to cmsis_dap_serial <serial-number>");
1069         }
1070
1071         return ERROR_OK;
1072 }
1073
1074 static const struct command_registration cmsis_dap_subcommand_handlers[] = {
1075         {
1076                 .name = "info",
1077                 .handler = &cmsis_dap_handle_info_command,
1078                 .mode = COMMAND_EXEC,
1079                 .usage = "",
1080                 .help = "show cmsis-dap info",
1081         },
1082         COMMAND_REGISTRATION_DONE
1083 };
1084
1085 static const struct command_registration cmsis_dap_command_handlers[] = {
1086         {
1087                 .name = "cmsis-dap",
1088                 .mode = COMMAND_ANY,
1089                 .help = "perform CMSIS-DAP management",
1090                 .usage = "<cmd>",
1091                 .chain = cmsis_dap_subcommand_handlers,
1092         },
1093         {
1094                 .name = "cmsis_dap_vid_pid",
1095                 .handler = &cmsis_dap_handle_vid_pid_command,
1096                 .mode = COMMAND_CONFIG,
1097                 .help = "the vendor ID and product ID of the CMSIS-DAP device",
1098                 .usage = "(vid pid)* ",
1099         },
1100         {
1101                 .name = "cmsis_dap_serial",
1102                 .handler = &cmsis_dap_handle_serial_command,
1103                 .mode = COMMAND_CONFIG,
1104                 .help = "set the serial number of the adapter",
1105                 .usage = "serial_string",
1106         },
1107         COMMAND_REGISTRATION_DONE
1108 };
1109
1110 static const struct swd_driver cmsis_dap_swd_driver = {
1111         .init = cmsis_dap_swd_init,
1112         .frequency = cmsis_dap_swd_frequency,
1113         .switch_seq = cmsis_dap_swd_switch_seq,
1114         .read_reg = cmsis_dap_swd_read_reg,
1115         .write_reg = cmsis_dap_swd_write_reg,
1116         .run = cmsis_dap_swd_run_queue,
1117 };
1118
1119 static const char * const cmsis_dap_transport[] = { "swd", NULL };
1120
1121 struct jtag_interface cmsis_dap_interface = {
1122         .name = "cmsis-dap",
1123         .commands = cmsis_dap_command_handlers,
1124         .swd = &cmsis_dap_swd_driver,
1125         .transports = cmsis_dap_transport,
1126
1127         .execute_queue = cmsis_dap_execute_queue,
1128         .speed = cmsis_dap_speed,
1129         .speed_div = cmsis_dap_speed_div,
1130         .khz = cmsis_dap_khz,
1131         .init = cmsis_dap_init,
1132         .quit = cmsis_dap_quit,
1133 };