7791840e77328cf00ec263aece14a9e079868161
[openocd.git] / src / jtag / drivers / cmsis_dap_usb.c
1 /***************************************************************************
2 * Copyright (C) 2016 by Maksym Hilliaka *
3 * oter@frozen-team.com *
4 * *
5 * Copyright (C) 2016 by Phillip Pearson *
6 * pp@myelin.co.nz *
7 * *
8 * Copyright (C) 2014 by Paul Fertser *
9 * fercerpav@gmail.com *
10 * *
11 * Copyright (C) 2013 by mike brown *
12 * mike@theshedworks.org.uk *
13 * *
14 * Copyright (C) 2013 by Spencer Oliver *
15 * spen@spen-soft.co.uk *
16 * *
17 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
21 * *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
26 * *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
29 ***************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #include <transport/transport.h>
36 #include <jtag/swd.h>
37 #include <jtag/interface.h>
38 #include <jtag/commands.h>
39 #include <jtag/tcl.h>
40
41 #include <hidapi.h>
42
43 /*
44 * See CMSIS-DAP documentation:
45 * Version 0.01 - Beta.
46 */
47
48 /* USB Config */
49
50 /* Known vid/pid pairs:
51 * VID 0xc251: Keil Software
52 * PID 0xf001: LPC-Link-II CMSIS_DAP
53 * PID 0xf002: OPEN-SDA CMSIS_DAP (Freedom Board)
54 * PID 0x2722: Keil ULINK2 CMSIS-DAP
55 *
56 * VID 0x0d28: mbed Software
57 * PID 0x0204: MBED CMSIS-DAP
58 */
59
60 #define MAX_USB_IDS 8
61 /* vid = pid = 0 marks the end of the list */
62 static uint16_t cmsis_dap_vid[MAX_USB_IDS + 1] = { 0 };
63 static uint16_t cmsis_dap_pid[MAX_USB_IDS + 1] = { 0 };
64 static wchar_t *cmsis_dap_serial;
65 static bool swd_mode;
66
67 #define PACKET_SIZE (64 + 1) /* 64 bytes plus report id */
68 #define USB_TIMEOUT 1000
69
70 /* CMSIS-DAP General Commands */
71 #define CMD_DAP_INFO 0x00
72 #define CMD_DAP_LED 0x01
73 #define CMD_DAP_CONNECT 0x02
74 #define CMD_DAP_DISCONNECT 0x03
75 #define CMD_DAP_WRITE_ABORT 0x08
76 #define CMD_DAP_DELAY 0x09
77 #define CMD_DAP_RESET_TARGET 0x0A
78
79 /* CMD_INFO */
80 #define INFO_ID_VID 0x00 /* string */
81 #define INFO_ID_PID 0x02 /* string */
82 #define INFO_ID_SERNUM 0x03 /* string */
83 #define INFO_ID_FW_VER 0x04 /* string */
84 #define INFO_ID_TD_VEND 0x05 /* string */
85 #define INFO_ID_TD_NAME 0x06 /* string */
86 #define INFO_ID_CAPS 0xf0 /* byte */
87 #define INFO_ID_PKT_CNT 0xfe /* byte */
88 #define INFO_ID_PKT_SZ 0xff /* short */
89
90 #define INFO_CAPS_SWD 0x01
91 #define INFO_CAPS_JTAG 0x02
92
93 /* CMD_LED */
94 #define LED_ID_CONNECT 0x00
95 #define LED_ID_RUN 0x01
96
97 #define LED_OFF 0x00
98 #define LED_ON 0x01
99
100 /* CMD_CONNECT */
101 #define CONNECT_DEFAULT 0x00
102 #define CONNECT_SWD 0x01
103 #define CONNECT_JTAG 0x02
104
105 /* CMSIS-DAP Common SWD/JTAG Commands */
106 #define CMD_DAP_DELAY 0x09
107 #define CMD_DAP_SWJ_PINS 0x10
108 #define CMD_DAP_SWJ_CLOCK 0x11
109 #define CMD_DAP_SWJ_SEQ 0x12
110
111 /*
112 * PINS
113 * Bit 0: SWCLK/TCK
114 * Bit 1: SWDIO/TMS
115 * Bit 2: TDI
116 * Bit 3: TDO
117 * Bit 5: nTRST
118 * Bit 7: nRESET
119 */
120
121 #define SWJ_PIN_TCK (1<<0)
122 #define SWJ_PIN_TMS (1<<1)
123 #define SWJ_PIN_TDI (1<<2)
124 #define SWJ_PIN_TDO (1<<3)
125 #define SWJ_PIN_TRST (1<<5)
126 #define SWJ_PIN_SRST (1<<7)
127
128 /* CMSIS-DAP SWD Commands */
129 #define CMD_DAP_SWD_CONFIGURE 0x13
130
131 /* CMSIS-DAP JTAG Commands */
132 #define CMD_DAP_JTAG_SEQ 0x14
133 #define CMD_DAP_JTAG_CONFIGURE 0x15
134 #define CMD_DAP_JTAG_IDCODE 0x16
135
136 /* CMSIS-DAP JTAG sequence info masks */
137 /* Number of bits to clock through (0 means 64) */
138 #define DAP_JTAG_SEQ_TCK 0x3F
139 /* TMS will be set during the sequence if this bit is set */
140 #define DAP_JTAG_SEQ_TMS 0x40
141 /* TDO output will be captured if this bit is set */
142 #define DAP_JTAG_SEQ_TDO 0x80
143
144
145 /* CMSIS-DAP Transfer Commands */
146 #define CMD_DAP_TFER_CONFIGURE 0x04
147 #define CMD_DAP_TFER 0x05
148 #define CMD_DAP_TFER_BLOCK 0x06
149 #define CMD_DAP_TFER_ABORT 0x07
150
151 /* DAP Status Code */
152 #define DAP_OK 0
153 #define DAP_ERROR 0xFF
154
155 /* CMSIS-DAP Vendor Commands
156 * None as yet... */
157
158 static const char * const info_caps_str[] = {
159 "SWD Supported",
160 "JTAG Supported"
161 };
162
163 /* max clock speed (kHz) */
164 #define DAP_MAX_CLOCK 5000
165
166 struct cmsis_dap {
167 hid_device *dev_handle;
168 uint16_t packet_size;
169 uint16_t packet_count;
170 uint8_t *packet_buffer;
171 uint8_t caps;
172 uint8_t mode;
173 };
174
175 struct pending_transfer_result {
176 uint8_t cmd;
177 uint32_t data;
178 void *buffer;
179 };
180
181 struct pending_scan_result {
182 /** Offset in bytes in the CMD_DAP_JTAG_SEQ response buffer. */
183 unsigned first;
184 /** Number of bits to read. */
185 unsigned length;
186 /** Location to store the result */
187 uint8_t *buffer;
188 /** Offset in the destination buffer */
189 unsigned buffer_offset;
190 };
191
192 static int pending_transfer_count, pending_queue_len;
193 static struct pending_transfer_result *pending_transfers;
194
195 /* pointers to buffers that will receive jtag scan results on the next flush */
196 #define MAX_PENDING_SCAN_RESULTS 256
197 static int pending_scan_result_count;
198 static struct pending_scan_result pending_scan_results[MAX_PENDING_SCAN_RESULTS];
199
200 /* queued JTAG sequences that will be executed on the next flush */
201 #define QUEUED_SEQ_BUF_LEN (cmsis_dap_handle->packet_size - 3)
202 static int queued_seq_count;
203 static int queued_seq_buf_end;
204 static int queued_seq_tdo_ptr;
205 static uint8_t queued_seq_buf[1024]; /* TODO: make dynamic / move into cmsis object */
206
207 static int queued_retval;
208
209 static struct cmsis_dap *cmsis_dap_handle;
210
211 static int cmsis_dap_usb_open(void)
212 {
213 hid_device *dev = NULL;
214 int i;
215 struct hid_device_info *devs, *cur_dev;
216 unsigned short target_vid, target_pid;
217 wchar_t *target_serial = NULL;
218
219 bool found = false;
220 bool serial_found = false;
221
222 target_vid = 0;
223 target_pid = 0;
224
225 /*
226 * The CMSIS-DAP specification stipulates:
227 * "The Product String must contain "CMSIS-DAP" somewhere in the string. This is used by the
228 * debuggers to identify a CMSIS-DAP compliant Debug Unit that is connected to a host computer."
229 */
230 devs = hid_enumerate(0x0, 0x0);
231 cur_dev = devs;
232 while (NULL != cur_dev) {
233 if (0 == cmsis_dap_vid[0]) {
234 if (NULL == cur_dev->product_string) {
235 LOG_DEBUG("Cannot read product string of device 0x%x:0x%x",
236 cur_dev->vendor_id, cur_dev->product_id);
237 } else {
238 if (wcsstr(cur_dev->product_string, L"CMSIS-DAP")) {
239 /* if the user hasn't specified VID:PID *and*
240 * product string contains "CMSIS-DAP", pick it
241 */
242 found = true;
243 }
244 }
245 } else {
246 /* otherwise, exhaustively compare against all VID:PID in list */
247 for (i = 0; cmsis_dap_vid[i] || cmsis_dap_pid[i]; i++) {
248 if ((cmsis_dap_vid[i] == cur_dev->vendor_id) && (cmsis_dap_pid[i] == cur_dev->product_id))
249 found = true;
250 }
251
252 if (cmsis_dap_vid[i] || cmsis_dap_pid[i])
253 found = true;
254 }
255
256 if (found) {
257 /* we have found an adapter, so exit further checks */
258 /* check serial number matches if given */
259 if (cmsis_dap_serial != NULL) {
260 if ((cur_dev->serial_number != NULL) && wcscmp(cmsis_dap_serial, cur_dev->serial_number) == 0) {
261 serial_found = true;
262 break;
263 }
264 } else
265 break;
266
267 found = false;
268 }
269
270 cur_dev = cur_dev->next;
271 }
272
273 if (NULL != cur_dev) {
274 target_vid = cur_dev->vendor_id;
275 target_pid = cur_dev->product_id;
276 if (serial_found)
277 target_serial = cmsis_dap_serial;
278 }
279
280 hid_free_enumeration(devs);
281
282 if (target_vid == 0 && target_pid == 0) {
283 LOG_ERROR("unable to find CMSIS-DAP device");
284 return ERROR_FAIL;
285 }
286
287 if (hid_init() != 0) {
288 LOG_ERROR("unable to open HIDAPI");
289 return ERROR_FAIL;
290 }
291
292 dev = hid_open(target_vid, target_pid, target_serial);
293
294 if (dev == NULL) {
295 LOG_ERROR("unable to open CMSIS-DAP device 0x%x:0x%x", target_vid, target_pid);
296 return ERROR_FAIL;
297 }
298
299 struct cmsis_dap *dap = malloc(sizeof(struct cmsis_dap));
300 if (dap == NULL) {
301 LOG_ERROR("unable to allocate memory");
302 return ERROR_FAIL;
303 }
304
305 dap->dev_handle = dev;
306 dap->caps = 0;
307 dap->mode = 0;
308
309 cmsis_dap_handle = dap;
310
311 /* allocate default packet buffer, may be changed later.
312 * currently with HIDAPI we have no way of getting the output report length
313 * without this info we cannot communicate with the adapter.
314 * For the moment we ahve to hard code the packet size */
315
316 int packet_size = PACKET_SIZE;
317
318 /* atmel cmsis-dap uses 512 byte reports */
319 /* TODO: HID report descriptor should be parsed instead of
320 * hardcoding a match by VID */
321 if (target_vid == 0x03eb)
322 packet_size = 512 + 1;
323
324 cmsis_dap_handle->packet_buffer = malloc(packet_size);
325 cmsis_dap_handle->packet_size = packet_size;
326
327 if (cmsis_dap_handle->packet_buffer == NULL) {
328 LOG_ERROR("unable to allocate memory");
329 return ERROR_FAIL;
330 }
331
332 return ERROR_OK;
333 }
334
335 static void cmsis_dap_usb_close(struct cmsis_dap *dap)
336 {
337 hid_close(dap->dev_handle);
338 hid_exit();
339
340 free(cmsis_dap_handle->packet_buffer);
341 free(cmsis_dap_handle);
342 cmsis_dap_handle = NULL;
343 free(cmsis_dap_serial);
344 cmsis_dap_serial = NULL;
345 free(pending_transfers);
346 pending_transfers = NULL;
347
348 return;
349 }
350
351 /* Send a message and receive the reply */
352 static int cmsis_dap_usb_xfer(struct cmsis_dap *dap, int txlen)
353 {
354 #ifdef CMSIS_DAP_JTAG_DEBUG
355 LOG_DEBUG("cmsis-dap usb xfer cmd=%02X", dap->packet_buffer[1]);
356 #endif
357 /* Pad the rest of the TX buffer with 0's */
358 memset(dap->packet_buffer + txlen, 0, dap->packet_size - txlen);
359
360 /* write data to device */
361 int retval = hid_write(dap->dev_handle, dap->packet_buffer, dap->packet_size);
362 if (retval == -1) {
363 LOG_ERROR("error writing data: %ls", hid_error(dap->dev_handle));
364 return ERROR_FAIL;
365 }
366
367 /* get reply */
368 retval = hid_read_timeout(dap->dev_handle, dap->packet_buffer, dap->packet_size, USB_TIMEOUT);
369 if (retval == -1 || retval == 0) {
370 LOG_DEBUG("error reading data: %ls", hid_error(dap->dev_handle));
371 return ERROR_FAIL;
372 }
373
374 return ERROR_OK;
375 }
376
377 static int cmsis_dap_cmd_DAP_SWJ_Pins(uint8_t pins, uint8_t mask, uint32_t delay, uint8_t *input)
378 {
379 int retval;
380 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
381
382 buffer[0] = 0; /* report number */
383 buffer[1] = CMD_DAP_SWJ_PINS;
384 buffer[2] = pins;
385 buffer[3] = mask;
386 buffer[4] = delay & 0xff;
387 buffer[5] = (delay >> 8) & 0xff;
388 buffer[6] = (delay >> 16) & 0xff;
389 buffer[7] = (delay >> 24) & 0xff;
390 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 8);
391
392 if (retval != ERROR_OK) {
393 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_PINS failed.");
394 return ERROR_JTAG_DEVICE_ERROR;
395 }
396
397 if (input)
398 *input = buffer[1];
399
400 return ERROR_OK;
401 }
402
403 static int cmsis_dap_cmd_DAP_SWJ_Clock(uint32_t swj_clock)
404 {
405 int retval;
406 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
407
408 /* set clock in Hz */
409 swj_clock *= 1000;
410 buffer[0] = 0; /* report number */
411 buffer[1] = CMD_DAP_SWJ_CLOCK;
412 buffer[2] = swj_clock & 0xff;
413 buffer[3] = (swj_clock >> 8) & 0xff;
414 buffer[4] = (swj_clock >> 16) & 0xff;
415 buffer[5] = (swj_clock >> 24) & 0xff;
416 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 6);
417
418 if (retval != ERROR_OK || buffer[1] != DAP_OK) {
419 LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_CLOCK failed.");
420 return ERROR_JTAG_DEVICE_ERROR;
421 }
422
423 return ERROR_OK;
424 }
425
426 /* clock a sequence of bits out on TMS, to change JTAG states */
427 static int cmsis_dap_cmd_DAP_SWJ_Sequence(uint8_t s_len, const uint8_t *sequence)
428 {
429 int retval;
430 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
431
432 #ifdef CMSIS_DAP_JTAG_DEBUG
433 LOG_DEBUG("cmsis-dap TMS sequence: len=%d", s_len);
434 for (int i = 0; i < DIV_ROUND_UP(s_len, 8); ++i)
435 printf("%02X ", sequence[i]);
436
437 printf("\n");
438 #endif
439
440 buffer[0] = 0; /* report number */
441 buffer[1] = CMD_DAP_SWJ_SEQ;
442 buffer[2] = s_len;
443 bit_copy(&buffer[3], 0, sequence, 0, s_len);
444
445 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, DIV_ROUND_UP(s_len, 8) + 3);
446
447 if (retval != ERROR_OK || buffer[1] != DAP_OK)
448 return ERROR_FAIL;
449
450 return ERROR_OK;
451 }
452
453 static int cmsis_dap_cmd_DAP_Info(uint8_t info, uint8_t **data)
454 {
455 int retval;
456 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
457
458 buffer[0] = 0; /* report number */
459 buffer[1] = CMD_DAP_INFO;
460 buffer[2] = info;
461 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 3);
462
463 if (retval != ERROR_OK) {
464 LOG_ERROR("CMSIS-DAP command CMD_INFO failed.");
465 return ERROR_JTAG_DEVICE_ERROR;
466 }
467
468 *data = &(buffer[1]);
469
470 return ERROR_OK;
471 }
472
473 static int cmsis_dap_cmd_DAP_LED(uint8_t leds)
474 {
475 int retval;
476 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
477
478 buffer[0] = 0; /* report number */
479 buffer[1] = CMD_DAP_LED;
480 buffer[2] = 0x00;
481 buffer[3] = leds;
482 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 4);
483
484 if (retval != ERROR_OK || buffer[1] != 0x00) {
485 LOG_ERROR("CMSIS-DAP command CMD_LED failed.");
486 return ERROR_JTAG_DEVICE_ERROR;
487 }
488
489 return ERROR_OK;
490 }
491
492 static int cmsis_dap_cmd_DAP_Connect(uint8_t mode)
493 {
494 int retval;
495 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
496
497 buffer[0] = 0; /* report number */
498 buffer[1] = CMD_DAP_CONNECT;
499 buffer[2] = mode;
500 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 3);
501
502 if (retval != ERROR_OK) {
503 LOG_ERROR("CMSIS-DAP command CMD_CONNECT failed.");
504 return ERROR_JTAG_DEVICE_ERROR;
505 }
506
507 if (buffer[1] != mode) {
508 LOG_ERROR("CMSIS-DAP failed to connect in mode (%d)", mode);
509 return ERROR_JTAG_DEVICE_ERROR;
510 }
511
512 return ERROR_OK;
513 }
514
515 static int cmsis_dap_cmd_DAP_Disconnect(void)
516 {
517 int retval;
518 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
519
520 buffer[0] = 0; /* report number */
521 buffer[1] = CMD_DAP_DISCONNECT;
522 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 2);
523
524 if (retval != ERROR_OK || buffer[1] != DAP_OK) {
525 LOG_ERROR("CMSIS-DAP command CMD_DISCONNECT failed.");
526 return ERROR_JTAG_DEVICE_ERROR;
527 }
528
529 return ERROR_OK;
530 }
531
532 static int cmsis_dap_cmd_DAP_TFER_Configure(uint8_t idle, uint16_t retry_count, uint16_t match_retry)
533 {
534 int retval;
535 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
536
537 buffer[0] = 0; /* report number */
538 buffer[1] = CMD_DAP_TFER_CONFIGURE;
539 buffer[2] = idle;
540 buffer[3] = retry_count & 0xff;
541 buffer[4] = (retry_count >> 8) & 0xff;
542 buffer[5] = match_retry & 0xff;
543 buffer[6] = (match_retry >> 8) & 0xff;
544 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 7);
545
546 if (retval != ERROR_OK || buffer[1] != DAP_OK) {
547 LOG_ERROR("CMSIS-DAP command CMD_TFER_Configure failed.");
548 return ERROR_JTAG_DEVICE_ERROR;
549 }
550
551 return ERROR_OK;
552 }
553
554 static int cmsis_dap_cmd_DAP_SWD_Configure(uint8_t cfg)
555 {
556 int retval;
557 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
558
559 buffer[0] = 0; /* report number */
560 buffer[1] = CMD_DAP_SWD_CONFIGURE;
561 buffer[2] = cfg;
562 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 3);
563
564 if (retval != ERROR_OK || buffer[1] != DAP_OK) {
565 LOG_ERROR("CMSIS-DAP command CMD_SWD_Configure failed.");
566 return ERROR_JTAG_DEVICE_ERROR;
567 }
568
569 return ERROR_OK;
570 }
571
572 #if 0
573 static int cmsis_dap_cmd_DAP_Delay(uint16_t delay_us)
574 {
575 int retval;
576 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
577
578 buffer[0] = 0; /* report number */
579 buffer[1] = CMD_DAP_DELAY;
580 buffer[2] = delay_us & 0xff;
581 buffer[3] = (delay_us >> 8) & 0xff;
582 retval = cmsis_dap_usb_xfer(cmsis_dap_handle, 4);
583
584 if (retval != ERROR_OK || buffer[1] != DAP_OK) {
585 LOG_ERROR("CMSIS-DAP command CMD_Delay failed.");
586 return ERROR_JTAG_DEVICE_ERROR;
587 }
588
589 return ERROR_OK;
590 }
591 #endif
592
593 static int cmsis_dap_swd_run_queue(void)
594 {
595 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
596
597 LOG_DEBUG("Executing %d queued transactions", pending_transfer_count);
598
599 if (queued_retval != ERROR_OK) {
600 LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
601 goto skip;
602 }
603
604 if (!pending_transfer_count)
605 goto skip;
606
607 size_t idx = 0;
608 buffer[idx++] = 0; /* report number */
609 buffer[idx++] = CMD_DAP_TFER;
610 buffer[idx++] = 0x00; /* DAP Index */
611 buffer[idx++] = pending_transfer_count;
612
613 for (int i = 0; i < pending_transfer_count; i++) {
614 uint8_t cmd = pending_transfers[i].cmd;
615 uint32_t data = pending_transfers[i].data;
616
617 LOG_DEBUG("%s %s reg %x %"PRIx32,
618 cmd & SWD_CMD_APnDP ? "AP" : "DP",
619 cmd & SWD_CMD_RnW ? "read" : "write",
620 (cmd & SWD_CMD_A32) >> 1, data);
621
622 /* When proper WAIT handling is implemented in the
623 * common SWD framework, this kludge can be
624 * removed. However, this might lead to minor
625 * performance degradation as the adapter wouldn't be
626 * able to automatically retry anything (because ARM
627 * has forgotten to implement sticky error flags
628 * clearing). See also comments regarding
629 * cmsis_dap_cmd_DAP_TFER_Configure() and
630 * cmsis_dap_cmd_DAP_SWD_Configure() in
631 * cmsis_dap_init().
632 */
633 if (!(cmd & SWD_CMD_RnW) &&
634 !(cmd & SWD_CMD_APnDP) &&
635 (cmd & SWD_CMD_A32) >> 1 == DP_CTRL_STAT &&
636 (data & CORUNDETECT)) {
637 LOG_DEBUG("refusing to enable sticky overrun detection");
638 data &= ~CORUNDETECT;
639 }
640
641 buffer[idx++] = (cmd >> 1) & 0x0f;
642 if (!(cmd & SWD_CMD_RnW)) {
643 buffer[idx++] = (data) & 0xff;
644 buffer[idx++] = (data >> 8) & 0xff;
645 buffer[idx++] = (data >> 16) & 0xff;
646 buffer[idx++] = (data >> 24) & 0xff;
647 }
648 }
649
650 queued_retval = cmsis_dap_usb_xfer(cmsis_dap_handle, idx);
651 if (queued_retval != ERROR_OK)
652 goto skip;
653
654 idx = 2;
655 uint8_t ack = buffer[idx] & 0x07;
656 if (ack != SWD_ACK_OK || (buffer[idx] & 0x08)) {
657 LOG_DEBUG("SWD ack not OK: %d %s", buffer[idx-1],
658 ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
659 queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
660 goto skip;
661 }
662 idx++;
663
664 if (pending_transfer_count != buffer[1])
665 LOG_ERROR("CMSIS-DAP transfer count mismatch: expected %d, got %d",
666 pending_transfer_count, buffer[1]);
667
668 for (int i = 0; i < buffer[1]; i++) {
669 if (pending_transfers[i].cmd & SWD_CMD_RnW) {
670 static uint32_t last_read;
671 uint32_t data = le_to_h_u32(&buffer[idx]);
672 uint32_t tmp = data;
673 idx += 4;
674
675 LOG_DEBUG("Read result: %"PRIx32, data);
676
677 /* Imitate posted AP reads */
678 if ((pending_transfers[i].cmd & SWD_CMD_APnDP) ||
679 ((pending_transfers[i].cmd & SWD_CMD_A32) >> 1 == DP_RDBUFF)) {
680 tmp = last_read;
681 last_read = data;
682 }
683
684 if (pending_transfers[i].buffer)
685 *(uint32_t *)pending_transfers[i].buffer = tmp;
686 }
687 }
688
689 skip:
690 pending_transfer_count = 0;
691 int retval = queued_retval;
692 queued_retval = ERROR_OK;
693
694 return retval;
695 }
696
697 static void cmsis_dap_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data)
698 {
699 if (pending_transfer_count == pending_queue_len) {
700 /* Not enough room in the queue. Run the queue. */
701 queued_retval = cmsis_dap_swd_run_queue();
702 }
703
704 if (queued_retval != ERROR_OK)
705 return;
706
707 pending_transfers[pending_transfer_count].data = data;
708 pending_transfers[pending_transfer_count].cmd = cmd;
709 if (cmd & SWD_CMD_RnW) {
710 /* Queue a read transaction */
711 pending_transfers[pending_transfer_count].buffer = dst;
712 }
713 pending_transfer_count++;
714 }
715
716 static void cmsis_dap_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
717 {
718 assert(!(cmd & SWD_CMD_RnW));
719 cmsis_dap_swd_queue_cmd(cmd, NULL, value);
720 }
721
722 static void cmsis_dap_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
723 {
724 assert(cmd & SWD_CMD_RnW);
725 cmsis_dap_swd_queue_cmd(cmd, value, 0);
726 }
727
728 static int cmsis_dap_get_version_info(void)
729 {
730 uint8_t *data;
731
732 /* INFO_ID_FW_VER - string */
733 int retval = cmsis_dap_cmd_DAP_Info(INFO_ID_FW_VER, &data);
734 if (retval != ERROR_OK)
735 return retval;
736
737 if (data[0]) /* strlen */
738 LOG_INFO("CMSIS-DAP: FW Version = %s", &data[1]);
739
740 return ERROR_OK;
741 }
742
743 static int cmsis_dap_get_caps_info(void)
744 {
745 uint8_t *data;
746
747 /* INFO_ID_CAPS - byte */
748 int retval = cmsis_dap_cmd_DAP_Info(INFO_ID_CAPS, &data);
749 if (retval != ERROR_OK)
750 return retval;
751
752 if (data[0] == 1) {
753 uint8_t caps = data[1];
754
755 cmsis_dap_handle->caps = caps;
756
757 if (caps & INFO_CAPS_SWD)
758 LOG_INFO("CMSIS-DAP: %s", info_caps_str[0]);
759 if (caps & INFO_CAPS_JTAG)
760 LOG_INFO("CMSIS-DAP: %s", info_caps_str[1]);
761 }
762
763 return ERROR_OK;
764 }
765
766 static int cmsis_dap_get_status(void)
767 {
768 uint8_t d;
769
770 int retval = cmsis_dap_cmd_DAP_SWJ_Pins(0, 0, 0, &d);
771
772 if (retval == ERROR_OK) {
773 LOG_INFO("SWCLK/TCK = %d SWDIO/TMS = %d TDI = %d TDO = %d nTRST = %d nRESET = %d",
774 (d & SWJ_PIN_TCK) ? 1 : 0,
775 (d & SWJ_PIN_TMS) ? 1 : 0,
776 (d & SWJ_PIN_TDI) ? 1 : 0,
777 (d & SWJ_PIN_TDO) ? 1 : 0,
778 (d & SWJ_PIN_TRST) ? 1 : 0,
779 (d & SWJ_PIN_SRST) ? 1 : 0);
780 }
781
782 return retval;
783 }
784
785 static int cmsis_dap_swd_switch_seq(enum swd_special_seq seq)
786 {
787 const uint8_t *s;
788 unsigned int s_len;
789 int retval;
790
791 /* First disconnect before connecting, Atmel EDBG needs it for SAMD/R/L/C */
792 cmsis_dap_cmd_DAP_Disconnect();
793
794 /* When we are reconnecting, DAP_Connect needs to be rerun, at
795 * least on Keil ULINK-ME */
796 retval = cmsis_dap_cmd_DAP_Connect(seq == LINE_RESET || seq == JTAG_TO_SWD ?
797 CONNECT_SWD : CONNECT_JTAG);
798 if (retval != ERROR_OK)
799 return retval;
800
801 switch (seq) {
802 case LINE_RESET:
803 LOG_DEBUG("SWD line reset");
804 s = swd_seq_line_reset;
805 s_len = swd_seq_line_reset_len;
806 break;
807 case JTAG_TO_SWD:
808 LOG_DEBUG("JTAG-to-SWD");
809 s = swd_seq_jtag_to_swd;
810 s_len = swd_seq_jtag_to_swd_len;
811 break;
812 case SWD_TO_JTAG:
813 LOG_DEBUG("SWD-to-JTAG");
814 s = swd_seq_swd_to_jtag;
815 s_len = swd_seq_swd_to_jtag_len;
816 break;
817 default:
818 LOG_ERROR("Sequence %d not supported", seq);
819 return ERROR_FAIL;
820 }
821
822 return cmsis_dap_cmd_DAP_SWJ_Sequence(s_len, s);
823 }
824
825 static int cmsis_dap_swd_open(void)
826 {
827 int retval;
828
829 if (cmsis_dap_handle == NULL) {
830 /* SWD init */
831 retval = cmsis_dap_usb_open();
832 if (retval != ERROR_OK)
833 return retval;
834
835 retval = cmsis_dap_get_caps_info();
836 if (retval != ERROR_OK)
837 return retval;
838 }
839
840 if (!(cmsis_dap_handle->caps & INFO_CAPS_SWD)) {
841 LOG_ERROR("CMSIS-DAP: SWD not supported");
842 return ERROR_JTAG_DEVICE_ERROR;
843 }
844
845 retval = cmsis_dap_cmd_DAP_Connect(CONNECT_SWD);
846 if (retval != ERROR_OK)
847 return retval;
848
849 /* Add more setup here.??... */
850
851 LOG_INFO("CMSIS-DAP: Interface Initialised (SWD)");
852 return ERROR_OK;
853 }
854
855 static int cmsis_dap_init(void)
856 {
857 int retval;
858 uint8_t *data;
859
860 if (swd_mode) {
861 retval = cmsis_dap_swd_open();
862 if (retval != ERROR_OK)
863 return retval;
864 }
865
866 if (cmsis_dap_handle == NULL) {
867
868 /* JTAG init */
869 retval = cmsis_dap_usb_open();
870 if (retval != ERROR_OK)
871 return retval;
872
873 retval = cmsis_dap_get_caps_info();
874 if (retval != ERROR_OK)
875 return retval;
876
877 /* Connect in JTAG mode */
878 if (!(cmsis_dap_handle->caps & INFO_CAPS_JTAG)) {
879 LOG_ERROR("CMSIS-DAP: JTAG not supported");
880 return ERROR_JTAG_DEVICE_ERROR;
881 }
882
883 retval = cmsis_dap_cmd_DAP_Connect(CONNECT_JTAG);
884 if (retval != ERROR_OK)
885 return retval;
886
887 LOG_INFO("CMSIS-DAP: Interface Initialised (JTAG)");
888 }
889
890 retval = cmsis_dap_get_version_info();
891 if (retval != ERROR_OK)
892 return retval;
893
894 /* INFO_ID_PKT_SZ - short */
895 retval = cmsis_dap_cmd_DAP_Info(INFO_ID_PKT_SZ, &data);
896 if (retval != ERROR_OK)
897 return retval;
898
899 if (data[0] == 2) { /* short */
900 uint16_t pkt_sz = data[1] + (data[2] << 8);
901
902 /* 4 bytes of command header + 5 bytes per register
903 * write. For bulk read sequences just 4 bytes are
904 * needed per transfer, so this is suboptimal. */
905 pending_queue_len = (pkt_sz - 4) / 5;
906 pending_transfers = malloc(pending_queue_len * sizeof(*pending_transfers));
907 if (!pending_transfers) {
908 LOG_ERROR("Unable to allocate memory for CMSIS-DAP queue");
909 return ERROR_FAIL;
910 }
911
912 if (cmsis_dap_handle->packet_size != pkt_sz + 1) {
913 /* reallocate buffer */
914 cmsis_dap_handle->packet_size = pkt_sz + 1;
915 cmsis_dap_handle->packet_buffer = realloc(cmsis_dap_handle->packet_buffer,
916 cmsis_dap_handle->packet_size);
917 if (cmsis_dap_handle->packet_buffer == NULL) {
918 LOG_ERROR("unable to reallocate memory");
919 return ERROR_FAIL;
920 }
921 }
922
923 LOG_DEBUG("CMSIS-DAP: Packet Size = %" PRId16, pkt_sz);
924 }
925
926 /* INFO_ID_PKT_CNT - byte */
927 retval = cmsis_dap_cmd_DAP_Info(INFO_ID_PKT_CNT, &data);
928 if (retval != ERROR_OK)
929 return retval;
930
931 if (data[0] == 1) { /* byte */
932 uint16_t pkt_cnt = data[1];
933 cmsis_dap_handle->packet_count = pkt_cnt;
934 LOG_DEBUG("CMSIS-DAP: Packet Count = %" PRId16, pkt_cnt);
935 }
936
937 retval = cmsis_dap_get_status();
938 if (retval != ERROR_OK)
939 return ERROR_FAIL;
940
941 /* Now try to connect to the target
942 * TODO: This is all SWD only @ present */
943 retval = cmsis_dap_cmd_DAP_SWJ_Clock(jtag_get_speed_khz());
944 if (retval != ERROR_OK)
945 return ERROR_FAIL;
946
947 /* Ask CMSIS-DAP to automatically retry on receiving WAIT for
948 * up to 64 times. This must be changed to 0 if sticky
949 * overrun detection is enabled. */
950 retval = cmsis_dap_cmd_DAP_TFER_Configure(0, 64, 0);
951 if (retval != ERROR_OK)
952 return ERROR_FAIL;
953 /* Data Phase (bit 2) must be set to 1 if sticky overrun
954 * detection is enabled */
955 retval = cmsis_dap_cmd_DAP_SWD_Configure(0); /* 1 TRN, no Data Phase */
956 if (retval != ERROR_OK)
957 return ERROR_FAIL;
958
959 retval = cmsis_dap_cmd_DAP_LED(0x03); /* Both LEDs on */
960 if (retval != ERROR_OK)
961 return ERROR_FAIL;
962
963 /* support connecting with srst asserted */
964 enum reset_types jtag_reset_config = jtag_get_reset_config();
965
966 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
967 if (jtag_reset_config & RESET_SRST_NO_GATING) {
968 retval = cmsis_dap_cmd_DAP_SWJ_Pins(0, (1 << 7), 0, NULL);
969 if (retval != ERROR_OK)
970 return ERROR_FAIL;
971 LOG_INFO("Connecting under reset");
972 }
973 }
974
975 cmsis_dap_cmd_DAP_LED(0x00); /* Both LEDs off */
976
977 LOG_INFO("CMSIS-DAP: Interface ready");
978
979 return ERROR_OK;
980 }
981
982 static int cmsis_dap_swd_init(void)
983 {
984 swd_mode = true;
985 return ERROR_OK;
986 }
987
988 static int cmsis_dap_quit(void)
989 {
990 cmsis_dap_cmd_DAP_Disconnect();
991 cmsis_dap_cmd_DAP_LED(0x00); /* Both LEDs off */
992
993 cmsis_dap_usb_close(cmsis_dap_handle);
994
995 return ERROR_OK;
996 }
997
998 static void cmsis_dap_execute_reset(struct jtag_command *cmd)
999 {
1000 /* Set both TRST and SRST even if they're not enabled as
1001 * there's no way to tristate them */
1002 uint8_t pins = 0;
1003
1004 if (!cmd->cmd.reset->srst)
1005 pins |= SWJ_PIN_SRST;
1006 if (!cmd->cmd.reset->trst)
1007 pins |= SWJ_PIN_TRST;
1008
1009 int retval = cmsis_dap_cmd_DAP_SWJ_Pins(pins,
1010 SWJ_PIN_TRST | SWJ_PIN_SRST, 0, NULL);
1011 if (retval != ERROR_OK)
1012 LOG_ERROR("CMSIS-DAP: Interface reset failed");
1013 }
1014
1015 static void cmsis_dap_execute_sleep(struct jtag_command *cmd)
1016 {
1017 #if 0
1018 int retval = cmsis_dap_cmd_DAP_Delay(cmd->cmd.sleep->us);
1019 if (retval != ERROR_OK)
1020 #endif
1021 jtag_sleep(cmd->cmd.sleep->us);
1022 }
1023
1024 /* Set TMS high for five TCK clocks, to move the TAP to the Test-Logic-Reset state */
1025 static int cmsis_dap_execute_tlr_reset(struct jtag_command *cmd)
1026 {
1027 LOG_INFO("cmsis-dap JTAG TLR_RESET");
1028 uint8_t seq = 0xff;
1029 int ret = cmsis_dap_cmd_DAP_SWJ_Sequence(8, &seq);
1030 if (ret == ERROR_OK)
1031 tap_set_state(TAP_RESET);
1032 return ret;
1033 }
1034
1035 /* Set new end state */
1036 static void cmsis_dap_end_state(tap_state_t state)
1037 {
1038 if (tap_is_state_stable(state))
1039 tap_set_end_state(state);
1040 else {
1041 LOG_ERROR("BUG: %i is not a valid end state", state);
1042 exit(-1);
1043 }
1044 }
1045
1046 #ifdef SPRINT_BINARY
1047 static void sprint_binary(char *s, const uint8_t *buf, int offset, int len)
1048 {
1049 if (!len)
1050 return;
1051
1052 /*
1053 buf = { 0x18 } len=5 should result in: 11000
1054 buf = { 0xff 0x18 } len=13 should result in: 11111111 11000
1055 buf = { 0xc0 0x18 } offset=3 len=10 should result in: 11000 11000
1056 i=3 there means i/8 = 0 so c = 0xFF, and
1057 */
1058 for (int i = offset; i < offset + len; ++i) {
1059 uint8_t c = buf[i / 8], mask = 1 << (i % 8);
1060 if ((i != offset) && !(i % 8))
1061 putchar(' ');
1062 *s++ = (c & mask) ? '1' : '0';
1063 }
1064 *s = 0;
1065 }
1066 #endif
1067
1068 #ifdef CMSIS_DAP_JTAG_DEBUG
1069 static void debug_parse_cmsis_buf(const uint8_t *cmd, int cmdlen)
1070 {
1071 /* cmd is a usb packet to go to the cmsis-dap interface */
1072 printf("cmsis-dap buffer (%d b): ", cmdlen);
1073 for (int i = 0; i < cmdlen; ++i)
1074 printf(" %02x", cmd[i]);
1075 printf("\n");
1076 switch (cmd[1]) {
1077 case CMD_DAP_JTAG_SEQ: {
1078 printf("cmsis-dap jtag sequence command %02x (n=%d)\n", cmd[1], cmd[2]);
1079 /*
1080 * #2 = number of sequences
1081 * #3 = sequence info 1
1082 * #4...4+n_bytes-1 = sequence 1
1083 * #4+n_bytes = sequence info 2
1084 * #5+n_bytes = sequence 2 (single bit)
1085 */
1086 int pos = 3;
1087 for (int seq = 0; seq < cmd[2]; ++seq) {
1088 uint8_t info = cmd[pos++];
1089 int len = info & DAP_JTAG_SEQ_TCK;
1090 if (len == 0)
1091 len = 64;
1092 printf(" sequence %d starting %d: info %02x (len=%d tms=%d read_tdo=%d): ",
1093 seq, pos, info, len, info & DAP_JTAG_SEQ_TMS, info & DAP_JTAG_SEQ_TDO);
1094 for (int i = 0; i < DIV_ROUND_UP(len, 8); ++i)
1095 printf(" %02x", cmd[pos+i]);
1096 pos += DIV_ROUND_UP(len, 8);
1097 printf("\n");
1098 }
1099 if (pos != cmdlen) {
1100 printf("BUFFER LENGTH MISMATCH looks like %d but %d specified", pos, cmdlen);
1101 exit(-1);
1102 }
1103
1104 break;
1105 }
1106 default:
1107 LOG_DEBUG("unknown cmsis-dap command %02x", cmd[1]);
1108 break;
1109 }
1110 }
1111 #endif
1112
1113 static void cmsis_dap_flush(void)
1114 {
1115 if (!queued_seq_count)
1116 return;
1117
1118 DEBUG_JTAG_IO("Flushing %d queued sequences (%d bytes) with %d pending scan results to capture",
1119 queued_seq_count, queued_seq_buf_end, pending_scan_result_count);
1120
1121 /* prep CMSIS-DAP packet */
1122 uint8_t *buffer = cmsis_dap_handle->packet_buffer;
1123 buffer[0] = 0; /* report number */
1124 buffer[1] = CMD_DAP_JTAG_SEQ;
1125 buffer[2] = queued_seq_count;
1126 memcpy(buffer + 3, queued_seq_buf, queued_seq_buf_end);
1127
1128 #ifdef CMSIS_DAP_JTAG_DEBUG
1129 debug_parse_cmsis_buf(buffer, queued_seq_buf_end + 3);
1130 #endif
1131
1132 /* send command to USB device */
1133 int retval = cmsis_dap_usb_xfer(cmsis_dap_handle, queued_seq_buf_end + 3);
1134 if (retval != ERROR_OK || buffer[1] != DAP_OK) {
1135 LOG_ERROR("CMSIS-DAP command CMD_DAP_JTAG_SEQ failed.");
1136 exit(-1);
1137 }
1138
1139 #ifdef CMSIS_DAP_JTAG_DEBUG
1140 DEBUG_JTAG_IO("USB response buf:");
1141 for (int c = 0; c < queued_seq_buf_end + 3; ++c)
1142 printf("%02X ", buffer[c]);
1143 printf("\n");
1144 #endif
1145
1146 /* copy scan results into client buffers */
1147 for (int i = 0; i < pending_scan_result_count; ++i) {
1148 struct pending_scan_result *scan = &pending_scan_results[i];
1149 DEBUG_JTAG_IO("Copying pending_scan_result %d/%d: %d bits from byte %d -> buffer + %d bits",
1150 i, pending_scan_result_count, scan->length, scan->first + 2, scan->buffer_offset);
1151 #ifdef CMSIS_DAP_JTAG_DEBUG
1152 for (uint32_t b = 0; b < DIV_ROUND_UP(scan->length, 8); ++b)
1153 printf("%02X ", buffer[2+scan->first+b]);
1154 printf("\n");
1155 #endif
1156 bit_copy(scan->buffer, scan->buffer_offset, buffer + 2 + scan->first, 0, scan->length);
1157 }
1158
1159 /* reset */
1160 queued_seq_count = 0;
1161 queued_seq_buf_end = 0;
1162 queued_seq_tdo_ptr = 0;
1163 pending_scan_result_count = 0;
1164 }
1165
1166 /* queue a sequence of bits to clock out TDI / in TDO, executing if the buffer is full.
1167 *
1168 * sequence=NULL means clock out zeros on TDI
1169 * tdo_buffer=NULL means don't capture TDO
1170 */
1171 static void cmsis_dap_add_jtag_sequence(int s_len, const uint8_t *sequence, int s_offset,
1172 bool tms, uint8_t *tdo_buffer, int tdo_buffer_offset)
1173 {
1174 DEBUG_JTAG_IO("[at %d] %d bits, tms %s, seq offset %d, tdo buf %p, tdo offset %d",
1175 queued_seq_buf_end,
1176 s_len, tms ? "HIGH" : "LOW", s_offset, tdo_buffer, tdo_buffer_offset);
1177
1178 if (s_len == 0)
1179 return;
1180
1181 if (s_len > 64) {
1182 DEBUG_JTAG_IO("START JTAG SEQ SPLIT");
1183 for (int offset = 0; offset < s_len; offset += 64) {
1184 int len = s_len - offset;
1185 if (len > 64)
1186 len = 64;
1187 DEBUG_JTAG_IO("Splitting long jtag sequence: %d-bit chunk starting at offset %d", len, offset);
1188 cmsis_dap_add_jtag_sequence(
1189 len,
1190 sequence,
1191 s_offset + offset,
1192 tms,
1193 tdo_buffer,
1194 tdo_buffer == NULL ? 0 : (tdo_buffer_offset + offset)
1195 );
1196 }
1197 DEBUG_JTAG_IO("END JTAG SEQ SPLIT");
1198 return;
1199 }
1200
1201 int cmd_len = 1 + DIV_ROUND_UP(s_len, 8);
1202 if (queued_seq_count >= 255 || queued_seq_buf_end + cmd_len > QUEUED_SEQ_BUF_LEN)
1203 /* empty out the buffer */
1204 cmsis_dap_flush();
1205
1206 ++queued_seq_count;
1207
1208 /* control byte */
1209 queued_seq_buf[queued_seq_buf_end] =
1210 (tms ? DAP_JTAG_SEQ_TMS : 0) |
1211 (tdo_buffer != NULL ? DAP_JTAG_SEQ_TDO : 0) |
1212 (s_len == 64 ? 0 : s_len);
1213
1214 if (sequence != NULL)
1215 bit_copy(&queued_seq_buf[queued_seq_buf_end + 1], 0, sequence, s_offset, s_len);
1216 else
1217 memset(&queued_seq_buf[queued_seq_buf_end + 1], 0, DIV_ROUND_UP(s_len, 8));
1218
1219 queued_seq_buf_end += cmd_len;
1220
1221 if (tdo_buffer != NULL) {
1222 struct pending_scan_result *scan = &pending_scan_results[pending_scan_result_count++];
1223 scan->first = queued_seq_tdo_ptr;
1224 queued_seq_tdo_ptr += DIV_ROUND_UP(s_len, 8);
1225 scan->length = s_len;
1226 scan->buffer = tdo_buffer;
1227 scan->buffer_offset = tdo_buffer_offset;
1228 }
1229 }
1230
1231 /* queue a sequence of bits to clock out TMS, executing if the buffer is full */
1232 static void cmsis_dap_add_tms_sequence(const uint8_t *sequence, int s_len)
1233 {
1234 DEBUG_JTAG_IO("%d bits: %02X", s_len, *sequence);
1235 /* we use a series of CMD_DAP_JTAG_SEQ commands to toggle TMS,
1236 because even though it seems ridiculously inefficient, it
1237 allows us to combine TMS and scan sequences into the same
1238 USB packet. */
1239 /* TODO: combine runs of the same tms value */
1240 for (int i = 0; i < s_len; ++i) {
1241 bool bit = (sequence[i / 8] & (1 << (i % 8))) != 0;
1242 cmsis_dap_add_jtag_sequence(1, NULL, 0, bit, NULL, 0);
1243 }
1244 }
1245
1246 /* Move to the end state by queuing a sequence to clock into TMS */
1247 static void cmsis_dap_state_move(void)
1248 {
1249 uint8_t tms_scan;
1250 uint8_t tms_scan_bits;
1251
1252 tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1253 tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1254
1255 DEBUG_JTAG_IO("state move from %s to %s: %d clocks, %02X on tms",
1256 tap_state_name(tap_get_state()), tap_state_name(tap_get_end_state()),
1257 tms_scan_bits, tms_scan);
1258 cmsis_dap_add_tms_sequence(&tms_scan, tms_scan_bits);
1259
1260 tap_set_state(tap_get_end_state());
1261 }
1262
1263
1264 /* Execute a JTAG scan operation by queueing TMS and TDI/TDO sequences */
1265 static void cmsis_dap_execute_scan(struct jtag_command *cmd)
1266 {
1267 DEBUG_JTAG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
1268 jtag_scan_type(cmd->cmd.scan));
1269
1270 /* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
1271 while (cmd->cmd.scan->num_fields > 0
1272 && cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
1273 cmd->cmd.scan->num_fields--;
1274 LOG_DEBUG("discarding trailing empty field");
1275 }
1276
1277 if (cmd->cmd.scan->num_fields == 0) {
1278 LOG_DEBUG("empty scan, doing nothing");
1279 return;
1280 }
1281
1282 if (cmd->cmd.scan->ir_scan) {
1283 if (tap_get_state() != TAP_IRSHIFT) {
1284 cmsis_dap_end_state(TAP_IRSHIFT);
1285 cmsis_dap_state_move();
1286 }
1287 } else {
1288 if (tap_get_state() != TAP_DRSHIFT) {
1289 cmsis_dap_end_state(TAP_DRSHIFT);
1290 cmsis_dap_state_move();
1291 }
1292 }
1293
1294 cmsis_dap_end_state(cmd->cmd.scan->end_state);
1295
1296 struct scan_field *field = cmd->cmd.scan->fields;
1297 unsigned scan_size = 0;
1298
1299 for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
1300 scan_size += field->num_bits;
1301 DEBUG_JTAG_IO("%s%s field %d/%d %d bits",
1302 field->in_value ? "in" : "",
1303 field->out_value ? "out" : "",
1304 i,
1305 cmd->cmd.scan->num_fields,
1306 field->num_bits);
1307
1308 if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
1309 DEBUG_JTAG_IO("Last field and have to move out of SHIFT state");
1310 /* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
1311 * movement. This last field can't have length zero, it was checked above. */
1312 cmsis_dap_add_jtag_sequence(
1313 field->num_bits - 1, /* number of bits to clock */
1314 field->out_value, /* output sequence */
1315 0, /* output offset */
1316 false, /* TMS low */
1317 field->in_value,
1318 0);
1319
1320 /* Clock the last bit out, with TMS high */
1321 uint8_t last_bit = 0;
1322 if (field->out_value)
1323 bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
1324 cmsis_dap_add_jtag_sequence(
1325 1,
1326 &last_bit,
1327 0,
1328 true,
1329 field->in_value,
1330 field->num_bits - 1);
1331 tap_set_state(tap_state_transition(tap_get_state(), 1));
1332
1333 /* Now clock one more cycle, with TMS low, to get us into a PAUSE state */
1334 cmsis_dap_add_jtag_sequence(
1335 1,
1336 &last_bit,
1337 0,
1338 false,
1339 NULL,
1340 0);
1341 tap_set_state(tap_state_transition(tap_get_state(), 0));
1342 } else {
1343 DEBUG_JTAG_IO("Internal field, staying in SHIFT state afterwards");
1344 /* Clocking part of a sequence into DR or IR with TMS=0,
1345 leaving TMS=0 at the end so we can continue later */
1346 cmsis_dap_add_jtag_sequence(
1347 field->num_bits,
1348 field->out_value,
1349 0,
1350 false,
1351 field->in_value,
1352 0);
1353 }
1354 }
1355
1356 if (tap_get_state() != tap_get_end_state()) {
1357 cmsis_dap_end_state(tap_get_end_state());
1358 cmsis_dap_state_move();
1359 }
1360
1361 DEBUG_JTAG_IO("%s scan, %i bits, end in %s",
1362 (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1363 tap_state_name(tap_get_end_state()));
1364 }
1365
1366 static void cmsis_dap_pathmove(int num_states, tap_state_t *path)
1367 {
1368 int i;
1369 uint8_t tms0 = 0x00;
1370 uint8_t tms1 = 0xff;
1371
1372 for (i = 0; i < num_states; i++) {
1373 if (path[i] == tap_state_transition(tap_get_state(), false))
1374 cmsis_dap_add_tms_sequence(&tms0, 1);
1375 else if (path[i] == tap_state_transition(tap_get_state(), true))
1376 cmsis_dap_add_tms_sequence(&tms1, 1);
1377 else {
1378 LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
1379 tap_state_name(tap_get_state()), tap_state_name(path[i]));
1380 exit(-1);
1381 }
1382
1383 tap_set_state(path[i]);
1384 }
1385
1386 cmsis_dap_end_state(tap_get_state());
1387 }
1388
1389 static void cmsis_dap_execute_pathmove(struct jtag_command *cmd)
1390 {
1391 DEBUG_JTAG_IO("pathmove: %i states, end in %i",
1392 cmd->cmd.pathmove->num_states,
1393 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
1394
1395 cmsis_dap_pathmove(cmd->cmd.pathmove->num_states, cmd->cmd.pathmove->path);
1396 }
1397
1398 static void cmsis_dap_stableclocks(int num_cycles)
1399 {
1400 int i;
1401
1402 uint8_t tms = tap_get_state() == TAP_RESET;
1403 /* TODO: Perform optimizations? */
1404 /* Execute num_cycles. */
1405 for (i = 0; i < num_cycles; i++)
1406 cmsis_dap_add_tms_sequence(&tms, 1);
1407 }
1408
1409 static void cmsis_dap_runtest(int num_cycles)
1410 {
1411 tap_state_t saved_end_state = tap_get_end_state();
1412
1413 /* Only do a state_move when we're not already in IDLE. */
1414 if (tap_get_state() != TAP_IDLE) {
1415 cmsis_dap_end_state(TAP_IDLE);
1416 cmsis_dap_state_move();
1417 }
1418 cmsis_dap_stableclocks(num_cycles);
1419
1420 /* Finish in end_state. */
1421 cmsis_dap_end_state(saved_end_state);
1422
1423 if (tap_get_state() != tap_get_end_state())
1424 cmsis_dap_state_move();
1425 }
1426
1427 static void cmsis_dap_execute_runtest(struct jtag_command *cmd)
1428 {
1429 DEBUG_JTAG_IO("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles,
1430 cmd->cmd.runtest->end_state);
1431
1432 cmsis_dap_end_state(cmd->cmd.runtest->end_state);
1433 cmsis_dap_runtest(cmd->cmd.runtest->num_cycles);
1434 }
1435
1436 static void cmsis_dap_execute_stableclocks(struct jtag_command *cmd)
1437 {
1438 DEBUG_JTAG_IO("stableclocks %i cycles", cmd->cmd.runtest->num_cycles);
1439 cmsis_dap_stableclocks(cmd->cmd.runtest->num_cycles);
1440 }
1441
1442 /* TODO: Is there need to call cmsis_dap_flush() for the JTAG_PATHMOVE,
1443 * JTAG_RUNTEST, JTAG_STABLECLOCKS? */
1444 static void cmsis_dap_execute_command(struct jtag_command *cmd)
1445 {
1446 switch (cmd->type) {
1447 case JTAG_RESET:
1448 cmsis_dap_flush();
1449 cmsis_dap_execute_reset(cmd);
1450 break;
1451 case JTAG_SLEEP:
1452 cmsis_dap_flush();
1453 cmsis_dap_execute_sleep(cmd);
1454 break;
1455 case JTAG_TLR_RESET:
1456 cmsis_dap_flush();
1457 cmsis_dap_execute_tlr_reset(cmd);
1458 break;
1459 case JTAG_SCAN:
1460 cmsis_dap_execute_scan(cmd);
1461 break;
1462 case JTAG_PATHMOVE:
1463 cmsis_dap_execute_pathmove(cmd);
1464 break;
1465 case JTAG_RUNTEST:
1466 cmsis_dap_execute_runtest(cmd);
1467 break;
1468 case JTAG_STABLECLOCKS:
1469 cmsis_dap_execute_stableclocks(cmd);
1470 break;
1471 case JTAG_TMS:
1472 default:
1473 LOG_ERROR("BUG: unknown JTAG command type 0x%X encountered", cmd->type);
1474 exit(-1);
1475 }
1476 }
1477
1478 static int cmsis_dap_execute_queue(void)
1479 {
1480 struct jtag_command *cmd = jtag_command_queue;
1481
1482 while (cmd != NULL) {
1483 cmsis_dap_execute_command(cmd);
1484 cmd = cmd->next;
1485 }
1486
1487 cmsis_dap_flush();
1488
1489 return ERROR_OK;
1490 }
1491
1492 static int cmsis_dap_speed(int speed)
1493 {
1494 if (speed > DAP_MAX_CLOCK) {
1495 LOG_INFO("reduce speed request: %dkHz to %dkHz maximum", speed, DAP_MAX_CLOCK);
1496 speed = DAP_MAX_CLOCK;
1497 }
1498
1499 if (speed == 0) {
1500 LOG_INFO("RTCK not supported");
1501 return ERROR_JTAG_NOT_IMPLEMENTED;
1502 }
1503
1504 return cmsis_dap_cmd_DAP_SWJ_Clock(speed);
1505 }
1506
1507 static int cmsis_dap_speed_div(int speed, int *khz)
1508 {
1509 *khz = speed;
1510 return ERROR_OK;
1511 }
1512
1513 static int cmsis_dap_khz(int khz, int *jtag_speed)
1514 {
1515 *jtag_speed = khz;
1516 return ERROR_OK;
1517 }
1518
1519 static int_least32_t cmsis_dap_swd_frequency(int_least32_t hz)
1520 {
1521 if (hz > 0)
1522 cmsis_dap_speed(hz / 1000);
1523
1524 return hz;
1525 }
1526
1527
1528 COMMAND_HANDLER(cmsis_dap_handle_info_command)
1529 {
1530 if (cmsis_dap_get_version_info() == ERROR_OK)
1531 cmsis_dap_get_status();
1532
1533 return ERROR_OK;
1534 }
1535
1536 COMMAND_HANDLER(cmsis_dap_handle_vid_pid_command)
1537 {
1538 if (CMD_ARGC > MAX_USB_IDS * 2) {
1539 LOG_WARNING("ignoring extra IDs in cmsis_dap_vid_pid "
1540 "(maximum is %d pairs)", MAX_USB_IDS);
1541 CMD_ARGC = MAX_USB_IDS * 2;
1542 }
1543 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
1544 LOG_WARNING("incomplete cmsis_dap_vid_pid configuration directive");
1545 if (CMD_ARGC < 2)
1546 return ERROR_COMMAND_SYNTAX_ERROR;
1547 /* remove the incomplete trailing id */
1548 CMD_ARGC -= 1;
1549 }
1550
1551 unsigned i;
1552 for (i = 0; i < CMD_ARGC; i += 2) {
1553 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], cmsis_dap_vid[i >> 1]);
1554 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], cmsis_dap_pid[i >> 1]);
1555 }
1556
1557 /*
1558 * Explicitly terminate, in case there are multiples instances of
1559 * cmsis_dap_vid_pid.
1560 */
1561 cmsis_dap_vid[i >> 1] = cmsis_dap_pid[i >> 1] = 0;
1562
1563 return ERROR_OK;
1564 }
1565
1566 COMMAND_HANDLER(cmsis_dap_handle_serial_command)
1567 {
1568 if (CMD_ARGC == 1) {
1569 size_t len = mbstowcs(NULL, CMD_ARGV[0], 0);
1570 cmsis_dap_serial = calloc(len + 1, sizeof(wchar_t));
1571 if (cmsis_dap_serial == NULL) {
1572 LOG_ERROR("unable to allocate memory");
1573 return ERROR_OK;
1574 }
1575 if (mbstowcs(cmsis_dap_serial, CMD_ARGV[0], len + 1) == (size_t)-1) {
1576 free(cmsis_dap_serial);
1577 cmsis_dap_serial = NULL;
1578 LOG_ERROR("unable to convert serial");
1579 }
1580 } else {
1581 LOG_ERROR("expected exactly one argument to cmsis_dap_serial <serial-number>");
1582 }
1583
1584 return ERROR_OK;
1585 }
1586
1587 static const struct command_registration cmsis_dap_subcommand_handlers[] = {
1588 {
1589 .name = "info",
1590 .handler = &cmsis_dap_handle_info_command,
1591 .mode = COMMAND_EXEC,
1592 .usage = "",
1593 .help = "show cmsis-dap info",
1594 },
1595 COMMAND_REGISTRATION_DONE
1596 };
1597
1598 static const struct command_registration cmsis_dap_command_handlers[] = {
1599 {
1600 .name = "cmsis-dap",
1601 .mode = COMMAND_ANY,
1602 .help = "perform CMSIS-DAP management",
1603 .usage = "<cmd>",
1604 .chain = cmsis_dap_subcommand_handlers,
1605 },
1606 {
1607 .name = "cmsis_dap_vid_pid",
1608 .handler = &cmsis_dap_handle_vid_pid_command,
1609 .mode = COMMAND_CONFIG,
1610 .help = "the vendor ID and product ID of the CMSIS-DAP device",
1611 .usage = "(vid pid)* ",
1612 },
1613 {
1614 .name = "cmsis_dap_serial",
1615 .handler = &cmsis_dap_handle_serial_command,
1616 .mode = COMMAND_CONFIG,
1617 .help = "set the serial number of the adapter",
1618 .usage = "serial_string",
1619 },
1620 COMMAND_REGISTRATION_DONE
1621 };
1622
1623 static const struct swd_driver cmsis_dap_swd_driver = {
1624 .init = cmsis_dap_swd_init,
1625 .frequency = cmsis_dap_swd_frequency,
1626 .switch_seq = cmsis_dap_swd_switch_seq,
1627 .read_reg = cmsis_dap_swd_read_reg,
1628 .write_reg = cmsis_dap_swd_write_reg,
1629 .run = cmsis_dap_swd_run_queue,
1630 };
1631
1632 static const char * const cmsis_dap_transport[] = { "swd", "jtag", NULL };
1633
1634 struct jtag_interface cmsis_dap_interface = {
1635 .name = "cmsis-dap",
1636 .commands = cmsis_dap_command_handlers,
1637 .swd = &cmsis_dap_swd_driver,
1638 .transports = cmsis_dap_transport,
1639
1640 .execute_queue = cmsis_dap_execute_queue,
1641 .speed = cmsis_dap_speed,
1642 .speed_div = cmsis_dap_speed_div,
1643 .khz = cmsis_dap_khz,
1644 .init = cmsis_dap_init,
1645 .quit = cmsis_dap_quit,
1646 };