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