jtag_libusb_bulk_read|write: return error code instead of size
[openocd.git] / src / jtag / drivers / stlink_usb.c
1 /***************************************************************************
2 * SWIM contributions by Ake Rehnman *
3 * Copyright (C) 2017 Ake Rehnman *
4 * ake.rehnman(at)gmail.com *
5 * *
6 * Copyright (C) 2011-2012 by Mathias Kuester *
7 * Mathias Kuester <kesmtp@freenet.de> *
8 * *
9 * Copyright (C) 2012 by Spencer Oliver *
10 * spen@spen-soft.co.uk *
11 * *
12 * This code is based on https://github.com/texane/stlink *
13 * *
14 * This program is free software; you can redistribute it and/or modify *
15 * it under the terms of the GNU General Public License as published by *
16 * the Free Software Foundation; either version 2 of the License, or *
17 * (at your option) any later version. *
18 * *
19 * This program is distributed in the hope that it will be useful, *
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
22 * GNU General Public License for more details. *
23 * *
24 * You should have received a copy of the GNU General Public License *
25 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
26 ***************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 /* project specific includes */
33 #include <helper/binarybuffer.h>
34 #include <helper/bits.h>
35 #include <jtag/interface.h>
36 #include <jtag/hla/hla_layout.h>
37 #include <jtag/hla/hla_transport.h>
38 #include <jtag/hla/hla_interface.h>
39 #include <target/target.h>
40 #include <transport/transport.h>
41
42 #include <target/cortex_m.h>
43
44 #include "libusb_common.h"
45
46 #ifdef HAVE_LIBUSB1
47 #define USE_LIBUSB_ASYNCIO
48 #endif
49
50 #define ENDPOINT_IN 0x80
51 #define ENDPOINT_OUT 0x00
52
53 #define STLINK_WRITE_TIMEOUT 1000
54 #define STLINK_READ_TIMEOUT 1000
55
56 #define STLINK_NULL_EP 0
57 #define STLINK_RX_EP (1|ENDPOINT_IN)
58 #define STLINK_TX_EP (2|ENDPOINT_OUT)
59 #define STLINK_TRACE_EP (3|ENDPOINT_IN)
60
61 #define STLINK_V2_1_TX_EP (1|ENDPOINT_OUT)
62 #define STLINK_V2_1_TRACE_EP (2|ENDPOINT_IN)
63
64 #define STLINK_SG_SIZE (31)
65 #define STLINK_DATA_SIZE (4096)
66 #define STLINK_CMD_SIZE_V2 (16)
67 #define STLINK_CMD_SIZE_V1 (10)
68
69 #define STLINK_V1_PID (0x3744)
70 #define STLINK_V2_PID (0x3748)
71 #define STLINK_V2_1_PID (0x374B)
72 #define STLINK_V2_1_NO_MSD_PID (0x3752)
73 #define STLINK_V3_USBLOADER_PID (0x374D)
74 #define STLINK_V3E_PID (0x374E)
75 #define STLINK_V3S_PID (0x374F)
76 #define STLINK_V3_2VCP_PID (0x3753)
77
78 /*
79 * ST-Link/V1, ST-Link/V2 and ST-Link/V2.1 are full-speed USB devices and
80 * this limits the bulk packet size and the 8bit read/writes to max 64 bytes.
81 * STLINK-V3 is a high speed USB 2.0 and the limit is 512 bytes.
82 */
83 #define STLINK_MAX_RW8 (64)
84 #define STLINKV3_MAX_RW8 (512)
85
86 /* "WAIT" responses will be retried (with exponential backoff) at
87 * most this many times before failing to caller.
88 */
89 #define MAX_WAIT_RETRIES 8
90
91 enum stlink_jtag_api_version {
92 STLINK_JTAG_API_V1 = 1,
93 STLINK_JTAG_API_V2,
94 STLINK_JTAG_API_V3,
95 };
96
97 /** */
98 struct stlink_usb_version {
99 /** */
100 int stlink;
101 /** */
102 int jtag;
103 /** */
104 int swim;
105 /** jtag api version supported */
106 enum stlink_jtag_api_version jtag_api;
107 /** one bit for each feature supported. See macros STLINK_F_* */
108 uint32_t flags;
109 };
110
111 /** */
112 struct stlink_usb_handle_s {
113 /** */
114 struct jtag_libusb_device_handle *fd;
115 /** */
116 struct libusb_transfer *trans;
117 /** */
118 uint8_t rx_ep;
119 /** */
120 uint8_t tx_ep;
121 /** */
122 uint8_t trace_ep;
123 /** */
124 uint8_t cmdbuf[STLINK_SG_SIZE];
125 /** */
126 uint8_t cmdidx;
127 /** */
128 uint8_t direction;
129 /** */
130 uint8_t databuf[STLINK_DATA_SIZE];
131 /** */
132 uint32_t max_mem_packet;
133 /** */
134 enum hl_transports transport;
135 /** */
136 struct stlink_usb_version version;
137 /** */
138 uint16_t vid;
139 /** */
140 uint16_t pid;
141 /** */
142 struct {
143 /** whether SWO tracing is enabled or not */
144 bool enabled;
145 /** trace module source clock */
146 uint32_t source_hz;
147 } trace;
148 /** reconnect is needed next time we try to query the
149 * status */
150 bool reconnect_pending;
151 };
152
153 #define STLINK_SWIM_ERR_OK 0x00
154 #define STLINK_SWIM_BUSY 0x01
155 #define STLINK_DEBUG_ERR_OK 0x80
156 #define STLINK_DEBUG_ERR_FAULT 0x81
157 #define STLINK_SWD_AP_WAIT 0x10
158 #define STLINK_SWD_AP_FAULT 0x11
159 #define STLINK_SWD_AP_ERROR 0x12
160 #define STLINK_SWD_AP_PARITY_ERROR 0x13
161 #define STLINK_JTAG_GET_IDCODE_ERROR 0x09
162 #define STLINK_JTAG_WRITE_ERROR 0x0c
163 #define STLINK_JTAG_WRITE_VERIF_ERROR 0x0d
164 #define STLINK_SWD_DP_WAIT 0x14
165 #define STLINK_SWD_DP_FAULT 0x15
166 #define STLINK_SWD_DP_ERROR 0x16
167 #define STLINK_SWD_DP_PARITY_ERROR 0x17
168
169 #define STLINK_SWD_AP_WDATA_ERROR 0x18
170 #define STLINK_SWD_AP_STICKY_ERROR 0x19
171 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
172
173 #define STLINK_BAD_AP_ERROR 0x1d
174
175 #define STLINK_CORE_RUNNING 0x80
176 #define STLINK_CORE_HALTED 0x81
177 #define STLINK_CORE_STAT_UNKNOWN -1
178
179 #define STLINK_GET_VERSION 0xF1
180 #define STLINK_DEBUG_COMMAND 0xF2
181 #define STLINK_DFU_COMMAND 0xF3
182 #define STLINK_SWIM_COMMAND 0xF4
183 #define STLINK_GET_CURRENT_MODE 0xF5
184 #define STLINK_GET_TARGET_VOLTAGE 0xF7
185
186 #define STLINK_DEV_DFU_MODE 0x00
187 #define STLINK_DEV_MASS_MODE 0x01
188 #define STLINK_DEV_DEBUG_MODE 0x02
189 #define STLINK_DEV_SWIM_MODE 0x03
190 #define STLINK_DEV_BOOTLOADER_MODE 0x04
191 #define STLINK_DEV_UNKNOWN_MODE -1
192
193 #define STLINK_DFU_EXIT 0x07
194
195 /*
196 STLINK_SWIM_ENTER_SEQ
197 1.3ms low then 750Hz then 1.5kHz
198
199 STLINK_SWIM_GEN_RST
200 STM8 DM pulls reset pin low 50us
201
202 STLINK_SWIM_SPEED
203 uint8_t (0=low|1=high)
204
205 STLINK_SWIM_WRITEMEM
206 uint16_t length
207 uint32_t address
208
209 STLINK_SWIM_RESET
210 send syncronization seq (16us low, response 64 clocks low)
211 */
212 #define STLINK_SWIM_ENTER 0x00
213 #define STLINK_SWIM_EXIT 0x01
214 #define STLINK_SWIM_READ_CAP 0x02
215 #define STLINK_SWIM_SPEED 0x03
216 #define STLINK_SWIM_ENTER_SEQ 0x04
217 #define STLINK_SWIM_GEN_RST 0x05
218 #define STLINK_SWIM_RESET 0x06
219 #define STLINK_SWIM_ASSERT_RESET 0x07
220 #define STLINK_SWIM_DEASSERT_RESET 0x08
221 #define STLINK_SWIM_READSTATUS 0x09
222 #define STLINK_SWIM_WRITEMEM 0x0a
223 #define STLINK_SWIM_READMEM 0x0b
224 #define STLINK_SWIM_READBUF 0x0c
225
226 #define STLINK_DEBUG_GETSTATUS 0x01
227 #define STLINK_DEBUG_FORCEDEBUG 0x02
228 #define STLINK_DEBUG_APIV1_RESETSYS 0x03
229 #define STLINK_DEBUG_APIV1_READALLREGS 0x04
230 #define STLINK_DEBUG_APIV1_READREG 0x05
231 #define STLINK_DEBUG_APIV1_WRITEREG 0x06
232 #define STLINK_DEBUG_READMEM_32BIT 0x07
233 #define STLINK_DEBUG_WRITEMEM_32BIT 0x08
234 #define STLINK_DEBUG_RUNCORE 0x09
235 #define STLINK_DEBUG_STEPCORE 0x0a
236 #define STLINK_DEBUG_APIV1_SETFP 0x0b
237 #define STLINK_DEBUG_READMEM_8BIT 0x0c
238 #define STLINK_DEBUG_WRITEMEM_8BIT 0x0d
239 #define STLINK_DEBUG_APIV1_CLEARFP 0x0e
240 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG 0x0f
241 #define STLINK_DEBUG_APIV1_SETWATCHPOINT 0x10
242
243 #define STLINK_DEBUG_ENTER_JTAG_RESET 0x00
244 #define STLINK_DEBUG_ENTER_SWD_NO_RESET 0xa3
245 #define STLINK_DEBUG_ENTER_JTAG_NO_RESET 0xa4
246
247 #define STLINK_DEBUG_APIV1_ENTER 0x20
248 #define STLINK_DEBUG_EXIT 0x21
249 #define STLINK_DEBUG_READCOREID 0x22
250
251 #define STLINK_DEBUG_APIV2_ENTER 0x30
252 #define STLINK_DEBUG_APIV2_READ_IDCODES 0x31
253 #define STLINK_DEBUG_APIV2_RESETSYS 0x32
254 #define STLINK_DEBUG_APIV2_READREG 0x33
255 #define STLINK_DEBUG_APIV2_WRITEREG 0x34
256 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG 0x35
257 #define STLINK_DEBUG_APIV2_READDEBUGREG 0x36
258
259 #define STLINK_DEBUG_APIV2_READALLREGS 0x3A
260 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
261 #define STLINK_DEBUG_APIV2_DRIVE_NRST 0x3C
262
263 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS2 0x3E
264
265 #define STLINK_DEBUG_APIV2_START_TRACE_RX 0x40
266 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX 0x41
267 #define STLINK_DEBUG_APIV2_GET_TRACE_NB 0x42
268 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ 0x43
269 #define STLINK_DEBUG_APIV2_JTAG_SET_FREQ 0x44
270 #define STLINK_DEBUG_APIV2_READ_DAP_REG 0x45
271 #define STLINK_DEBUG_APIV2_WRITE_DAP_REG 0x46
272 #define STLINK_DEBUG_APIV2_READMEM_16BIT 0x47
273 #define STLINK_DEBUG_APIV2_WRITEMEM_16BIT 0x48
274
275 #define STLINK_DEBUG_APIV2_INIT_AP 0x4B
276 #define STLINK_DEBUG_APIV2_CLOSE_AP_DBG 0x4C
277
278 #define STLINK_APIV3_SET_COM_FREQ 0x61
279 #define STLINK_APIV3_GET_COM_FREQ 0x62
280
281 #define STLINK_APIV3_GET_VERSION_EX 0xFB
282
283 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW 0x00
284 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH 0x01
285 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
286
287 #define STLINK_DEBUG_PORT_ACCESS 0xffff
288
289 #define STLINK_TRACE_SIZE 4096
290 #define STLINK_TRACE_MAX_HZ 2000000
291
292 #define STLINK_V3_MAX_FREQ_NB 10
293
294 /** */
295 enum stlink_mode {
296 STLINK_MODE_UNKNOWN = 0,
297 STLINK_MODE_DFU,
298 STLINK_MODE_MASS,
299 STLINK_MODE_DEBUG_JTAG,
300 STLINK_MODE_DEBUG_SWD,
301 STLINK_MODE_DEBUG_SWIM
302 };
303
304 #define REQUEST_SENSE 0x03
305 #define REQUEST_SENSE_LENGTH 18
306
307 /*
308 * Map the relevant features, quirks and workaround for specific firmware
309 * version of stlink
310 */
311 #define STLINK_F_HAS_TRACE BIT(0)
312 #define STLINK_F_HAS_SWD_SET_FREQ BIT(1)
313 #define STLINK_F_HAS_JTAG_SET_FREQ BIT(2)
314 #define STLINK_F_HAS_MEM_16BIT BIT(3)
315 #define STLINK_F_HAS_GETLASTRWSTATUS2 BIT(4)
316 #define STLINK_F_HAS_DAP_REG BIT(5)
317 #define STLINK_F_QUIRK_JTAG_DP_READ BIT(6)
318 #define STLINK_F_HAS_AP_INIT BIT(7)
319 #define STLINK_F_HAS_DPBANKSEL BIT(8)
320
321 /* aliases */
322 #define STLINK_F_HAS_TARGET_VOLT STLINK_F_HAS_TRACE
323
324 struct speed_map {
325 int speed;
326 int speed_divisor;
327 };
328
329 /* SWD clock speed */
330 static const struct speed_map stlink_khz_to_speed_map_swd[] = {
331 {4000, 0},
332 {1800, 1}, /* default */
333 {1200, 2},
334 {950, 3},
335 {480, 7},
336 {240, 15},
337 {125, 31},
338 {100, 40},
339 {50, 79},
340 {25, 158},
341 {15, 265},
342 {5, 798}
343 };
344
345 /* JTAG clock speed */
346 static const struct speed_map stlink_khz_to_speed_map_jtag[] = {
347 {18000, 2},
348 {9000, 4},
349 {4500, 8},
350 {2250, 16},
351 {1125, 32}, /* default */
352 {562, 64},
353 {281, 128},
354 {140, 256}
355 };
356
357 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
358 static int stlink_swim_status(void *handle);
359 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size);
360 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map);
361 static int stlink_speed(void *handle, int khz, bool query);
362
363 /** */
364 static unsigned int stlink_usb_block(void *handle)
365 {
366 struct stlink_usb_handle_s *h = handle;
367
368 assert(handle != NULL);
369
370 if (h->version.stlink == 3)
371 return STLINKV3_MAX_RW8;
372 else
373 return STLINK_MAX_RW8;
374 }
375
376
377
378 #ifdef USE_LIBUSB_ASYNCIO
379
380 static LIBUSB_CALL void sync_transfer_cb(struct libusb_transfer *transfer)
381 {
382 int *completed = transfer->user_data;
383 *completed = 1;
384 /* caller interprets result and frees transfer */
385 }
386
387
388 static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
389 {
390 int r, *completed = transfer->user_data;
391
392 /* Assuming a single libusb context exists. There no existing interface into this
393 * module to pass a libusb context.
394 */
395 struct libusb_context *ctx = NULL;
396
397 while (!*completed) {
398 r = libusb_handle_events_completed(ctx, completed);
399 if (r < 0) {
400 if (r == LIBUSB_ERROR_INTERRUPTED)
401 continue;
402 libusb_cancel_transfer(transfer);
403 continue;
404 }
405 }
406 }
407
408
409 static int transfer_error_status(const struct libusb_transfer *transfer)
410 {
411 int r = 0;
412
413 switch (transfer->status) {
414 case LIBUSB_TRANSFER_COMPLETED:
415 r = 0;
416 break;
417 case LIBUSB_TRANSFER_TIMED_OUT:
418 r = LIBUSB_ERROR_TIMEOUT;
419 break;
420 case LIBUSB_TRANSFER_STALL:
421 r = LIBUSB_ERROR_PIPE;
422 break;
423 case LIBUSB_TRANSFER_OVERFLOW:
424 r = LIBUSB_ERROR_OVERFLOW;
425 break;
426 case LIBUSB_TRANSFER_NO_DEVICE:
427 r = LIBUSB_ERROR_NO_DEVICE;
428 break;
429 case LIBUSB_TRANSFER_ERROR:
430 case LIBUSB_TRANSFER_CANCELLED:
431 r = LIBUSB_ERROR_IO;
432 break;
433 default:
434 r = LIBUSB_ERROR_OTHER;
435 break;
436 }
437
438 return r;
439 }
440
441 struct jtag_xfer {
442 int ep;
443 uint8_t *buf;
444 size_t size;
445 /* Internal */
446 int retval;
447 int completed;
448 size_t transfer_size;
449 struct libusb_transfer *transfer;
450 };
451
452 static int jtag_libusb_bulk_transfer_n(
453 jtag_libusb_device_handle * dev_handle,
454 struct jtag_xfer *transfers,
455 size_t n_transfers,
456 int timeout)
457 {
458 int retval = 0;
459 int returnval = ERROR_OK;
460
461
462 for (size_t i = 0; i < n_transfers; ++i) {
463 transfers[i].retval = 0;
464 transfers[i].completed = 0;
465 transfers[i].transfer_size = 0;
466 transfers[i].transfer = libusb_alloc_transfer(0);
467
468 if (transfers[i].transfer == NULL) {
469 for (size_t j = 0; j < i; ++j)
470 libusb_free_transfer(transfers[j].transfer);
471
472 LOG_DEBUG("ERROR, failed to alloc usb transfers");
473 for (size_t k = 0; k < n_transfers; ++k)
474 transfers[k].retval = LIBUSB_ERROR_NO_MEM;
475 return ERROR_FAIL;
476 }
477 }
478
479 for (size_t i = 0; i < n_transfers; ++i) {
480 libusb_fill_bulk_transfer(
481 transfers[i].transfer,
482 dev_handle,
483 transfers[i].ep, transfers[i].buf, transfers[i].size,
484 sync_transfer_cb, &transfers[i].completed, timeout);
485 transfers[i].transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
486
487 retval = libusb_submit_transfer(transfers[i].transfer);
488 if (retval < 0) {
489 LOG_DEBUG("ERROR, failed to submit transfer %zu, error %d", i, retval);
490
491 /* Probably no point continuing to submit transfers once a submission fails.
492 * As a result, tag all remaining transfers as errors.
493 */
494 for (size_t j = i; j < n_transfers; ++j)
495 transfers[j].retval = retval;
496
497 returnval = ERROR_FAIL;
498 break;
499 }
500 }
501
502 /* Wait for every submitted USB transfer to complete.
503 */
504 for (size_t i = 0; i < n_transfers; ++i) {
505 if (transfers[i].retval == 0) {
506 sync_transfer_wait_for_completion(transfers[i].transfer);
507
508 retval = transfer_error_status(transfers[i].transfer);
509 if (retval) {
510 returnval = ERROR_FAIL;
511 transfers[i].retval = retval;
512 LOG_DEBUG("ERROR, transfer %zu failed, error %d", i, retval);
513 } else {
514 /* Assuming actual_length is only valid if there is no transfer error.
515 */
516 transfers[i].transfer_size = transfers[i].transfer->actual_length;
517 }
518 }
519
520 libusb_free_transfer(transfers[i].transfer);
521 transfers[i].transfer = NULL;
522 }
523
524 return returnval;
525 }
526
527 #endif
528
529
530 /** */
531 static int stlink_usb_xfer_v1_get_status(void *handle)
532 {
533 struct stlink_usb_handle_s *h = handle;
534 int tr, ret;
535
536 assert(handle != NULL);
537
538 /* read status */
539 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
540
541 ret = jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)h->cmdbuf, 13,
542 STLINK_READ_TIMEOUT, &tr);
543 if (ret || tr != 13)
544 return ERROR_FAIL;
545
546 uint32_t t1;
547
548 t1 = buf_get_u32(h->cmdbuf, 0, 32);
549
550 /* check for USBS */
551 if (t1 != 0x53425355)
552 return ERROR_FAIL;
553 /*
554 * CSW status:
555 * 0 success
556 * 1 command failure
557 * 2 phase error
558 */
559 if (h->cmdbuf[12] != 0)
560 return ERROR_FAIL;
561
562 return ERROR_OK;
563 }
564
565 #ifdef USE_LIBUSB_ASYNCIO
566 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
567 {
568 struct stlink_usb_handle_s *h = handle;
569
570 assert(handle != NULL);
571
572 size_t n_transfers = 0;
573 struct jtag_xfer transfers[2];
574
575 memset(transfers, 0, sizeof(transfers));
576
577 transfers[0].ep = h->tx_ep;
578 transfers[0].buf = h->cmdbuf;
579 transfers[0].size = cmdsize;
580
581 ++n_transfers;
582
583 if (h->direction == h->tx_ep && size) {
584 transfers[1].ep = h->tx_ep;
585 transfers[1].buf = (uint8_t *)buf;
586 transfers[1].size = size;
587
588 ++n_transfers;
589 } else if (h->direction == h->rx_ep && size) {
590 transfers[1].ep = h->rx_ep;
591 transfers[1].buf = (uint8_t *)buf;
592 transfers[1].size = size;
593
594 ++n_transfers;
595 }
596
597 return jtag_libusb_bulk_transfer_n(
598 h->fd,
599 transfers,
600 n_transfers,
601 STLINK_WRITE_TIMEOUT);
602 }
603 #else
604 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
605 {
606 struct stlink_usb_handle_s *h = handle;
607 int tr, ret;
608
609 assert(handle != NULL);
610
611 ret = jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)h->cmdbuf,
612 cmdsize, STLINK_WRITE_TIMEOUT, &tr);
613 if (ret || tr != cmdsize)
614 return ERROR_FAIL;
615
616 if (h->direction == h->tx_ep && size) {
617 ret = jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)buf,
618 size, STLINK_WRITE_TIMEOUT, &tr);
619 if (ret || tr != size) {
620 LOG_DEBUG("bulk write failed");
621 return ERROR_FAIL;
622 }
623 } else if (h->direction == h->rx_ep && size) {
624 ret = jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)buf,
625 size, STLINK_READ_TIMEOUT, &tr);
626 if (ret || tr != size) {
627 LOG_DEBUG("bulk read failed");
628 return ERROR_FAIL;
629 }
630 }
631
632 return ERROR_OK;
633 }
634 #endif
635
636 /** */
637 static int stlink_usb_xfer_v1_get_sense(void *handle)
638 {
639 int res;
640 struct stlink_usb_handle_s *h = handle;
641
642 assert(handle != NULL);
643
644 stlink_usb_init_buffer(handle, h->rx_ep, 16);
645
646 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE;
647 h->cmdbuf[h->cmdidx++] = 0;
648 h->cmdbuf[h->cmdidx++] = 0;
649 h->cmdbuf[h->cmdidx++] = 0;
650 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE_LENGTH;
651
652 res = stlink_usb_xfer_rw(handle, REQUEST_SENSE_LENGTH, h->databuf, 16);
653
654 if (res != ERROR_OK)
655 return res;
656
657 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK)
658 return ERROR_FAIL;
659
660 return ERROR_OK;
661 }
662
663 /*
664 transfers block in cmdbuf
665 <size> indicates number of bytes in the following
666 data phase.
667 Ignore the (eventual) error code in the received packet.
668 */
669 static int stlink_usb_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
670 {
671 int err, cmdsize = STLINK_CMD_SIZE_V2;
672 struct stlink_usb_handle_s *h = handle;
673
674 assert(handle != NULL);
675
676 if (h->version.stlink == 1) {
677 cmdsize = STLINK_SG_SIZE;
678 /* put length in bCBWCBLength */
679 h->cmdbuf[14] = h->cmdidx-15;
680 }
681
682 err = stlink_usb_xfer_rw(handle, cmdsize, buf, size);
683
684 if (err != ERROR_OK)
685 return err;
686
687 if (h->version.stlink == 1) {
688 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK) {
689 /* check csw status */
690 if (h->cmdbuf[12] == 1) {
691 LOG_DEBUG("get sense");
692 if (stlink_usb_xfer_v1_get_sense(handle) != ERROR_OK)
693 return ERROR_FAIL;
694 }
695 return ERROR_FAIL;
696 }
697 }
698
699 return ERROR_OK;
700 }
701
702 /**
703 Converts an STLINK status code held in the first byte of a response
704 to an openocd error, logs any error/wait status as debug output.
705 */
706 static int stlink_usb_error_check(void *handle)
707 {
708 struct stlink_usb_handle_s *h = handle;
709
710 assert(handle != NULL);
711
712 if (h->transport == HL_TRANSPORT_SWIM) {
713 switch (h->databuf[0]) {
714 case STLINK_SWIM_ERR_OK:
715 return ERROR_OK;
716 case STLINK_SWIM_BUSY:
717 return ERROR_WAIT;
718 default:
719 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
720 return ERROR_FAIL;
721 }
722 }
723
724 /* TODO: no error checking yet on api V1 */
725 if (h->version.jtag_api == STLINK_JTAG_API_V1)
726 h->databuf[0] = STLINK_DEBUG_ERR_OK;
727
728 switch (h->databuf[0]) {
729 case STLINK_DEBUG_ERR_OK:
730 return ERROR_OK;
731 case STLINK_DEBUG_ERR_FAULT:
732 LOG_DEBUG("SWD fault response (0x%x)", STLINK_DEBUG_ERR_FAULT);
733 return ERROR_FAIL;
734 case STLINK_SWD_AP_WAIT:
735 LOG_DEBUG("wait status SWD_AP_WAIT (0x%x)", STLINK_SWD_AP_WAIT);
736 return ERROR_WAIT;
737 case STLINK_SWD_DP_WAIT:
738 LOG_DEBUG("wait status SWD_DP_WAIT (0x%x)", STLINK_SWD_DP_WAIT);
739 return ERROR_WAIT;
740 case STLINK_JTAG_GET_IDCODE_ERROR:
741 LOG_DEBUG("STLINK_JTAG_GET_IDCODE_ERROR");
742 return ERROR_FAIL;
743 case STLINK_JTAG_WRITE_ERROR:
744 LOG_DEBUG("Write error");
745 return ERROR_FAIL;
746 case STLINK_JTAG_WRITE_VERIF_ERROR:
747 LOG_DEBUG("Write verify error, ignoring");
748 return ERROR_OK;
749 case STLINK_SWD_AP_FAULT:
750 /* git://git.ac6.fr/openocd commit 657e3e885b9ee10
751 * returns ERROR_OK with the comment:
752 * Change in error status when reading outside RAM.
753 * This fix allows CDT plugin to visualize memory.
754 */
755 LOG_DEBUG("STLINK_SWD_AP_FAULT");
756 return ERROR_FAIL;
757 case STLINK_SWD_AP_ERROR:
758 LOG_DEBUG("STLINK_SWD_AP_ERROR");
759 return ERROR_FAIL;
760 case STLINK_SWD_AP_PARITY_ERROR:
761 LOG_DEBUG("STLINK_SWD_AP_PARITY_ERROR");
762 return ERROR_FAIL;
763 case STLINK_SWD_DP_FAULT:
764 LOG_DEBUG("STLINK_SWD_DP_FAULT");
765 return ERROR_FAIL;
766 case STLINK_SWD_DP_ERROR:
767 LOG_DEBUG("STLINK_SWD_DP_ERROR");
768 return ERROR_FAIL;
769 case STLINK_SWD_DP_PARITY_ERROR:
770 LOG_DEBUG("STLINK_SWD_DP_PARITY_ERROR");
771 return ERROR_FAIL;
772 case STLINK_SWD_AP_WDATA_ERROR:
773 LOG_DEBUG("STLINK_SWD_AP_WDATA_ERROR");
774 return ERROR_FAIL;
775 case STLINK_SWD_AP_STICKY_ERROR:
776 LOG_DEBUG("STLINK_SWD_AP_STICKY_ERROR");
777 return ERROR_FAIL;
778 case STLINK_SWD_AP_STICKYORUN_ERROR:
779 LOG_DEBUG("STLINK_SWD_AP_STICKYORUN_ERROR");
780 return ERROR_FAIL;
781 case STLINK_BAD_AP_ERROR:
782 LOG_DEBUG("STLINK_BAD_AP_ERROR");
783 return ERROR_FAIL;
784 default:
785 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
786 return ERROR_FAIL;
787 }
788 }
789
790 /*
791 * Wrapper around stlink_usb_xfer_noerrcheck()
792 * to check the error code in the received packet
793 */
794 static int stlink_usb_xfer_errcheck(void *handle, const uint8_t *buf, int size)
795 {
796 int retval;
797
798 assert(size > 0);
799
800 retval = stlink_usb_xfer_noerrcheck(handle, buf, size);
801 if (retval != ERROR_OK)
802 return retval;
803
804 return stlink_usb_error_check(handle);
805 }
806
807 /** Issue an STLINK command via USB transfer, with retries on any wait status responses.
808
809 Works for commands where the STLINK_DEBUG status is returned in the first
810 byte of the response packet. For SWIM a SWIM_READSTATUS is requested instead.
811
812 Returns an openocd result code.
813 */
814 static int stlink_cmd_allow_retry(void *handle, const uint8_t *buf, int size)
815 {
816 int retries = 0;
817 int res;
818 struct stlink_usb_handle_s *h = handle;
819
820 while (1) {
821 if ((h->transport != HL_TRANSPORT_SWIM) || !retries) {
822 res = stlink_usb_xfer_noerrcheck(handle, buf, size);
823 if (res != ERROR_OK)
824 return res;
825 }
826
827 if (h->transport == HL_TRANSPORT_SWIM) {
828 res = stlink_swim_status(handle);
829 if (res != ERROR_OK)
830 return res;
831 }
832
833 res = stlink_usb_error_check(handle);
834 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
835 useconds_t delay_us = (1<<retries++) * 1000;
836 LOG_DEBUG("stlink_cmd_allow_retry ERROR_WAIT, retry %d, delaying %u microseconds", retries, delay_us);
837 usleep(delay_us);
838 continue;
839 }
840 return res;
841 }
842 }
843
844 /** */
845 static int stlink_usb_read_trace(void *handle, const uint8_t *buf, int size)
846 {
847 struct stlink_usb_handle_s *h = handle;
848 int tr, ret;
849
850 assert(handle != NULL);
851
852 assert(h->version.flags & STLINK_F_HAS_TRACE);
853
854 ret = jtag_libusb_bulk_read(h->fd, h->trace_ep, (char *)buf, size,
855 STLINK_READ_TIMEOUT, &tr);
856 if (ret || tr != size) {
857 LOG_ERROR("bulk trace read failed");
858 return ERROR_FAIL;
859 }
860
861 return ERROR_OK;
862 }
863
864 /*
865 this function writes transfer length in
866 the right place in the cb
867 */
868 static void stlink_usb_set_cbw_transfer_datalength(void *handle, uint32_t size)
869 {
870 struct stlink_usb_handle_s *h = handle;
871
872 buf_set_u32(h->cmdbuf+8, 0, 32, size);
873 }
874
875 static void stlink_usb_xfer_v1_create_cmd(void *handle, uint8_t direction, uint32_t size)
876 {
877 struct stlink_usb_handle_s *h = handle;
878
879 /* fill the send buffer */
880 strcpy((char *)h->cmdbuf, "USBC");
881 h->cmdidx += 4;
882 /* csw tag not used */
883 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, 0);
884 h->cmdidx += 4;
885 /* cbw data transfer length (in the following data phase in or out) */
886 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, size);
887 h->cmdidx += 4;
888 /* cbw flags */
889 h->cmdbuf[h->cmdidx++] = (direction == h->rx_ep ? ENDPOINT_IN : ENDPOINT_OUT);
890 h->cmdbuf[h->cmdidx++] = 0; /* lun */
891 /* cdb clength (is filled in at xfer) */
892 h->cmdbuf[h->cmdidx++] = 0;
893 }
894
895 /** */
896 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size)
897 {
898 struct stlink_usb_handle_s *h = handle;
899
900 h->direction = direction;
901
902 h->cmdidx = 0;
903
904 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
905 memset(h->databuf, 0, STLINK_DATA_SIZE);
906
907 if (h->version.stlink == 1)
908 stlink_usb_xfer_v1_create_cmd(handle, direction, size);
909 }
910
911 /** */
912 static int stlink_usb_version(void *handle)
913 {
914 int res;
915 uint32_t flags;
916 uint16_t version;
917 uint8_t v, x, y, jtag, swim, msd, bridge = 0;
918 char v_str[5 * (1 + 3) + 1]; /* VvJjMmBbSs */
919 char *p;
920 struct stlink_usb_handle_s *h = handle;
921
922 assert(handle != NULL);
923
924 stlink_usb_init_buffer(handle, h->rx_ep, 6);
925
926 h->cmdbuf[h->cmdidx++] = STLINK_GET_VERSION;
927
928 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 6);
929
930 if (res != ERROR_OK)
931 return res;
932
933 version = be_to_h_u16(h->databuf);
934 v = (version >> 12) & 0x0f;
935 x = (version >> 6) & 0x3f;
936 y = version & 0x3f;
937
938 h->vid = le_to_h_u16(h->databuf + 2);
939 h->pid = le_to_h_u16(h->databuf + 4);
940
941 switch (h->pid) {
942 case STLINK_V2_1_PID:
943 case STLINK_V2_1_NO_MSD_PID:
944 if ((x <= 22 && y == 7) || (x >= 25 && y >= 7 && y <= 12)) {
945 /* MxSy : STM8 V2.1 - SWIM only */
946 msd = x;
947 swim = y;
948 jtag = 0;
949 } else {
950 /* JxMy : STM32 V2.1 - JTAG/SWD only */
951 jtag = x;
952 msd = y;
953 swim = 0;
954 }
955 break;
956 default:
957 jtag = x;
958 swim = y;
959 msd = 0;
960 break;
961 }
962
963 /* STLINK-V3 requires a specific command */
964 if (v == 3 && x == 0 && y == 0) {
965 stlink_usb_init_buffer(handle, h->rx_ep, 16);
966
967 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_VERSION_EX;
968
969 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 12);
970 if (res != ERROR_OK)
971 return res;
972
973 v = h->databuf[0];
974 swim = h->databuf[1];
975 jtag = h->databuf[2];
976 msd = h->databuf[3];
977 bridge = h->databuf[4];
978 h->vid = le_to_h_u16(h->databuf + 8);
979 h->pid = le_to_h_u16(h->databuf + 10);
980 }
981
982 h->version.stlink = v;
983 h->version.jtag = jtag;
984 h->version.swim = swim;
985
986 flags = 0;
987 switch (h->version.stlink) {
988 case 1:
989 /* ST-LINK/V1 from J11 switch to api-v2 (and support SWD) */
990 if (h->version.jtag >= 11)
991 h->version.jtag_api = STLINK_JTAG_API_V2;
992 else
993 h->version.jtag_api = STLINK_JTAG_API_V1;
994
995 break;
996 case 2:
997 /* all ST-LINK/V2 and ST-Link/V2.1 use api-v2 */
998 h->version.jtag_api = STLINK_JTAG_API_V2;
999
1000 /* API for trace from J13 */
1001 /* API for target voltage from J13 */
1002 if (h->version.jtag >= 13)
1003 flags |= STLINK_F_HAS_TRACE;
1004
1005 /* preferred API to get last R/W status from J15 */
1006 if (h->version.jtag >= 15)
1007 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1008
1009 /* API to set SWD frequency from J22 */
1010 if (h->version.jtag >= 22)
1011 flags |= STLINK_F_HAS_SWD_SET_FREQ;
1012
1013 /* API to set JTAG frequency from J24 */
1014 /* API to access DAP registers from J24 */
1015 if (h->version.jtag >= 24) {
1016 flags |= STLINK_F_HAS_JTAG_SET_FREQ;
1017 flags |= STLINK_F_HAS_DAP_REG;
1018 }
1019
1020 /* Quirk for read DP in JTAG mode (V2 only) from J24, fixed in J32 */
1021 if (h->version.jtag >= 24 && h->version.jtag < 32)
1022 flags |= STLINK_F_QUIRK_JTAG_DP_READ;
1023
1024 /* API to read/write memory at 16 bit from J26 */
1025 if (h->version.jtag >= 26)
1026 flags |= STLINK_F_HAS_MEM_16BIT;
1027
1028 /* API required to init AP before any AP access from J28 */
1029 if (h->version.jtag >= 28)
1030 flags |= STLINK_F_HAS_AP_INIT;
1031
1032 /* Banked regs (DPv1 & DPv2) support from V2J32 */
1033 if (h->version.jtag >= 32)
1034 flags |= STLINK_F_HAS_DPBANKSEL;
1035
1036 break;
1037 case 3:
1038 /* all STLINK-V3 use api-v3 */
1039 h->version.jtag_api = STLINK_JTAG_API_V3;
1040
1041 /* STLINK-V3 is a superset of ST-LINK/V2 */
1042
1043 /* API for trace */
1044 /* API for target voltage */
1045 flags |= STLINK_F_HAS_TRACE;
1046
1047 /* preferred API to get last R/W status */
1048 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1049
1050 /* API to access DAP registers */
1051 flags |= STLINK_F_HAS_DAP_REG;
1052
1053 /* API to read/write memory at 16 bit */
1054 flags |= STLINK_F_HAS_MEM_16BIT;
1055
1056 /* API required to init AP before any AP access */
1057 flags |= STLINK_F_HAS_AP_INIT;
1058
1059 /* Banked regs (DPv1 & DPv2) support from V3J2 */
1060 if (h->version.jtag >= 2)
1061 flags |= STLINK_F_HAS_DPBANKSEL;
1062
1063 break;
1064 default:
1065 break;
1066 }
1067 h->version.flags = flags;
1068
1069 p = v_str;
1070 p += sprintf(p, "V%d", v);
1071 if (jtag || !msd)
1072 p += sprintf(p, "J%d", jtag);
1073 if (msd)
1074 p += sprintf(p, "M%d", msd);
1075 if (bridge)
1076 p += sprintf(p, "B%d", bridge);
1077 if (swim || !msd)
1078 sprintf(p, "S%d", swim);
1079
1080 LOG_INFO("STLINK %s (API v%d) VID:PID %04X:%04X",
1081 v_str,
1082 h->version.jtag_api,
1083 h->vid,
1084 h->pid);
1085
1086 return ERROR_OK;
1087 }
1088
1089 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
1090 {
1091 struct stlink_usb_handle_s *h = handle;
1092 uint32_t adc_results[2];
1093
1094 /* no error message, simply quit with error */
1095 if (!(h->version.flags & STLINK_F_HAS_TARGET_VOLT))
1096 return ERROR_COMMAND_NOTFOUND;
1097
1098 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1099
1100 h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
1101
1102 int result = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1103
1104 if (result != ERROR_OK)
1105 return result;
1106
1107 /* convert result */
1108 adc_results[0] = le_to_h_u32(h->databuf);
1109 adc_results[1] = le_to_h_u32(h->databuf + 4);
1110
1111 *target_voltage = 0;
1112
1113 if (adc_results[0])
1114 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
1115
1116 LOG_INFO("Target voltage: %f", (double)*target_voltage);
1117
1118 return ERROR_OK;
1119 }
1120
1121 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
1122 {
1123 struct stlink_usb_handle_s *h = handle;
1124
1125 assert(handle != NULL);
1126
1127 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
1128 return ERROR_COMMAND_NOTFOUND;
1129
1130 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1131
1132 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1133 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
1134 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1135 h->cmdidx += 2;
1136
1137 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1138
1139 if (result != ERROR_OK)
1140 return result;
1141
1142 return ERROR_OK;
1143 }
1144
1145 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
1146 {
1147 struct stlink_usb_handle_s *h = handle;
1148
1149 assert(handle != NULL);
1150
1151 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
1152 return ERROR_COMMAND_NOTFOUND;
1153
1154 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1155
1156 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1157 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
1158 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1159 h->cmdidx += 2;
1160
1161 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1162
1163 if (result != ERROR_OK)
1164 return result;
1165
1166 return ERROR_OK;
1167 }
1168
1169 /** */
1170 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
1171 {
1172 int res;
1173 struct stlink_usb_handle_s *h = handle;
1174
1175 assert(handle != NULL);
1176
1177 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1178
1179 h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
1180
1181 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1182
1183 if (res != ERROR_OK)
1184 return res;
1185
1186 *mode = h->databuf[0];
1187
1188 return ERROR_OK;
1189 }
1190
1191 /** */
1192 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
1193 {
1194 int rx_size = 0;
1195 struct stlink_usb_handle_s *h = handle;
1196
1197 assert(handle != NULL);
1198
1199 /* on api V2 we are able the read the latest command
1200 * status
1201 * TODO: we need the test on api V1 too
1202 */
1203 if (h->version.jtag_api != STLINK_JTAG_API_V1)
1204 rx_size = 2;
1205
1206 stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
1207
1208 switch (type) {
1209 case STLINK_MODE_DEBUG_JTAG:
1210 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1211 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1212 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1213 else
1214 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1215 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG_NO_RESET;
1216 break;
1217 case STLINK_MODE_DEBUG_SWD:
1218 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1219 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1220 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1221 else
1222 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1223 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD_NO_RESET;
1224 break;
1225 case STLINK_MODE_DEBUG_SWIM:
1226 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1227 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
1228 /* no answer for this function... */
1229 rx_size = 0;
1230 break;
1231 case STLINK_MODE_DFU:
1232 case STLINK_MODE_MASS:
1233 default:
1234 return ERROR_FAIL;
1235 }
1236
1237 return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
1238 }
1239
1240 /** */
1241 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
1242 {
1243 int res;
1244 struct stlink_usb_handle_s *h = handle;
1245
1246 assert(handle != NULL);
1247
1248 stlink_usb_init_buffer(handle, STLINK_NULL_EP, 0);
1249
1250 switch (type) {
1251 case STLINK_MODE_DEBUG_JTAG:
1252 case STLINK_MODE_DEBUG_SWD:
1253 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1254 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
1255 break;
1256 case STLINK_MODE_DEBUG_SWIM:
1257 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1258 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
1259 break;
1260 case STLINK_MODE_DFU:
1261 h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
1262 h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
1263 break;
1264 case STLINK_MODE_MASS:
1265 default:
1266 return ERROR_FAIL;
1267 }
1268
1269 res = stlink_usb_xfer_noerrcheck(handle, 0, 0);
1270
1271 if (res != ERROR_OK)
1272 return res;
1273
1274 return ERROR_OK;
1275 }
1276
1277 static int stlink_usb_assert_srst(void *handle, int srst);
1278
1279 static enum stlink_mode stlink_get_mode(enum hl_transports t)
1280 {
1281 switch (t) {
1282 case HL_TRANSPORT_SWD:
1283 return STLINK_MODE_DEBUG_SWD;
1284 case HL_TRANSPORT_JTAG:
1285 return STLINK_MODE_DEBUG_JTAG;
1286 case HL_TRANSPORT_SWIM:
1287 return STLINK_MODE_DEBUG_SWIM;
1288 default:
1289 return STLINK_MODE_UNKNOWN;
1290 }
1291 }
1292
1293 /** */
1294 static int stlink_usb_init_mode(void *handle, bool connect_under_reset, int initial_interface_speed)
1295 {
1296 int res;
1297 uint8_t mode;
1298 enum stlink_mode emode;
1299 struct stlink_usb_handle_s *h = handle;
1300
1301 assert(handle != NULL);
1302
1303 res = stlink_usb_current_mode(handle, &mode);
1304
1305 if (res != ERROR_OK)
1306 return res;
1307
1308 LOG_DEBUG("MODE: 0x%02X", mode);
1309
1310 /* try to exit current mode */
1311 switch (mode) {
1312 case STLINK_DEV_DFU_MODE:
1313 emode = STLINK_MODE_DFU;
1314 break;
1315 case STLINK_DEV_DEBUG_MODE:
1316 emode = STLINK_MODE_DEBUG_SWD;
1317 break;
1318 case STLINK_DEV_SWIM_MODE:
1319 emode = STLINK_MODE_DEBUG_SWIM;
1320 break;
1321 case STLINK_DEV_BOOTLOADER_MODE:
1322 case STLINK_DEV_MASS_MODE:
1323 default:
1324 emode = STLINK_MODE_UNKNOWN;
1325 break;
1326 }
1327
1328 if (emode != STLINK_MODE_UNKNOWN) {
1329 res = stlink_usb_mode_leave(handle, emode);
1330
1331 if (res != ERROR_OK)
1332 return res;
1333 }
1334
1335 res = stlink_usb_current_mode(handle, &mode);
1336
1337 if (res != ERROR_OK)
1338 return res;
1339
1340 /* we check the target voltage here as an aid to debugging connection problems.
1341 * the stlink requires the target Vdd to be connected for reliable debugging.
1342 * this cmd is supported in all modes except DFU
1343 */
1344 if (mode != STLINK_DEV_DFU_MODE) {
1345
1346 float target_voltage;
1347
1348 /* check target voltage (if supported) */
1349 res = stlink_usb_check_voltage(h, &target_voltage);
1350
1351 if (res != ERROR_OK) {
1352 if (res != ERROR_COMMAND_NOTFOUND)
1353 LOG_ERROR("voltage check failed");
1354 /* attempt to continue as it is not a catastrophic failure */
1355 } else {
1356 /* check for a sensible target voltage, operating range is 1.65-5.5v
1357 * according to datasheet */
1358 if (target_voltage < 1.5)
1359 LOG_ERROR("target voltage may be too low for reliable debugging");
1360 }
1361 }
1362
1363 LOG_DEBUG("MODE: 0x%02X", mode);
1364
1365 /* set selected mode */
1366 emode = stlink_get_mode(h->transport);
1367
1368 if (emode == STLINK_MODE_UNKNOWN) {
1369 LOG_ERROR("selected mode (transport) not supported");
1370 return ERROR_FAIL;
1371 }
1372
1373 /* set the speed before entering the mode, as the chip discovery phase should be done at this speed too */
1374 if (h->transport == HL_TRANSPORT_JTAG) {
1375 if (h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ) {
1376 stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
1377 stlink_speed(h, initial_interface_speed, false);
1378 }
1379 } else if (h->transport == HL_TRANSPORT_SWD) {
1380 if (h->version.flags & STLINK_F_HAS_SWD_SET_FREQ) {
1381 stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
1382 stlink_speed(h, initial_interface_speed, false);
1383 }
1384 }
1385
1386 if (h->version.jtag_api == STLINK_JTAG_API_V3) {
1387 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
1388
1389 stlink_get_com_freq(h, (h->transport == HL_TRANSPORT_JTAG), map);
1390 stlink_dump_speed_map(map, ARRAY_SIZE(map));
1391 stlink_speed(h, initial_interface_speed, false);
1392 }
1393
1394 /* preliminary SRST assert:
1395 * We want SRST is asserted before activating debug signals (mode_enter).
1396 * As the required mode has not been set, the adapter may not know what pin to use.
1397 * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
1398 * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
1399 * after power on, SWIM_RST stays unchanged */
1400 if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
1401 stlink_usb_assert_srst(handle, 0);
1402 /* do not check the return status here, we will
1403 proceed and enter the desired mode below
1404 and try asserting srst again. */
1405
1406 res = stlink_usb_mode_enter(handle, emode);
1407 if (res != ERROR_OK)
1408 return res;
1409
1410 /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
1411 if (connect_under_reset) {
1412 res = stlink_usb_assert_srst(handle, 0);
1413 if (res != ERROR_OK)
1414 return res;
1415 }
1416
1417 res = stlink_usb_current_mode(handle, &mode);
1418
1419 if (res != ERROR_OK)
1420 return res;
1421
1422 LOG_DEBUG("MODE: 0x%02X", mode);
1423
1424 return ERROR_OK;
1425 }
1426
1427 /* request status from last swim request */
1428 static int stlink_swim_status(void *handle)
1429 {
1430 struct stlink_usb_handle_s *h = handle;
1431 int res;
1432
1433 stlink_usb_init_buffer(handle, h->rx_ep, 4);
1434 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1435 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
1436 /* error is checked by the caller */
1437 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1438 if (res != ERROR_OK)
1439 return res;
1440 return ERROR_OK;
1441 }
1442 /*
1443 the purpose of this function is unknown...
1444 capabilites? anyway for swim v6 it returns
1445 0001020600000000
1446 */
1447 __attribute__((unused))
1448 static int stlink_swim_cap(void *handle, uint8_t *cap)
1449 {
1450 struct stlink_usb_handle_s *h = handle;
1451 int res;
1452
1453 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1454 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1455 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1456 h->cmdbuf[h->cmdidx++] = 0x01;
1457 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1458 if (res != ERROR_OK)
1459 return res;
1460 memcpy(cap, h->databuf, 8);
1461 return ERROR_OK;
1462 }
1463
1464 /* debug dongle assert/deassert sreset line */
1465 static int stlink_swim_assert_reset(void *handle, int reset)
1466 {
1467 struct stlink_usb_handle_s *h = handle;
1468 int res;
1469
1470 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1471 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1472 if (!reset)
1473 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1474 else
1475 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1476 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1477 if (res != ERROR_OK)
1478 return res;
1479 return ERROR_OK;
1480 }
1481
1482 /*
1483 send swim enter seq
1484 1.3ms low then 750Hz then 1.5kHz
1485 */
1486 static int stlink_swim_enter(void *handle)
1487 {
1488 struct stlink_usb_handle_s *h = handle;
1489 int res;
1490
1491 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1492 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1493 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1494 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1495 if (res != ERROR_OK)
1496 return res;
1497 return ERROR_OK;
1498 }
1499
1500 /* switch high/low speed swim */
1501 static int stlink_swim_speed(void *handle, int speed)
1502 {
1503 struct stlink_usb_handle_s *h = handle;
1504 int res;
1505
1506 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1507 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1508 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1509 if (speed)
1510 h->cmdbuf[h->cmdidx++] = 1;
1511 else
1512 h->cmdbuf[h->cmdidx++] = 0;
1513 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1514 if (res != ERROR_OK)
1515 return res;
1516 return ERROR_OK;
1517 }
1518
1519 /*
1520 initiate srst from swim.
1521 nrst is pulled low for 50us.
1522 */
1523 static int stlink_swim_generate_rst(void *handle)
1524 {
1525 struct stlink_usb_handle_s *h = handle;
1526 int res;
1527
1528 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1529 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1530 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1531 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1532 if (res != ERROR_OK)
1533 return res;
1534 return ERROR_OK;
1535 }
1536
1537 /*
1538 send resyncronize sequence
1539 swim is pulled low for 16us
1540 reply is 64 clks low
1541 */
1542 static int stlink_swim_resync(void *handle)
1543 {
1544 struct stlink_usb_handle_s *h = handle;
1545 int res;
1546
1547 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1548 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1549 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_RESET;
1550 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1551 if (res != ERROR_OK)
1552 return res;
1553 return ERROR_OK;
1554 }
1555
1556 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1557 {
1558 struct stlink_usb_handle_s *h = handle;
1559 int res;
1560 unsigned int i;
1561 unsigned int datalen = 0;
1562 int cmdsize = STLINK_CMD_SIZE_V2;
1563
1564 if (len > STLINK_DATA_SIZE)
1565 return ERROR_FAIL;
1566
1567 if (h->version.stlink == 1)
1568 cmdsize = STLINK_SG_SIZE;
1569
1570 stlink_usb_init_buffer(handle, h->tx_ep, 0);
1571 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1572 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1573 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1574 h->cmdidx += 2;
1575 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1576 h->cmdidx += 4;
1577 for (i = 0; i < len; i++) {
1578 if (h->cmdidx == cmdsize)
1579 h->databuf[datalen++] = *(data++);
1580 else
1581 h->cmdbuf[h->cmdidx++] = *(data++);
1582 }
1583 if (h->version.stlink == 1)
1584 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1585
1586 res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1587 if (res != ERROR_OK)
1588 return res;
1589 return ERROR_OK;
1590 }
1591
1592 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1593 {
1594 struct stlink_usb_handle_s *h = handle;
1595 int res;
1596
1597 if (len > STLINK_DATA_SIZE)
1598 return ERROR_FAIL;
1599
1600 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1601 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1602 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1603 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1604 h->cmdidx += 2;
1605 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1606 h->cmdidx += 4;
1607 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1608 if (res != ERROR_OK)
1609 return res;
1610
1611 stlink_usb_init_buffer(handle, h->rx_ep, len);
1612 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1613 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1614 res = stlink_usb_xfer_noerrcheck(handle, data, len);
1615 if (res != ERROR_OK)
1616 return res;
1617
1618 return ERROR_OK;
1619 }
1620
1621 /** */
1622 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1623 {
1624 int res, offset;
1625 struct stlink_usb_handle_s *h = handle;
1626
1627 assert(handle != NULL);
1628
1629 /* there is no swim read core id cmd */
1630 if (h->transport == HL_TRANSPORT_SWIM) {
1631 *idcode = 0;
1632 return ERROR_OK;
1633 }
1634
1635 stlink_usb_init_buffer(handle, h->rx_ep, 12);
1636
1637 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1638 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1639 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1640
1641 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1642 offset = 0;
1643 } else {
1644 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_IDCODES;
1645
1646 res = stlink_usb_xfer_errcheck(handle, h->databuf, 12);
1647 offset = 4;
1648 }
1649
1650 if (res != ERROR_OK)
1651 return res;
1652
1653 *idcode = le_to_h_u32(h->databuf + offset);
1654
1655 LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1656
1657 return ERROR_OK;
1658 }
1659
1660 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1661 {
1662 struct stlink_usb_handle_s *h = handle;
1663 int res;
1664
1665 assert(handle != NULL);
1666
1667 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1668
1669 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1670 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1671 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1672 h->cmdidx += 4;
1673
1674 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1675 if (res != ERROR_OK)
1676 return res;
1677
1678 *val = le_to_h_u32(h->databuf + 4);
1679 return ERROR_OK;
1680 }
1681
1682 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1683 {
1684 struct stlink_usb_handle_s *h = handle;
1685
1686 assert(handle != NULL);
1687
1688 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1689
1690 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1691 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1692 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1693 else
1694 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1695 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1696 h->cmdidx += 4;
1697 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1698 h->cmdidx += 4;
1699
1700 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1701 }
1702
1703 /** */
1704 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1705 {
1706 struct stlink_usb_handle_s *h = handle;
1707
1708 assert(handle != NULL);
1709
1710 if (h->trace.enabled && (h->version.flags & STLINK_F_HAS_TRACE)) {
1711 int res;
1712
1713 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1714
1715 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1716 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1717
1718 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1719 if (res != ERROR_OK)
1720 return res;
1721
1722 size_t bytes_avail = le_to_h_u16(h->databuf);
1723 *size = bytes_avail < *size ? bytes_avail : *size - 1;
1724
1725 if (*size > 0) {
1726 res = stlink_usb_read_trace(handle, buf, *size);
1727 if (res != ERROR_OK)
1728 return res;
1729 return ERROR_OK;
1730 }
1731 }
1732 *size = 0;
1733 return ERROR_OK;
1734 }
1735
1736 static enum target_state stlink_usb_v2_get_status(void *handle)
1737 {
1738 int result;
1739 uint32_t status;
1740
1741 result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1742 if (result != ERROR_OK)
1743 return TARGET_UNKNOWN;
1744
1745 if (status & S_HALT)
1746 return TARGET_HALTED;
1747 else if (status & S_RESET_ST)
1748 return TARGET_RESET;
1749
1750 return TARGET_RUNNING;
1751 }
1752
1753 /** */
1754 static enum target_state stlink_usb_state(void *handle)
1755 {
1756 int res;
1757 struct stlink_usb_handle_s *h = handle;
1758
1759 assert(handle != NULL);
1760
1761 if (h->transport == HL_TRANSPORT_SWIM) {
1762 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1763 if (res != ERROR_OK)
1764 return TARGET_UNKNOWN;
1765
1766 res = stlink_swim_resync(handle);
1767 if (res != ERROR_OK)
1768 return TARGET_UNKNOWN;
1769
1770 return ERROR_OK;
1771 }
1772
1773 if (h->reconnect_pending) {
1774 LOG_INFO("Previous state query failed, trying to reconnect");
1775 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1776
1777 if (res != ERROR_OK)
1778 return TARGET_UNKNOWN;
1779
1780 h->reconnect_pending = false;
1781 }
1782
1783 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1784 res = stlink_usb_v2_get_status(handle);
1785 if (res == TARGET_UNKNOWN)
1786 h->reconnect_pending = true;
1787 return res;
1788 }
1789
1790 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1791
1792 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1793 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
1794
1795 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1796
1797 if (res != ERROR_OK)
1798 return TARGET_UNKNOWN;
1799
1800 if (h->databuf[0] == STLINK_CORE_RUNNING)
1801 return TARGET_RUNNING;
1802 if (h->databuf[0] == STLINK_CORE_HALTED)
1803 return TARGET_HALTED;
1804
1805 h->reconnect_pending = true;
1806
1807 return TARGET_UNKNOWN;
1808 }
1809
1810 static int stlink_usb_assert_srst(void *handle, int srst)
1811 {
1812 struct stlink_usb_handle_s *h = handle;
1813
1814 assert(handle != NULL);
1815
1816 if (h->transport == HL_TRANSPORT_SWIM)
1817 return stlink_swim_assert_reset(handle, srst);
1818
1819 if (h->version.stlink == 1)
1820 return ERROR_COMMAND_NOTFOUND;
1821
1822 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1823
1824 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1825 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
1826 h->cmdbuf[h->cmdidx++] = srst;
1827
1828 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1829 }
1830
1831 /** */
1832 static void stlink_usb_trace_disable(void *handle)
1833 {
1834 int res = ERROR_OK;
1835 struct stlink_usb_handle_s *h = handle;
1836
1837 assert(handle != NULL);
1838
1839 assert(h->version.flags & STLINK_F_HAS_TRACE);
1840
1841 LOG_DEBUG("Tracing: disable");
1842
1843 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1844 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1845 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
1846 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1847
1848 if (res == ERROR_OK)
1849 h->trace.enabled = false;
1850 }
1851
1852
1853 /** */
1854 static int stlink_usb_trace_enable(void *handle)
1855 {
1856 int res;
1857 struct stlink_usb_handle_s *h = handle;
1858
1859 assert(handle != NULL);
1860
1861 if (h->version.flags & STLINK_F_HAS_TRACE) {
1862 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1863
1864 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1865 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
1866 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
1867 h->cmdidx += 2;
1868 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
1869 h->cmdidx += 4;
1870
1871 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1872
1873 if (res == ERROR_OK) {
1874 h->trace.enabled = true;
1875 LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
1876 }
1877 } else {
1878 LOG_ERROR("Tracing is not supported by this version.");
1879 res = ERROR_FAIL;
1880 }
1881
1882 return res;
1883 }
1884
1885 /** */
1886 static int stlink_usb_reset(void *handle)
1887 {
1888 struct stlink_usb_handle_s *h = handle;
1889 int retval;
1890
1891 assert(handle != NULL);
1892
1893 if (h->transport == HL_TRANSPORT_SWIM)
1894 return stlink_swim_generate_rst(handle);
1895
1896 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1897
1898 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1899
1900 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1901 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
1902 else
1903 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
1904
1905 retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
1906 if (retval != ERROR_OK)
1907 return retval;
1908
1909 if (h->trace.enabled) {
1910 stlink_usb_trace_disable(h);
1911 return stlink_usb_trace_enable(h);
1912 }
1913
1914 return ERROR_OK;
1915 }
1916
1917 /** */
1918 static int stlink_usb_run(void *handle)
1919 {
1920 int res;
1921 struct stlink_usb_handle_s *h = handle;
1922
1923 assert(handle != NULL);
1924
1925 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1926 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
1927
1928 return res;
1929 }
1930
1931 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1932
1933 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1934 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
1935
1936 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1937 }
1938
1939 /** */
1940 static int stlink_usb_halt(void *handle)
1941 {
1942 int res;
1943 struct stlink_usb_handle_s *h = handle;
1944
1945 assert(handle != NULL);
1946
1947 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1948 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1949
1950 return res;
1951 }
1952
1953 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1954
1955 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1956 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
1957
1958 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1959 }
1960
1961 /** */
1962 static int stlink_usb_step(void *handle)
1963 {
1964 struct stlink_usb_handle_s *h = handle;
1965
1966 assert(handle != NULL);
1967
1968 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1969 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
1970 * that the Cortex-M3 currently does. */
1971 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
1972 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
1973 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1974 }
1975
1976 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1977
1978 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1979 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
1980
1981 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1982 }
1983
1984 /** */
1985 static int stlink_usb_read_regs(void *handle)
1986 {
1987 int res;
1988 struct stlink_usb_handle_s *h = handle;
1989
1990 assert(handle != NULL);
1991
1992 stlink_usb_init_buffer(handle, h->rx_ep, 88);
1993
1994 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1995 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1996
1997 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
1998 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 84);
1999 /* regs data from offset 0 */
2000 } else {
2001 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
2002 res = stlink_usb_xfer_errcheck(handle, h->databuf, 88);
2003 /* status at offset 0, regs data from offset 4 */
2004 }
2005
2006 return res;
2007 }
2008
2009 /** */
2010 static int stlink_usb_read_reg(void *handle, int num, uint32_t *val)
2011 {
2012 int res;
2013 struct stlink_usb_handle_s *h = handle;
2014
2015 assert(handle != NULL);
2016
2017 stlink_usb_init_buffer(handle, h->rx_ep, h->version.jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
2018
2019 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2020 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2021 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
2022 else
2023 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
2024 h->cmdbuf[h->cmdidx++] = num;
2025
2026 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2027 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
2028 if (res != ERROR_OK)
2029 return res;
2030 *val = le_to_h_u32(h->databuf);
2031 return ERROR_OK;
2032 } else {
2033 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
2034 if (res != ERROR_OK)
2035 return res;
2036 *val = le_to_h_u32(h->databuf + 4);
2037 return ERROR_OK;
2038 }
2039 }
2040
2041 /** */
2042 static int stlink_usb_write_reg(void *handle, int num, uint32_t val)
2043 {
2044 struct stlink_usb_handle_s *h = handle;
2045
2046 assert(handle != NULL);
2047
2048 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2049
2050 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2051 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2052 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
2053 else
2054 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
2055 h->cmdbuf[h->cmdidx++] = num;
2056 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
2057 h->cmdidx += 4;
2058
2059 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2060 }
2061
2062 static int stlink_usb_get_rw_status(void *handle)
2063 {
2064 struct stlink_usb_handle_s *h = handle;
2065
2066 assert(handle != NULL);
2067
2068 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2069 return ERROR_OK;
2070
2071 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2072
2073 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2074 if (h->version.flags & STLINK_F_HAS_GETLASTRWSTATUS2) {
2075 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS2;
2076 return stlink_usb_xfer_errcheck(handle, h->databuf, 12);
2077 } else {
2078 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
2079 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2080 }
2081 }
2082
2083 /** */
2084 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
2085 uint8_t *buffer)
2086 {
2087 int res;
2088 uint16_t read_len = len;
2089 struct stlink_usb_handle_s *h = handle;
2090
2091 assert(handle != NULL);
2092
2093 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2094 if (len > stlink_usb_block(h)) {
2095 LOG_DEBUG("max buffer (%d) length exceeded", stlink_usb_block(h));
2096 return ERROR_FAIL;
2097 }
2098
2099 stlink_usb_init_buffer(handle, h->rx_ep, read_len);
2100
2101 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2102 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
2103 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2104 h->cmdidx += 4;
2105 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2106 h->cmdidx += 2;
2107
2108 /* we need to fix read length for single bytes */
2109 if (read_len == 1)
2110 read_len++;
2111
2112 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, read_len);
2113
2114 if (res != ERROR_OK)
2115 return res;
2116
2117 memcpy(buffer, h->databuf, len);
2118
2119 return stlink_usb_get_rw_status(handle);
2120 }
2121
2122 /** */
2123 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
2124 const uint8_t *buffer)
2125 {
2126 int res;
2127 struct stlink_usb_handle_s *h = handle;
2128
2129 assert(handle != NULL);
2130
2131 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2132 if (len > stlink_usb_block(h)) {
2133 LOG_DEBUG("max buffer length (%d) exceeded", stlink_usb_block(h));
2134 return ERROR_FAIL;
2135 }
2136
2137 stlink_usb_init_buffer(handle, h->tx_ep, len);
2138
2139 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2140 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
2141 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2142 h->cmdidx += 4;
2143 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2144 h->cmdidx += 2;
2145
2146 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2147
2148 if (res != ERROR_OK)
2149 return res;
2150
2151 return stlink_usb_get_rw_status(handle);
2152 }
2153
2154 /** */
2155 static int stlink_usb_read_mem16(void *handle, uint32_t addr, uint16_t len,
2156 uint8_t *buffer)
2157 {
2158 int res;
2159 struct stlink_usb_handle_s *h = handle;
2160
2161 assert(handle != NULL);
2162
2163 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2164 return ERROR_COMMAND_NOTFOUND;
2165
2166 /* data must be a multiple of 2 and half-word aligned */
2167 if (len % 2 || addr % 2) {
2168 LOG_DEBUG("Invalid data alignment");
2169 return ERROR_TARGET_UNALIGNED_ACCESS;
2170 }
2171
2172 stlink_usb_init_buffer(handle, h->rx_ep, len);
2173
2174 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2175 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READMEM_16BIT;
2176 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2177 h->cmdidx += 4;
2178 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2179 h->cmdidx += 2;
2180
2181 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2182
2183 if (res != ERROR_OK)
2184 return res;
2185
2186 memcpy(buffer, h->databuf, len);
2187
2188 return stlink_usb_get_rw_status(handle);
2189 }
2190
2191 /** */
2192 static int stlink_usb_write_mem16(void *handle, uint32_t addr, uint16_t len,
2193 const uint8_t *buffer)
2194 {
2195 int res;
2196 struct stlink_usb_handle_s *h = handle;
2197
2198 assert(handle != NULL);
2199
2200 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2201 return ERROR_COMMAND_NOTFOUND;
2202
2203 /* data must be a multiple of 2 and half-word aligned */
2204 if (len % 2 || addr % 2) {
2205 LOG_DEBUG("Invalid data alignment");
2206 return ERROR_TARGET_UNALIGNED_ACCESS;
2207 }
2208
2209 stlink_usb_init_buffer(handle, h->tx_ep, len);
2210
2211 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2212 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEMEM_16BIT;
2213 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2214 h->cmdidx += 4;
2215 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2216 h->cmdidx += 2;
2217
2218 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2219
2220 if (res != ERROR_OK)
2221 return res;
2222
2223 return stlink_usb_get_rw_status(handle);
2224 }
2225
2226 /** */
2227 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
2228 uint8_t *buffer)
2229 {
2230 int res;
2231 struct stlink_usb_handle_s *h = handle;
2232
2233 assert(handle != NULL);
2234
2235 /* data must be a multiple of 4 and word aligned */
2236 if (len % 4 || addr % 4) {
2237 LOG_DEBUG("Invalid data alignment");
2238 return ERROR_TARGET_UNALIGNED_ACCESS;
2239 }
2240
2241 stlink_usb_init_buffer(handle, h->rx_ep, len);
2242
2243 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2244 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
2245 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2246 h->cmdidx += 4;
2247 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2248 h->cmdidx += 2;
2249
2250 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2251
2252 if (res != ERROR_OK)
2253 return res;
2254
2255 memcpy(buffer, h->databuf, len);
2256
2257 return stlink_usb_get_rw_status(handle);
2258 }
2259
2260 /** */
2261 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
2262 const uint8_t *buffer)
2263 {
2264 int res;
2265 struct stlink_usb_handle_s *h = handle;
2266
2267 assert(handle != NULL);
2268
2269 /* data must be a multiple of 4 and word aligned */
2270 if (len % 4 || addr % 4) {
2271 LOG_DEBUG("Invalid data alignment");
2272 return ERROR_TARGET_UNALIGNED_ACCESS;
2273 }
2274
2275 stlink_usb_init_buffer(handle, h->tx_ep, len);
2276
2277 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2278 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
2279 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2280 h->cmdidx += 4;
2281 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2282 h->cmdidx += 2;
2283
2284 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2285
2286 if (res != ERROR_OK)
2287 return res;
2288
2289 return stlink_usb_get_rw_status(handle);
2290 }
2291
2292 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
2293 {
2294 uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
2295 if (max_tar_block == 0)
2296 max_tar_block = 4;
2297 return max_tar_block;
2298 }
2299
2300 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
2301 uint32_t count, uint8_t *buffer)
2302 {
2303 int retval = ERROR_OK;
2304 uint32_t bytes_remaining;
2305 int retries = 0;
2306 struct stlink_usb_handle_s *h = handle;
2307
2308 /* calculate byte count */
2309 count *= size;
2310
2311 /* switch to 8 bit if stlink does not support 16 bit memory read */
2312 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2313 size = 1;
2314
2315 while (count) {
2316
2317 bytes_remaining = (size != 1) ? \
2318 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2319
2320 if (count < bytes_remaining)
2321 bytes_remaining = count;
2322
2323 if (h->transport == HL_TRANSPORT_SWIM) {
2324 retval = stlink_swim_readbytes(handle, addr, bytes_remaining, buffer);
2325 if (retval != ERROR_OK)
2326 return retval;
2327 } else
2328 /*
2329 * all stlink support 8/32bit memory read/writes and only from
2330 * stlink V2J26 there is support for 16 bit memory read/write.
2331 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2332 * as 8bit access.
2333 */
2334 if (size != 1) {
2335
2336 /* When in jtag mode the stlink uses the auto-increment functionality.
2337 * However it expects us to pass the data correctly, this includes
2338 * alignment and any page boundaries. We already do this as part of the
2339 * adi_v5 implementation, but the stlink is a hla adapter and so this
2340 * needs implementing manually.
2341 * currently this only affects jtag mode, according to ST they do single
2342 * access in SWD mode - but this may change and so we do it for both modes */
2343
2344 /* we first need to check for any unaligned bytes */
2345 if (addr & (size - 1)) {
2346
2347 uint32_t head_bytes = size - (addr & (size - 1));
2348 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
2349 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2350 usleep((1<<retries++) * 1000);
2351 continue;
2352 }
2353 if (retval != ERROR_OK)
2354 return retval;
2355 buffer += head_bytes;
2356 addr += head_bytes;
2357 count -= head_bytes;
2358 bytes_remaining -= head_bytes;
2359 }
2360
2361 if (bytes_remaining & (size - 1))
2362 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
2363 else if (size == 2)
2364 retval = stlink_usb_read_mem16(handle, addr, bytes_remaining, buffer);
2365 else
2366 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
2367 } else
2368 retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
2369
2370 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2371 usleep((1<<retries++) * 1000);
2372 continue;
2373 }
2374 if (retval != ERROR_OK)
2375 return retval;
2376
2377 buffer += bytes_remaining;
2378 addr += bytes_remaining;
2379 count -= bytes_remaining;
2380 }
2381
2382 return retval;
2383 }
2384
2385 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
2386 uint32_t count, const uint8_t *buffer)
2387 {
2388 int retval = ERROR_OK;
2389 uint32_t bytes_remaining;
2390 int retries = 0;
2391 struct stlink_usb_handle_s *h = handle;
2392
2393 /* calculate byte count */
2394 count *= size;
2395
2396 /* switch to 8 bit if stlink does not support 16 bit memory read */
2397 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2398 size = 1;
2399
2400 while (count) {
2401
2402 bytes_remaining = (size != 1) ? \
2403 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2404
2405 if (count < bytes_remaining)
2406 bytes_remaining = count;
2407
2408 if (h->transport == HL_TRANSPORT_SWIM) {
2409 retval = stlink_swim_writebytes(handle, addr, bytes_remaining, buffer);
2410 if (retval != ERROR_OK)
2411 return retval;
2412 } else
2413 /*
2414 * all stlink support 8/32bit memory read/writes and only from
2415 * stlink V2J26 there is support for 16 bit memory read/write.
2416 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2417 * as 8bit access.
2418 */
2419 if (size != 1) {
2420
2421 /* When in jtag mode the stlink uses the auto-increment functionality.
2422 * However it expects us to pass the data correctly, this includes
2423 * alignment and any page boundaries. We already do this as part of the
2424 * adi_v5 implementation, but the stlink is a hla adapter and so this
2425 * needs implementing manually.
2426 * currently this only affects jtag mode, according to ST they do single
2427 * access in SWD mode - but this may change and so we do it for both modes */
2428
2429 /* we first need to check for any unaligned bytes */
2430 if (addr & (size - 1)) {
2431
2432 uint32_t head_bytes = size - (addr & (size - 1));
2433 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
2434 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2435 usleep((1<<retries++) * 1000);
2436 continue;
2437 }
2438 if (retval != ERROR_OK)
2439 return retval;
2440 buffer += head_bytes;
2441 addr += head_bytes;
2442 count -= head_bytes;
2443 bytes_remaining -= head_bytes;
2444 }
2445
2446 if (bytes_remaining & (size - 1))
2447 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
2448 else if (size == 2)
2449 retval = stlink_usb_write_mem16(handle, addr, bytes_remaining, buffer);
2450 else
2451 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
2452
2453 } else
2454 retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
2455 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2456 usleep((1<<retries++) * 1000);
2457 continue;
2458 }
2459 if (retval != ERROR_OK)
2460 return retval;
2461
2462 buffer += bytes_remaining;
2463 addr += bytes_remaining;
2464 count -= bytes_remaining;
2465 }
2466
2467 return retval;
2468 }
2469
2470 /** */
2471 static int stlink_usb_override_target(const char *targetname)
2472 {
2473 return !strcmp(targetname, "cortex_m");
2474 }
2475
2476 static int stlink_speed_swim(void *handle, int khz, bool query)
2477 {
2478 /*
2479 we dont care what the khz rate is
2480 we only have low and high speed...
2481 before changing speed the SWIM_CSR HS bit
2482 must be updated
2483 */
2484 if (khz == 0)
2485 stlink_swim_speed(handle, 0);
2486 else
2487 stlink_swim_speed(handle, 1);
2488 return khz;
2489 }
2490
2491 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
2492 {
2493 unsigned int i;
2494 int speed_index = -1;
2495 int speed_diff = INT_MAX;
2496 int last_valid_speed = -1;
2497 bool match = true;
2498
2499 for (i = 0; i < map_size; i++) {
2500 if (!map[i].speed)
2501 continue;
2502 last_valid_speed = i;
2503 if (khz == map[i].speed) {
2504 speed_index = i;
2505 break;
2506 } else {
2507 int current_diff = khz - map[i].speed;
2508 /* get abs value for comparison */
2509 current_diff = (current_diff > 0) ? current_diff : -current_diff;
2510 if ((current_diff < speed_diff) && khz >= map[i].speed) {
2511 speed_diff = current_diff;
2512 speed_index = i;
2513 }
2514 }
2515 }
2516
2517 if (speed_index == -1) {
2518 /* this will only be here if we cannot match the slow speed.
2519 * use the slowest speed we support.*/
2520 speed_index = last_valid_speed;
2521 match = false;
2522 } else if (i == map_size)
2523 match = false;
2524
2525 if (!match && query) {
2526 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz", \
2527 khz, map[speed_index].speed);
2528 }
2529
2530 return speed_index;
2531 }
2532
2533 static int stlink_speed_swd(void *handle, int khz, bool query)
2534 {
2535 int speed_index;
2536 struct stlink_usb_handle_s *h = handle;
2537
2538 /* old firmware cannot change it */
2539 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
2540 return khz;
2541
2542 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
2543 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
2544
2545 if (!query) {
2546 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
2547 if (result != ERROR_OK) {
2548 LOG_ERROR("Unable to set adapter speed");
2549 return khz;
2550 }
2551 }
2552
2553 return stlink_khz_to_speed_map_swd[speed_index].speed;
2554 }
2555
2556 static int stlink_speed_jtag(void *handle, int khz, bool query)
2557 {
2558 int speed_index;
2559 struct stlink_usb_handle_s *h = handle;
2560
2561 /* old firmware cannot change it */
2562 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
2563 return khz;
2564
2565 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2566 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2567
2568 if (!query) {
2569 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2570 if (result != ERROR_OK) {
2571 LOG_ERROR("Unable to set adapter speed");
2572 return khz;
2573 }
2574 }
2575
2576 return stlink_khz_to_speed_map_jtag[speed_index].speed;
2577 }
2578
2579 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2580 {
2581 unsigned int i;
2582
2583 LOG_DEBUG("Supported clock speeds are:");
2584 for (i = 0; i < map_size; i++)
2585 if (map[i].speed)
2586 LOG_DEBUG("%d kHz", map[i].speed);
2587 }
2588
2589 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map)
2590 {
2591 struct stlink_usb_handle_s *h = handle;
2592 int i;
2593
2594 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2595 LOG_ERROR("Unknown command");
2596 return 0;
2597 }
2598
2599 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2600
2601 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2602 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_COM_FREQ;
2603 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2604
2605 int res = stlink_usb_xfer_errcheck(handle, h->databuf, 52);
2606
2607 int size = h->databuf[8];
2608
2609 if (size > STLINK_V3_MAX_FREQ_NB)
2610 size = STLINK_V3_MAX_FREQ_NB;
2611
2612 for (i = 0; i < size; i++) {
2613 map[i].speed = le_to_h_u32(&h->databuf[12 + 4 * i]);
2614 map[i].speed_divisor = i;
2615 }
2616
2617 /* set to zero all the next entries */
2618 for (i = size; i < STLINK_V3_MAX_FREQ_NB; i++)
2619 map[i].speed = 0;
2620
2621 return res;
2622 }
2623
2624 static int stlink_set_com_freq(void *handle, bool is_jtag, unsigned int frequency)
2625 {
2626 struct stlink_usb_handle_s *h = handle;
2627
2628 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2629 LOG_ERROR("Unknown command");
2630 return 0;
2631 }
2632
2633 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2634
2635 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2636 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_SET_COM_FREQ;
2637 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2638 h->cmdbuf[h->cmdidx++] = 0;
2639
2640 h_u32_to_le(&h->cmdbuf[4], frequency);
2641
2642 return stlink_usb_xfer_errcheck(handle, h->databuf, 8);
2643 }
2644
2645 static int stlink_speed_v3(void *handle, bool is_jtag, int khz, bool query)
2646 {
2647 struct stlink_usb_handle_s *h = handle;
2648 int speed_index;
2649 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
2650
2651 stlink_get_com_freq(h, is_jtag, map);
2652
2653 speed_index = stlink_match_speed_map(map, ARRAY_SIZE(map), khz, query);
2654
2655 if (!query) {
2656 int result = stlink_set_com_freq(h, is_jtag, map[speed_index].speed);
2657 if (result != ERROR_OK) {
2658 LOG_ERROR("Unable to set adapter speed");
2659 return khz;
2660 }
2661 }
2662 return map[speed_index].speed;
2663 }
2664
2665 static int stlink_speed(void *handle, int khz, bool query)
2666 {
2667 struct stlink_usb_handle_s *h = handle;
2668
2669 if (!handle)
2670 return khz;
2671
2672 switch (h->transport) {
2673 case HL_TRANSPORT_SWIM:
2674 return stlink_speed_swim(handle, khz, query);
2675 break;
2676 case HL_TRANSPORT_SWD:
2677 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2678 return stlink_speed_v3(handle, false, khz, query);
2679 else
2680 return stlink_speed_swd(handle, khz, query);
2681 break;
2682 case HL_TRANSPORT_JTAG:
2683 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2684 return stlink_speed_v3(handle, true, khz, query);
2685 else
2686 return stlink_speed_jtag(handle, khz, query);
2687 break;
2688 default:
2689 break;
2690 }
2691
2692 return khz;
2693 }
2694
2695 /** */
2696 static int stlink_usb_close(void *handle)
2697 {
2698 int res;
2699 uint8_t mode;
2700 enum stlink_mode emode;
2701 struct stlink_usb_handle_s *h = handle;
2702
2703 if (h && h->fd)
2704 res = stlink_usb_current_mode(handle, &mode);
2705 else
2706 res = ERROR_FAIL;
2707 /* do not exit if return code != ERROR_OK,
2708 it prevents us from closing jtag_libusb */
2709
2710 if (res == ERROR_OK) {
2711 /* try to exit current mode */
2712 switch (mode) {
2713 case STLINK_DEV_DFU_MODE:
2714 emode = STLINK_MODE_DFU;
2715 break;
2716 case STLINK_DEV_DEBUG_MODE:
2717 emode = STLINK_MODE_DEBUG_SWD;
2718 break;
2719 case STLINK_DEV_SWIM_MODE:
2720 emode = STLINK_MODE_DEBUG_SWIM;
2721 break;
2722 case STLINK_DEV_BOOTLOADER_MODE:
2723 case STLINK_DEV_MASS_MODE:
2724 default:
2725 emode = STLINK_MODE_UNKNOWN;
2726 break;
2727 }
2728
2729 if (emode != STLINK_MODE_UNKNOWN)
2730 stlink_usb_mode_leave(handle, emode);
2731 /* do not check return code, it prevent
2732 us from closing jtag_libusb */
2733 }
2734
2735 if (h && h->fd)
2736 jtag_libusb_close(h->fd);
2737
2738 free(h);
2739
2740 return ERROR_OK;
2741 }
2742
2743 /** */
2744 static int stlink_usb_open(struct hl_interface_param_s *param, void **fd)
2745 {
2746 int err, retry_count = 1;
2747 struct stlink_usb_handle_s *h;
2748
2749 LOG_DEBUG("stlink_usb_open");
2750
2751 h = calloc(1, sizeof(struct stlink_usb_handle_s));
2752
2753 if (h == 0) {
2754 LOG_DEBUG("malloc failed");
2755 return ERROR_FAIL;
2756 }
2757
2758 h->transport = param->transport;
2759
2760 for (unsigned i = 0; param->vid[i]; i++) {
2761 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
2762 param->transport, param->vid[i], param->pid[i],
2763 param->serial ? param->serial : "");
2764 }
2765
2766 /*
2767 On certain host USB configurations(e.g. MacBook Air)
2768 STLINKv2 dongle seems to have its FW in a funky state if,
2769 after plugging it in, you try to use openocd with it more
2770 then once (by launching and closing openocd). In cases like
2771 that initial attempt to read the FW info via
2772 stlink_usb_version will fail and the device has to be reset
2773 in order to become operational.
2774 */
2775 do {
2776 if (jtag_libusb_open(param->vid, param->pid, param->serial, &h->fd) != ERROR_OK) {
2777 LOG_ERROR("open failed");
2778 goto error_open;
2779 }
2780
2781 jtag_libusb_set_configuration(h->fd, 0);
2782
2783 if (jtag_libusb_claim_interface(h->fd, 0) != ERROR_OK) {
2784 LOG_DEBUG("claim interface failed");
2785 goto error_open;
2786 }
2787
2788 /* RX EP is common for all versions */
2789 h->rx_ep = STLINK_RX_EP;
2790
2791 uint16_t pid;
2792 if (jtag_libusb_get_pid(jtag_libusb_get_device(h->fd), &pid) != ERROR_OK) {
2793 LOG_DEBUG("libusb_get_pid failed");
2794 goto error_open;
2795 }
2796
2797 /* wrap version for first read */
2798 switch (pid) {
2799 case STLINK_V1_PID:
2800 h->version.stlink = 1;
2801 h->tx_ep = STLINK_TX_EP;
2802 break;
2803 case STLINK_V3_USBLOADER_PID:
2804 case STLINK_V3E_PID:
2805 case STLINK_V3S_PID:
2806 case STLINK_V3_2VCP_PID:
2807 h->version.stlink = 3;
2808 h->tx_ep = STLINK_V2_1_TX_EP;
2809 h->trace_ep = STLINK_V2_1_TRACE_EP;
2810 break;
2811 case STLINK_V2_1_PID:
2812 case STLINK_V2_1_NO_MSD_PID:
2813 h->version.stlink = 2;
2814 h->tx_ep = STLINK_V2_1_TX_EP;
2815 h->trace_ep = STLINK_V2_1_TRACE_EP;
2816 break;
2817 default:
2818 /* fall through - we assume V2 to be the default version*/
2819 case STLINK_V2_PID:
2820 h->version.stlink = 2;
2821 h->tx_ep = STLINK_TX_EP;
2822 h->trace_ep = STLINK_TRACE_EP;
2823 break;
2824 }
2825
2826 /* get the device version */
2827 err = stlink_usb_version(h);
2828
2829 if (err == ERROR_OK) {
2830 break;
2831 } else if (h->version.stlink == 1 ||
2832 retry_count == 0) {
2833 LOG_ERROR("read version failed");
2834 goto error_open;
2835 } else {
2836 err = jtag_libusb_release_interface(h->fd, 0);
2837 if (err != ERROR_OK) {
2838 LOG_ERROR("release interface failed");
2839 goto error_open;
2840 }
2841
2842 err = jtag_libusb_reset_device(h->fd);
2843 if (err != ERROR_OK) {
2844 LOG_ERROR("reset device failed");
2845 goto error_open;
2846 }
2847
2848 jtag_libusb_close(h->fd);
2849 /*
2850 Give the device one second to settle down and
2851 reenumerate.
2852 */
2853 usleep(1 * 1000 * 1000);
2854 retry_count--;
2855 }
2856 } while (1);
2857
2858 /* check if mode is supported */
2859 err = ERROR_OK;
2860
2861 switch (h->transport) {
2862 case HL_TRANSPORT_SWD:
2863 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2864 err = ERROR_FAIL;
2865 /* fall-through */
2866 case HL_TRANSPORT_JTAG:
2867 if (h->version.jtag == 0)
2868 err = ERROR_FAIL;
2869 break;
2870 case HL_TRANSPORT_SWIM:
2871 if (h->version.swim == 0)
2872 err = ERROR_FAIL;
2873 break;
2874 default:
2875 err = ERROR_FAIL;
2876 break;
2877 }
2878
2879 if (err != ERROR_OK) {
2880 LOG_ERROR("mode (transport) not supported by device");
2881 goto error_open;
2882 }
2883
2884 /* initialize the debug hardware */
2885 err = stlink_usb_init_mode(h, param->connect_under_reset, param->initial_interface_speed);
2886
2887 if (err != ERROR_OK) {
2888 LOG_ERROR("init mode failed (unable to connect to the target)");
2889 goto error_open;
2890 }
2891
2892 if (h->transport == HL_TRANSPORT_SWIM) {
2893 err = stlink_swim_enter(h);
2894 if (err != ERROR_OK) {
2895 LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
2896 goto error_open;
2897 }
2898 *fd = h;
2899 h->max_mem_packet = STLINK_DATA_SIZE;
2900 return ERROR_OK;
2901 }
2902
2903 /* get cpuid, so we can determine the max page size
2904 * start with a safe default */
2905 h->max_mem_packet = (1 << 10);
2906
2907 uint8_t buffer[4];
2908 err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
2909 if (err == ERROR_OK) {
2910 uint32_t cpuid = le_to_h_u32(buffer);
2911 int i = (cpuid >> 4) & 0xf;
2912 if (i == 4 || i == 3) {
2913 /* Cortex-M3/M4 has 4096 bytes autoincrement range */
2914 h->max_mem_packet = (1 << 12);
2915 }
2916 }
2917
2918 LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
2919
2920 *fd = h;
2921
2922 return ERROR_OK;
2923
2924 error_open:
2925 stlink_usb_close(h);
2926
2927 return ERROR_FAIL;
2928 }
2929
2930 int stlink_config_trace(void *handle, bool enabled,
2931 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
2932 unsigned int *trace_freq, unsigned int traceclkin_freq,
2933 uint16_t *prescaler)
2934 {
2935 struct stlink_usb_handle_s *h = handle;
2936 uint16_t presc;
2937
2938 if (enabled && (!(h->version.flags & STLINK_F_HAS_TRACE) ||
2939 pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART)) {
2940 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
2941 return ERROR_FAIL;
2942 }
2943
2944 if (!enabled) {
2945 stlink_usb_trace_disable(h);
2946 return ERROR_OK;
2947 }
2948
2949 if (*trace_freq > STLINK_TRACE_MAX_HZ) {
2950 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
2951 STLINK_TRACE_MAX_HZ);
2952 return ERROR_FAIL;
2953 }
2954
2955 stlink_usb_trace_disable(h);
2956
2957 if (!*trace_freq)
2958 *trace_freq = STLINK_TRACE_MAX_HZ;
2959
2960 presc = traceclkin_freq / *trace_freq;
2961
2962 if (traceclkin_freq % *trace_freq > 0)
2963 presc++;
2964
2965 if (presc > TPIU_ACPR_MAX_SWOSCALER) {
2966 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
2967 "frequency.");
2968 return ERROR_FAIL;
2969 }
2970
2971 *prescaler = presc;
2972 h->trace.source_hz = *trace_freq;
2973
2974 return stlink_usb_trace_enable(h);
2975 }
2976
2977 /** */
2978 static int stlink_usb_init_access_port(void *handle, unsigned char ap_num)
2979 {
2980 struct stlink_usb_handle_s *h = handle;
2981
2982 assert(handle != NULL);
2983
2984 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
2985 return ERROR_COMMAND_NOTFOUND;
2986
2987 LOG_DEBUG_IO("init ap_num = %d", ap_num);
2988 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2989 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2990 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_INIT_AP;
2991 h->cmdbuf[h->cmdidx++] = ap_num;
2992
2993 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2994 }
2995
2996 /** */
2997 static int stlink_usb_close_access_port(void *handle, unsigned char ap_num)
2998 {
2999 struct stlink_usb_handle_s *h = handle;
3000
3001 assert(handle != NULL);
3002
3003 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3004 return ERROR_COMMAND_NOTFOUND;
3005
3006 LOG_DEBUG_IO("close ap_num = %d", ap_num);
3007 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3008 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3009 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_CLOSE_AP_DBG;
3010 h->cmdbuf[h->cmdidx++] = ap_num;
3011
3012 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3013 }
3014
3015 /** */
3016 static int stlink_read_dap_register(void *handle, unsigned short dap_port,
3017 unsigned short addr, uint32_t *val)
3018 {
3019 struct stlink_usb_handle_s *h = handle;
3020 int retval;
3021
3022 assert(handle != NULL);
3023
3024 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3025 return ERROR_COMMAND_NOTFOUND;
3026
3027 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3028 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3029 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_DAP_REG;
3030 h_u16_to_le(&h->cmdbuf[2], dap_port);
3031 h_u16_to_le(&h->cmdbuf[4], addr);
3032
3033 retval = stlink_usb_xfer_errcheck(handle, h->databuf, 8);
3034 *val = le_to_h_u32(h->databuf + 4);
3035 LOG_DEBUG_IO("dap_port_read = %d, addr = 0x%x, value = 0x%x", dap_port, addr, *val);
3036 return retval;
3037 }
3038
3039 /** */
3040 static int stlink_write_dap_register(void *handle, unsigned short dap_port,
3041 unsigned short addr, uint32_t val)
3042 {
3043 struct stlink_usb_handle_s *h = handle;
3044
3045 assert(handle != NULL);
3046
3047 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3048 return ERROR_COMMAND_NOTFOUND;
3049
3050 LOG_DEBUG_IO("dap_write port = %d, addr = 0x%x, value = 0x%x", dap_port, addr, val);
3051 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3052 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3053 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITE_DAP_REG;
3054 h_u16_to_le(&h->cmdbuf[2], dap_port);
3055 h_u16_to_le(&h->cmdbuf[4], addr);
3056 h_u32_to_le(&h->cmdbuf[6], val);
3057 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3058 }
3059
3060 /** */
3061 struct hl_layout_api_s stlink_usb_layout_api = {
3062 /** */
3063 .open = stlink_usb_open,
3064 /** */
3065 .close = stlink_usb_close,
3066 /** */
3067 .idcode = stlink_usb_idcode,
3068 /** */
3069 .state = stlink_usb_state,
3070 /** */
3071 .reset = stlink_usb_reset,
3072 /** */
3073 .assert_srst = stlink_usb_assert_srst,
3074 /** */
3075 .run = stlink_usb_run,
3076 /** */
3077 .halt = stlink_usb_halt,
3078 /** */
3079 .step = stlink_usb_step,
3080 /** */
3081 .read_regs = stlink_usb_read_regs,
3082 /** */
3083 .read_reg = stlink_usb_read_reg,
3084 /** */
3085 .write_reg = stlink_usb_write_reg,
3086 /** */
3087 .read_mem = stlink_usb_read_mem,
3088 /** */
3089 .write_mem = stlink_usb_write_mem,
3090 /** */
3091 .write_debug_reg = stlink_usb_write_debug_reg,
3092 /** */
3093 .override_target = stlink_usb_override_target,
3094 /** */
3095 .speed = stlink_speed,
3096 /** */
3097 .config_trace = stlink_config_trace,
3098 /** */
3099 .poll_trace = stlink_usb_trace_read,
3100 };
3101
3102 /*****************************************************************************
3103 * DAP direct interface
3104 */
3105
3106 static struct stlink_usb_handle_s *stlink_dap_handle;
3107 static struct hl_interface_param_s stlink_dap_param;
3108 static DECLARE_BITMAP(opened_ap, DP_APSEL_MAX + 1);
3109 static int stlink_dap_error = ERROR_OK;
3110
3111 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3112 uint32_t *data);
3113
3114 /** */
3115 static int stlink_dap_record_error(int error)
3116 {
3117 if (stlink_dap_error == ERROR_OK)
3118 stlink_dap_error = error;
3119 return ERROR_OK;
3120 }
3121
3122 /** */
3123 static int stlink_dap_get_and_clear_error(void)
3124 {
3125 int retval = stlink_dap_error;
3126 stlink_dap_error = ERROR_OK;
3127 return retval;
3128 }
3129
3130 /** */
3131 static int stlink_dap_open_ap(unsigned short apsel)
3132 {
3133 int retval;
3134
3135 /* nothing to do on old versions */
3136 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3137 return ERROR_OK;
3138
3139 if (apsel > DP_APSEL_MAX)
3140 return ERROR_FAIL;
3141
3142 if (test_bit(apsel, opened_ap))
3143 return ERROR_OK;
3144
3145 retval = stlink_usb_init_access_port(stlink_dap_handle, apsel);
3146 if (retval != ERROR_OK)
3147 return retval;
3148
3149 LOG_DEBUG("AP %d enabled", apsel);
3150 set_bit(apsel, opened_ap);
3151 return ERROR_OK;
3152 }
3153
3154 /** */
3155 static int stlink_dap_closeall_ap(void)
3156 {
3157 int retval, apsel;
3158
3159 /* nothing to do on old versions */
3160 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3161 return ERROR_OK;
3162
3163 for (apsel = 0; apsel <= DP_APSEL_MAX; apsel++) {
3164 if (!test_bit(apsel, opened_ap))
3165 continue;
3166 retval = stlink_usb_close_access_port(stlink_dap_handle, apsel);
3167 if (retval != ERROR_OK)
3168 return retval;
3169 clear_bit(apsel, opened_ap);
3170 }
3171 return ERROR_OK;
3172 }
3173
3174 /** */
3175 static int stlink_dap_reinit_interface(void)
3176 {
3177 int retval;
3178 enum stlink_mode mode;
3179
3180 /*
3181 * On JTAG only, it should be enough to call stlink_usb_reset(). But on
3182 * some firmware version it does not work as expected, and there is no
3183 * equivalent for SWD.
3184 * At least for now, to reset the interface quit from JTAG/SWD mode then
3185 * select the mode again.
3186 */
3187
3188 mode = stlink_get_mode(stlink_dap_param.transport);
3189 if (!stlink_dap_handle->reconnect_pending) {
3190 stlink_dap_handle->reconnect_pending = true;
3191 stlink_usb_mode_leave(stlink_dap_handle, mode);
3192 }
3193
3194 retval = stlink_usb_mode_enter(stlink_dap_handle, mode);
3195 if (retval != ERROR_OK)
3196 return retval;
3197
3198 stlink_dap_handle->reconnect_pending = false;
3199 /* on new FW, calling mode-leave closes all the opened AP; reopen them! */
3200 if (stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT)
3201 for (int apsel = 0; apsel <= DP_APSEL_MAX; apsel++)
3202 if (test_bit(apsel, opened_ap)) {
3203 clear_bit(apsel, opened_ap);
3204 stlink_dap_open_ap(apsel);
3205 }
3206 return ERROR_OK;
3207 }
3208
3209 /** */
3210 static int stlink_dap_op_connect(struct adiv5_dap *dap)
3211 {
3212 uint32_t idcode;
3213 int retval;
3214
3215 LOG_INFO("stlink_dap_op_connect(%sconnect)", dap->do_reconnect ? "re" : "");
3216
3217 /* Check if we should reset srst already when connecting, but not if reconnecting. */
3218 if (!dap->do_reconnect) {
3219 enum reset_types jtag_reset_config = jtag_get_reset_config();
3220
3221 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3222 if (jtag_reset_config & RESET_SRST_NO_GATING)
3223 adapter_assert_reset();
3224 else
3225 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3226 }
3227 }
3228
3229 dap->do_reconnect = false;
3230 dap_invalidate_cache(dap);
3231
3232 retval = dap_dp_init(dap);
3233 if (retval != ERROR_OK) {
3234 dap->do_reconnect = true;
3235 return retval;
3236 }
3237
3238 retval = stlink_usb_idcode(stlink_dap_handle, &idcode);
3239 if (retval == ERROR_OK)
3240 LOG_INFO("%s %#8.8" PRIx32,
3241 (stlink_dap_handle->transport == HL_TRANSPORT_JTAG) ? "JTAG IDCODE" : "SWD DPIDR",
3242 idcode);
3243 else
3244 dap->do_reconnect = true;
3245
3246 return retval;
3247 }
3248
3249 /** */
3250 static int stlink_dap_check_reconnect(struct adiv5_dap *dap)
3251 {
3252 int retval;
3253
3254 if (!dap->do_reconnect)
3255 return ERROR_OK;
3256
3257 retval = stlink_dap_reinit_interface();
3258 if (retval != ERROR_OK)
3259 return retval;
3260
3261 return stlink_dap_op_connect(dap);
3262 }
3263
3264 /** */
3265 static int stlink_dap_op_send_sequence(struct adiv5_dap *dap, enum swd_special_seq seq)
3266 {
3267 /* Ignore the request */
3268 return ERROR_OK;
3269 }
3270
3271 /** */
3272 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3273 uint32_t *data)
3274 {
3275 uint32_t dummy;
3276 int retval;
3277
3278 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3279 if (reg & 0x000000F0) {
3280 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3281 return ERROR_COMMAND_NOTFOUND;
3282 }
3283
3284 retval = stlink_dap_check_reconnect(dap);
3285 if (retval != ERROR_OK)
3286 return retval;
3287
3288 data = data ? : &dummy;
3289 if (stlink_dap_handle->version.flags & STLINK_F_QUIRK_JTAG_DP_READ
3290 && stlink_dap_handle->transport == HL_TRANSPORT_JTAG) {
3291 /* Quirk required in JTAG. Read RDBUFF to get the data */
3292 retval = stlink_read_dap_register(stlink_dap_handle,
3293 STLINK_DEBUG_PORT_ACCESS, reg, &dummy);
3294 if (retval == ERROR_OK)
3295 retval = stlink_read_dap_register(stlink_dap_handle,
3296 STLINK_DEBUG_PORT_ACCESS, DP_RDBUFF, data);
3297 } else {
3298 retval = stlink_read_dap_register(stlink_dap_handle,
3299 STLINK_DEBUG_PORT_ACCESS, reg, data);
3300 }
3301
3302 return stlink_dap_record_error(retval);
3303 }
3304
3305 /** */
3306 static int stlink_dap_op_queue_dp_write(struct adiv5_dap *dap, unsigned reg,
3307 uint32_t data)
3308 {
3309 int retval;
3310
3311 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3312 if (reg & 0x000000F0) {
3313 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3314 return ERROR_COMMAND_NOTFOUND;
3315 }
3316
3317 if (reg == DP_SELECT && (data & DP_SELECT_DPBANK) != 0) {
3318 /* ignored if STLINK_F_HAS_DPBANKSEL, not properly managed otherwise */
3319 LOG_DEBUG("Ignoring DPBANKSEL while write SELECT");
3320 data &= ~DP_SELECT_DPBANK;
3321 }
3322
3323 retval = stlink_dap_check_reconnect(dap);
3324 if (retval != ERROR_OK)
3325 return retval;
3326
3327 /* ST-Link does not like that we set CORUNDETECT */
3328 if (reg == DP_CTRL_STAT)
3329 data &= ~CORUNDETECT;
3330
3331 retval = stlink_write_dap_register(stlink_dap_handle,
3332 STLINK_DEBUG_PORT_ACCESS, reg, data);
3333 return stlink_dap_record_error(retval);
3334 }
3335
3336 /** */
3337 static int stlink_dap_op_queue_ap_read(struct adiv5_ap *ap, unsigned reg,
3338 uint32_t *data)
3339 {
3340 struct adiv5_dap *dap = ap->dap;
3341 uint32_t dummy;
3342 int retval;
3343
3344 retval = stlink_dap_check_reconnect(dap);
3345 if (retval != ERROR_OK)
3346 return retval;
3347
3348 if (reg != AP_REG_IDR) {
3349 retval = stlink_dap_open_ap(ap->ap_num);
3350 if (retval != ERROR_OK)
3351 return retval;
3352 }
3353 data = data ? : &dummy;
3354 retval = stlink_read_dap_register(stlink_dap_handle, ap->ap_num, reg,
3355 data);
3356 dap->stlink_flush_ap_write = false;
3357 return stlink_dap_record_error(retval);
3358 }
3359
3360 /** */
3361 static int stlink_dap_op_queue_ap_write(struct adiv5_ap *ap, unsigned reg,
3362 uint32_t data)
3363 {
3364 struct adiv5_dap *dap = ap->dap;
3365 int retval;
3366
3367 retval = stlink_dap_check_reconnect(dap);
3368 if (retval != ERROR_OK)
3369 return retval;
3370
3371 retval = stlink_dap_open_ap(ap->ap_num);
3372 if (retval != ERROR_OK)
3373 return retval;
3374
3375 retval = stlink_write_dap_register(stlink_dap_handle, ap->ap_num, reg,
3376 data);
3377 dap->stlink_flush_ap_write = true;
3378 return stlink_dap_record_error(retval);
3379 }
3380
3381 /** */
3382 static int stlink_dap_op_queue_ap_abort(struct adiv5_dap *dap, uint8_t *ack)
3383 {
3384 LOG_WARNING("stlink_dap_op_queue_ap_abort()");
3385 return ERROR_OK;
3386 }
3387
3388 /** */
3389 static int stlink_dap_op_run(struct adiv5_dap *dap)
3390 {
3391 uint32_t ctrlstat, pwrmask;
3392 int retval, saved_retval;
3393
3394 /* Here no LOG_DEBUG. This is called continuously! */
3395
3396 /*
3397 * ST-Link returns immediately after a DAP write, without waiting for it
3398 * to complete.
3399 * Run a dummy read to DP_RDBUFF, as suggested in
3400 * http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka16363.html
3401 */
3402 if (dap->stlink_flush_ap_write) {
3403 dap->stlink_flush_ap_write = false;
3404 retval = stlink_dap_op_queue_dp_read(dap, DP_RDBUFF, NULL);
3405 if (retval != ERROR_OK) {
3406 dap->do_reconnect = true;
3407 return retval;
3408 }
3409 }
3410
3411 saved_retval = stlink_dap_get_and_clear_error();
3412
3413 retval = stlink_dap_op_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
3414 if (retval != ERROR_OK) {
3415 dap->do_reconnect = true;
3416 return retval;
3417 }
3418 retval = stlink_dap_get_and_clear_error();
3419 if (retval != ERROR_OK) {
3420 LOG_ERROR("Fail reading CTRL/STAT register. Force reconnect");
3421 dap->do_reconnect = true;
3422 return retval;
3423 }
3424
3425 if (ctrlstat & SSTICKYERR) {
3426 if (stlink_dap_param.transport == HL_TRANSPORT_JTAG)
3427 retval = stlink_dap_op_queue_dp_write(dap, DP_CTRL_STAT,
3428 ctrlstat & (dap->dp_ctrl_stat | SSTICKYERR));
3429 else
3430 retval = stlink_dap_op_queue_dp_write(dap, DP_ABORT, STKERRCLR);
3431 if (retval != ERROR_OK) {
3432 dap->do_reconnect = true;
3433 return retval;
3434 }
3435 retval = stlink_dap_get_and_clear_error();
3436 if (retval != ERROR_OK) {
3437 dap->do_reconnect = true;
3438 return retval;
3439 }
3440 }
3441
3442 /* check for power lost */
3443 pwrmask = dap->dp_ctrl_stat & (CDBGPWRUPREQ | CSYSPWRUPREQ);
3444 if ((ctrlstat & pwrmask) != pwrmask)
3445 dap->do_reconnect = true;
3446
3447 return saved_retval;
3448 }
3449
3450 /** */
3451 static void stlink_dap_op_quit(struct adiv5_dap *dap)
3452 {
3453 int retval;
3454
3455 retval = stlink_dap_closeall_ap();
3456 if (retval != ERROR_OK)
3457 LOG_ERROR("Error closing APs");
3458 }
3459
3460 /** */
3461 COMMAND_HANDLER(stlink_dap_serial_command)
3462 {
3463 LOG_DEBUG("stlink_dap_serial_command");
3464
3465 if (CMD_ARGC != 1) {
3466 LOG_ERROR("Expected exactly one argument for \"st-link serial <serial-number>\".");
3467 return ERROR_COMMAND_SYNTAX_ERROR;
3468 }
3469
3470 if (stlink_dap_param.serial) {
3471 LOG_WARNING("Command \"st-link serial\" already used. Replacing previous value");
3472 free((void *)stlink_dap_param.serial);
3473 }
3474
3475 stlink_dap_param.serial = strdup(CMD_ARGV[0]);
3476 return ERROR_OK;
3477 }
3478
3479 /** */
3480 COMMAND_HANDLER(stlink_dap_vid_pid)
3481 {
3482 unsigned int i, max_usb_ids = HLA_MAX_USB_IDS;
3483
3484 if (CMD_ARGC > max_usb_ids * 2) {
3485 LOG_WARNING("ignoring extra IDs in vid_pid "
3486 "(maximum is %d pairs)", max_usb_ids);
3487 CMD_ARGC = max_usb_ids * 2;
3488 }
3489 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
3490 LOG_WARNING("incomplete vid_pid configuration directive");
3491 return ERROR_COMMAND_SYNTAX_ERROR;
3492 }
3493 for (i = 0; i < CMD_ARGC; i += 2) {
3494 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], stlink_dap_param.vid[i / 2]);
3495 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], stlink_dap_param.pid[i / 2]);
3496 }
3497
3498 /* null termination */
3499 stlink_dap_param.vid[i / 2] = stlink_dap_param.pid[i / 2] = 0;
3500
3501 return ERROR_OK;
3502 }
3503
3504 /** */
3505 static const struct command_registration stlink_dap_subcommand_handlers[] = {
3506 {
3507 .name = "serial",
3508 .handler = stlink_dap_serial_command,
3509 .mode = COMMAND_CONFIG,
3510 .help = "set the serial number of the adapter",
3511 .usage = "<serial_number>",
3512 },
3513 {
3514 .name = "vid_pid",
3515 .handler = stlink_dap_vid_pid,
3516 .mode = COMMAND_CONFIG,
3517 .help = "USB VID and PID of the adapter",
3518 .usage = "(vid pid)+",
3519 },
3520 COMMAND_REGISTRATION_DONE
3521 };
3522
3523 /** */
3524 static const struct command_registration stlink_dap_command_handlers[] = {
3525 {
3526 .name = "st-link",
3527 .mode = COMMAND_ANY,
3528 .help = "perform st-link management",
3529 .chain = stlink_dap_subcommand_handlers,
3530 .usage = "",
3531 },
3532 COMMAND_REGISTRATION_DONE
3533 };
3534
3535 /** */
3536 static int stlink_dap_init(void)
3537 {
3538 enum reset_types jtag_reset_config = jtag_get_reset_config();
3539 int retval;
3540
3541 LOG_DEBUG("stlink_dap_init()");
3542
3543 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3544 if (jtag_reset_config & RESET_SRST_NO_GATING)
3545 stlink_dap_param.connect_under_reset = true;
3546 else
3547 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3548 }
3549
3550 if (transport_is_dapdirect_swd())
3551 stlink_dap_param.transport = HL_TRANSPORT_SWD;
3552 else if (transport_is_dapdirect_jtag())
3553 stlink_dap_param.transport = HL_TRANSPORT_JTAG;
3554 else {
3555 LOG_ERROR("Unsupported transport");
3556 return ERROR_FAIL;
3557 }
3558
3559 retval = stlink_usb_open(&stlink_dap_param, (void **)&stlink_dap_handle);
3560 if (retval != ERROR_OK)
3561 return retval;
3562
3563 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DAP_REG)) {
3564 LOG_ERROR("ST-Link version does not support DAP direct transport");
3565 return ERROR_FAIL;
3566 }
3567 return ERROR_OK;
3568 }
3569
3570 /** */
3571 static int stlink_dap_quit(void)
3572 {
3573 LOG_DEBUG("stlink_dap_quit()");
3574
3575 free((void *)stlink_dap_param.serial);
3576 stlink_dap_param.serial = NULL;
3577
3578 return stlink_usb_close(stlink_dap_handle);
3579 }
3580
3581 /** */
3582 static int stlink_dap_reset(int req_trst, int req_srst)
3583 {
3584 LOG_DEBUG("stlink_dap_reset(%d)", req_srst);
3585 return stlink_usb_assert_srst(stlink_dap_handle,
3586 req_srst ? STLINK_DEBUG_APIV2_DRIVE_NRST_LOW
3587 : STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH);
3588 }
3589
3590 /** */
3591 static int stlink_dap_speed(int speed)
3592 {
3593 if (speed == 0) {
3594 LOG_ERROR("RTCK not supported. Set nonzero adapter_khz.");
3595 return ERROR_JTAG_NOT_IMPLEMENTED;
3596 }
3597
3598 stlink_dap_param.initial_interface_speed = speed;
3599 stlink_speed(stlink_dap_handle, speed, false);
3600 return ERROR_OK;
3601 }
3602
3603 /** */
3604 static int stlink_dap_khz(int khz, int *jtag_speed)
3605 {
3606 *jtag_speed = khz;
3607 return ERROR_OK;
3608 }
3609
3610 /** */
3611 static int stlink_dap_speed_div(int speed, int *khz)
3612 {
3613 *khz = speed;
3614 return ERROR_OK;
3615 }
3616
3617 static const struct dap_ops stlink_dap_ops = {
3618 .connect = stlink_dap_op_connect,
3619 .send_sequence = stlink_dap_op_send_sequence,
3620 .queue_dp_read = stlink_dap_op_queue_dp_read,
3621 .queue_dp_write = stlink_dap_op_queue_dp_write,
3622 .queue_ap_read = stlink_dap_op_queue_ap_read,
3623 .queue_ap_write = stlink_dap_op_queue_ap_write,
3624 .queue_ap_abort = stlink_dap_op_queue_ap_abort,
3625 .run = stlink_dap_op_run,
3626 .sync = NULL, /* optional */
3627 .quit = stlink_dap_op_quit, /* optional */
3628 };
3629
3630 static const char *const stlink_dap_transport[] = { "dapdirect_jtag", "dapdirect_swd", NULL };
3631
3632 struct adapter_driver stlink_dap_adapter_driver = {
3633 .name = "st-link",
3634 .transports = stlink_dap_transport,
3635 .commands = stlink_dap_command_handlers,
3636
3637 .init = stlink_dap_init,
3638 .quit = stlink_dap_quit,
3639 .reset = stlink_dap_reset,
3640 .speed = stlink_dap_speed,
3641 .khz = stlink_dap_khz,
3642 .speed_div = stlink_dap_speed_div,
3643
3644 .dap_jtag_ops = &stlink_dap_ops,
3645 .dap_swd_ops = &stlink_dap_ops,
3646 };

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)