]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/cmsis_dap_usb.c
drivers/cmsis-dap: port to common SWD framework
[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");
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         /* When we are reconnecting, DAP_Connect needs to be rerun, at
718          * least on Keil ULINK-ME */
719         retval = cmsis_dap_cmd_DAP_Connect(seq == LINE_RESET || seq == JTAG_TO_SWD ?
720                                            CONNECT_SWD : CONNECT_JTAG);
721         if (retval != ERROR_OK)
722                 return retval;
723
724         switch (seq) {
725         case LINE_RESET:
726                 LOG_DEBUG("SWD line reset");
727                 s = swd_seq_line_reset;
728                 s_len = swd_seq_line_reset_len;
729                 break;
730         case JTAG_TO_SWD:
731                 LOG_DEBUG("JTAG-to-SWD");
732                 s = swd_seq_jtag_to_swd;
733                 s_len = swd_seq_jtag_to_swd_len;
734                 break;
735         case SWD_TO_JTAG:
736                 LOG_DEBUG("SWD-to-JTAG");
737                 s = swd_seq_swd_to_jtag;
738                 s_len = swd_seq_swd_to_jtag_len;
739                 break;
740         default:
741                 LOG_ERROR("Sequence %d not supported", seq);
742                 return ERROR_FAIL;
743         }
744
745         buffer[0] = 0;  /* report number */
746         buffer[1] = CMD_DAP_SWJ_SEQ;
747         buffer[2] = s_len;
748         bit_copy(&buffer[3], 0, s, 0, s_len);
749
750         retval = cmsis_dap_usb_xfer(cmsis_dap_handle, DIV_ROUND_UP(s_len, 8) + 3);
751
752         if (retval != ERROR_OK || buffer[1] != DAP_OK)
753                 return ERROR_FAIL;
754
755         return ERROR_OK;
756 }
757
758 static int cmsis_dap_swd_open(void)
759 {
760         int retval;
761
762         if (cmsis_dap_handle == NULL) {
763                 /* SWD init */
764                 retval = cmsis_dap_usb_open();
765                 if (retval != ERROR_OK)
766                         return retval;
767
768                 retval = cmsis_dap_get_caps_info();
769                 if (retval != ERROR_OK)
770                         return retval;
771         }
772
773         if (!(cmsis_dap_handle->caps & INFO_CAPS_SWD)) {
774                 LOG_ERROR("CMSIS-DAP: SWD not supported");
775                 return ERROR_JTAG_DEVICE_ERROR;
776         }
777
778         retval = cmsis_dap_cmd_DAP_Connect(CONNECT_SWD);
779         if (retval != ERROR_OK)
780                 return retval;
781
782         /* Add more setup here.??... */
783
784         LOG_INFO("CMSIS-DAP: Interface Initialised (SWD)");
785         return ERROR_OK;
786 }
787
788 static int cmsis_dap_init(void)
789 {
790         int retval;
791         uint8_t *data;
792
793         if (swd_mode) {
794                 retval = cmsis_dap_swd_open();
795                 if (retval != ERROR_OK)
796                         return retval;
797         }
798
799         if (cmsis_dap_handle == NULL) {
800
801                 /* JTAG init */
802                 retval = cmsis_dap_usb_open();
803                 if (retval != ERROR_OK)
804                         return retval;
805
806                 retval = cmsis_dap_get_caps_info();
807                 if (retval != ERROR_OK)
808                         return retval;
809
810                 /* Connect in JTAG mode */
811                 if (!(cmsis_dap_handle->caps & INFO_CAPS_JTAG)) {
812                         LOG_ERROR("CMSIS-DAP: JTAG not supported");
813                         return ERROR_JTAG_DEVICE_ERROR;
814                 }
815
816                 retval = cmsis_dap_cmd_DAP_Connect(CONNECT_JTAG);
817                 if (retval != ERROR_OK)
818                         return retval;
819
820                 LOG_INFO("CMSIS-DAP: Interface Initialised (JTAG)");
821         }
822
823         retval = cmsis_dap_get_version_info();
824         if (retval != ERROR_OK)
825                 return retval;
826
827         /* INFO_ID_PKT_SZ - short */
828         retval = cmsis_dap_cmd_DAP_Info(INFO_ID_PKT_SZ, &data);
829         if (retval != ERROR_OK)
830                 return retval;
831
832         if (data[0] == 2) {  /* short */
833                 uint16_t pkt_sz = data[1] + (data[2] << 8);
834
835                 /* 4 bytes of command header + 5 bytes per register
836                  * write. For bulk read sequences just 4 bytes are
837                  * needed per transfer, so this is suboptimal. */
838                 pending_queue_len = (pkt_sz - 4) / 5;
839                 pending_transfers = malloc(pending_queue_len * sizeof(*pending_transfers));
840                 if (!pending_transfers) {
841                         LOG_ERROR("Unable to allocate memory for CMSIS-DAP queue");
842                         return ERROR_FAIL;
843                 }
844
845                 if (cmsis_dap_handle->packet_size != pkt_sz + 1) {
846                         /* reallocate buffer */
847                         cmsis_dap_handle->packet_size = pkt_sz + 1;
848                         cmsis_dap_handle->packet_buffer = realloc(cmsis_dap_handle->packet_buffer,
849                                         cmsis_dap_handle->packet_size);
850                         if (cmsis_dap_handle->packet_buffer == NULL) {
851                                 LOG_ERROR("unable to reallocate memory");
852                                 return ERROR_FAIL;
853                         }
854                 }
855
856                 LOG_DEBUG("CMSIS-DAP: Packet Size = %" PRId16, pkt_sz);
857         }
858
859         /* INFO_ID_PKT_CNT - byte */
860         retval = cmsis_dap_cmd_DAP_Info(INFO_ID_PKT_CNT, &data);
861         if (retval != ERROR_OK)
862                 return retval;
863
864         if (data[0] == 1) { /* byte */
865                 uint16_t pkt_cnt = data[1];
866                 cmsis_dap_handle->packet_count = pkt_cnt;
867                 LOG_DEBUG("CMSIS-DAP: Packet Count = %" PRId16, pkt_cnt);
868         }
869
870         retval = cmsis_dap_get_status();
871         if (retval != ERROR_OK)
872                 return ERROR_FAIL;
873
874         /* Now try to connect to the target
875          * TODO: This is all SWD only @ present */
876         retval = cmsis_dap_cmd_DAP_SWJ_Clock(jtag_get_speed_khz());
877         if (retval != ERROR_OK)
878                 return ERROR_FAIL;
879
880         /* Ask CMSIS-DAP to automatically retry on receiving WAIT for
881          * up to 64 times. This must be changed to 0 if sticky
882          * overrun detection is enabled. */
883         retval = cmsis_dap_cmd_DAP_TFER_Configure(0, 64, 0);
884         if (retval != ERROR_OK)
885                 return ERROR_FAIL;
886         /* Data Phase (bit 2) must be set to 1 if sticky overrun
887          * detection is enabled */
888         retval = cmsis_dap_cmd_DAP_SWD_Configure(0);    /* 1 TRN, no Data Phase */
889         if (retval != ERROR_OK)
890                 return ERROR_FAIL;
891
892         retval = cmsis_dap_cmd_DAP_LED(0x03);           /* Both LEDs on */
893         if (retval != ERROR_OK)
894                 return ERROR_FAIL;
895
896         /* support connecting with srst asserted */
897         enum reset_types jtag_reset_config = jtag_get_reset_config();
898
899         if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
900                 if (jtag_reset_config & RESET_SRST_NO_GATING) {
901                         retval = cmsis_dap_cmd_DAP_SWJ_Pins(0, (1 << 7), 0, NULL);
902                         if (retval != ERROR_OK)
903                                 return ERROR_FAIL;
904                         LOG_INFO("Connecting under reset");
905                 }
906         }
907
908         cmsis_dap_cmd_DAP_LED(0x00);                    /* Both LEDs off */
909
910         LOG_INFO("CMSIS-DAP: Interface ready");
911
912         return ERROR_OK;
913 }
914
915 static int cmsis_dap_swd_init(void)
916 {
917         swd_mode = true;
918         return ERROR_OK;
919 }
920
921 static int cmsis_dap_quit(void)
922 {
923         cmsis_dap_cmd_DAP_Disconnect();
924         cmsis_dap_cmd_DAP_LED(0x00);            /* Both LEDs off */
925
926         cmsis_dap_usb_close(cmsis_dap_handle);
927
928         return ERROR_OK;
929 }
930
931 static void cmsis_dap_execute_reset(struct jtag_command *cmd)
932 {
933         int retval = cmsis_dap_cmd_DAP_SWJ_Pins(cmd->cmd.reset->srst ? 0 : (1 << 7), \
934                         (1 << 7), 0, NULL);
935         if (retval != ERROR_OK)
936                 LOG_ERROR("CMSIS-DAP: Interface reset failed");
937 }
938
939 static void cmsis_dap_execute_sleep(struct jtag_command *cmd)
940 {
941 #if 0
942         int retval = cmsis_dap_cmd_DAP_Delay(cmd->cmd.sleep->us);
943         if (retval != ERROR_OK)
944 #endif
945                 jtag_sleep(cmd->cmd.sleep->us);
946 }
947
948 static void cmsis_dap_execute_command(struct jtag_command *cmd)
949 {
950         switch (cmd->type) {
951                 case JTAG_RESET:
952                         cmsis_dap_execute_reset(cmd);
953                         break;
954                 case JTAG_SLEEP:
955                         cmsis_dap_execute_sleep(cmd);
956                         break;
957                 default:
958                         LOG_ERROR("BUG: unknown JTAG command type encountered");
959                         exit(-1);
960         }
961 }
962
963 static int cmsis_dap_execute_queue(void)
964 {
965         struct jtag_command *cmd = jtag_command_queue;
966
967         while (cmd != NULL) {
968                 cmsis_dap_execute_command(cmd);
969                 cmd = cmd->next;
970         }
971
972         return ERROR_OK;
973 }
974
975 static int cmsis_dap_speed(int speed)
976 {
977         if (speed > DAP_MAX_CLOCK) {
978                 LOG_INFO("reduce speed request: %dkHz to %dkHz maximum", speed, DAP_MAX_CLOCK);
979                 speed = DAP_MAX_CLOCK;
980         }
981
982         if (speed == 0) {
983                 LOG_INFO("RTCK not supported");
984                 return ERROR_JTAG_NOT_IMPLEMENTED;
985         }
986
987         return cmsis_dap_cmd_DAP_SWJ_Clock(speed);
988 }
989
990 static int cmsis_dap_speed_div(int speed, int *khz)
991 {
992         *khz = speed;
993         return ERROR_OK;
994 }
995
996 static int cmsis_dap_khz(int khz, int *jtag_speed)
997 {
998         *jtag_speed = khz;
999         return ERROR_OK;
1000 }
1001
1002 static int_least32_t cmsis_dap_swd_frequency(struct adiv5_dap *dap, int_least32_t hz)
1003 {
1004         if (hz > 0)
1005                 cmsis_dap_speed(hz / 1000);
1006
1007         return hz;
1008 }
1009
1010 COMMAND_HANDLER(cmsis_dap_handle_info_command)
1011 {
1012         if (cmsis_dap_get_version_info() == ERROR_OK)
1013                 cmsis_dap_get_status();
1014
1015         return ERROR_OK;
1016 }
1017
1018 COMMAND_HANDLER(cmsis_dap_handle_vid_pid_command)
1019 {
1020         if (CMD_ARGC > MAX_USB_IDS * 2) {
1021                 LOG_WARNING("ignoring extra IDs in cmsis_dap_vid_pid "
1022                         "(maximum is %d pairs)", MAX_USB_IDS);
1023                 CMD_ARGC = MAX_USB_IDS * 2;
1024         }
1025         if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
1026                 LOG_WARNING("incomplete cmsis_dap_vid_pid configuration directive");
1027                 if (CMD_ARGC < 2)
1028                         return ERROR_COMMAND_SYNTAX_ERROR;
1029                 /* remove the incomplete trailing id */
1030                 CMD_ARGC -= 1;
1031         }
1032
1033         unsigned i;
1034         for (i = 0; i < CMD_ARGC; i += 2) {
1035                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], cmsis_dap_vid[i >> 1]);
1036                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], cmsis_dap_pid[i >> 1]);
1037         }
1038
1039         /*
1040          * Explicitly terminate, in case there are multiples instances of
1041          * cmsis_dap_vid_pid.
1042          */
1043         cmsis_dap_vid[i >> 1] = cmsis_dap_pid[i >> 1] = 0;
1044
1045         return ERROR_OK;
1046 }
1047
1048 COMMAND_HANDLER(cmsis_dap_handle_serial_command)
1049 {
1050         if (CMD_ARGC == 1) {
1051                 size_t len = mbstowcs(NULL, CMD_ARGV[0], 0);
1052                 cmsis_dap_serial = calloc(len + 1, sizeof(wchar_t));
1053                 if (cmsis_dap_serial == NULL) {
1054                         LOG_ERROR("unable to allocate memory");
1055                         return ERROR_OK;
1056                 }
1057                 if (mbstowcs(cmsis_dap_serial, CMD_ARGV[0], len + 1) == (size_t)-1) {
1058                         free(cmsis_dap_serial);
1059                         cmsis_dap_serial = NULL;
1060                         LOG_ERROR("unable to convert serial");
1061                 }
1062         } else {
1063                 LOG_ERROR("expected exactly one argument to cmsis_dap_serial <serial-number>");
1064         }
1065
1066         return ERROR_OK;
1067 }
1068
1069 static const struct command_registration cmsis_dap_subcommand_handlers[] = {
1070         {
1071                 .name = "info",
1072                 .handler = &cmsis_dap_handle_info_command,
1073                 .mode = COMMAND_EXEC,
1074                 .usage = "",
1075                 .help = "show cmsis-dap info",
1076         },
1077         COMMAND_REGISTRATION_DONE
1078 };
1079
1080 static const struct command_registration cmsis_dap_command_handlers[] = {
1081         {
1082                 .name = "cmsis-dap",
1083                 .mode = COMMAND_ANY,
1084                 .help = "perform CMSIS-DAP management",
1085                 .usage = "<cmd>",
1086                 .chain = cmsis_dap_subcommand_handlers,
1087         },
1088         {
1089                 .name = "cmsis_dap_vid_pid",
1090                 .handler = &cmsis_dap_handle_vid_pid_command,
1091                 .mode = COMMAND_CONFIG,
1092                 .help = "the vendor ID and product ID of the CMSIS-DAP device",
1093                 .usage = "(vid pid)* ",
1094         },
1095         {
1096                 .name = "cmsis_dap_serial",
1097                 .handler = &cmsis_dap_handle_serial_command,
1098                 .mode = COMMAND_CONFIG,
1099                 .help = "set the serial number of the adapter",
1100                 .usage = "serial_string",
1101         },
1102         COMMAND_REGISTRATION_DONE
1103 };
1104
1105 static const struct swd_driver cmsis_dap_swd_driver = {
1106         .init = cmsis_dap_swd_init,
1107         .frequency = cmsis_dap_swd_frequency,
1108         .switch_seq = cmsis_dap_swd_switch_seq,
1109         .read_reg = cmsis_dap_swd_read_reg,
1110         .write_reg = cmsis_dap_swd_write_reg,
1111         .run = cmsis_dap_swd_run_queue,
1112 };
1113
1114 static const char * const cmsis_dap_transport[] = { "swd", NULL };
1115
1116 struct jtag_interface cmsis_dap_interface = {
1117         .name = "cmsis-dap",
1118         .commands = cmsis_dap_command_handlers,
1119         .swd = &cmsis_dap_swd_driver,
1120         .transports = cmsis_dap_transport,
1121
1122         .execute_queue = cmsis_dap_execute_queue,
1123         .speed = cmsis_dap_speed,
1124         .speed_div = cmsis_dap_speed_div,
1125         .khz = cmsis_dap_khz,
1126         .init = cmsis_dap_init,
1127         .quit = cmsis_dap_quit,
1128 };