1 /***************************************************************************
2 * SWIM contributions by Ake Rehnman *
3 * Copyright (C) 2017 Ake Rehnman *
4 * ake.rehnman(at)gmail.com *
6 * Copyright (C) 2011-2012 by Mathias Kuester *
7 * Mathias Kuester <kesmtp@freenet.de> *
9 * Copyright (C) 2012 by Spencer Oliver *
10 * spen@spen-soft.co.uk *
12 * This code is based on https://github.com/texane/stlink *
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. *
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. *
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 ***************************************************************************/
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 <jtag/swim.h>
40 #include <target/target.h>
41 #include <transport/transport.h>
43 #include <target/cortex_m.h>
45 #include "libusb_helper.h"
48 #define USE_LIBUSB_ASYNCIO
51 #define STLINK_SERIAL_LEN 24
53 #define ENDPOINT_IN 0x80
54 #define ENDPOINT_OUT 0x00
56 #define STLINK_WRITE_TIMEOUT 1000
57 #define STLINK_READ_TIMEOUT 1000
59 #define STLINK_RX_EP (1|ENDPOINT_IN)
60 #define STLINK_TX_EP (2|ENDPOINT_OUT)
61 #define STLINK_TRACE_EP (3|ENDPOINT_IN)
63 #define STLINK_V2_1_TX_EP (1|ENDPOINT_OUT)
64 #define STLINK_V2_1_TRACE_EP (2|ENDPOINT_IN)
66 #define STLINK_SG_SIZE (31)
67 #define STLINK_DATA_SIZE (4096)
68 #define STLINK_CMD_SIZE_V2 (16)
69 #define STLINK_CMD_SIZE_V1 (10)
71 #define STLINK_V1_PID (0x3744)
72 #define STLINK_V2_PID (0x3748)
73 #define STLINK_V2_1_PID (0x374B)
74 #define STLINK_V2_1_NO_MSD_PID (0x3752)
75 #define STLINK_V3_USBLOADER_PID (0x374D)
76 #define STLINK_V3E_PID (0x374E)
77 #define STLINK_V3S_PID (0x374F)
78 #define STLINK_V3_2VCP_PID (0x3753)
81 * ST-Link/V1, ST-Link/V2 and ST-Link/V2.1 are full-speed USB devices and
82 * this limits the bulk packet size and the 8bit read/writes to max 64 bytes.
83 * STLINK-V3 is a high speed USB 2.0 and the limit is 512 bytes from FW V3J6.
85 #define STLINK_MAX_RW8 (64)
86 #define STLINKV3_MAX_RW8 (512)
88 /* "WAIT" responses will be retried (with exponential backoff) at
89 * most this many times before failing to caller.
91 #define MAX_WAIT_RETRIES 8
93 enum stlink_jtag_api_version {
94 STLINK_JTAG_API_V1 = 1,
100 STLINK_MODE_UNKNOWN = 0,
103 STLINK_MODE_DEBUG_JTAG,
104 STLINK_MODE_DEBUG_SWD,
105 STLINK_MODE_DEBUG_SWIM
109 struct stlink_usb_version {
116 /** jtag api version supported */
117 enum stlink_jtag_api_version jtag_api;
118 /** one bit for each feature supported. See macros STLINK_F_* */
123 struct stlink_usb_handle_s {
125 struct libusb_device_handle *fd;
127 struct libusb_transfer *trans;
135 uint8_t cmdbuf[STLINK_SG_SIZE];
141 uint8_t databuf[STLINK_DATA_SIZE];
143 uint32_t max_mem_packet;
145 enum stlink_mode st_mode;
147 struct stlink_usb_version version;
154 /** whether SWO tracing is enabled or not */
156 /** trace module source clock */
159 /** reconnect is needed next time we try to query the
161 bool reconnect_pending;
164 #define STLINK_SWIM_ERR_OK 0x00
165 #define STLINK_SWIM_BUSY 0x01
166 #define STLINK_DEBUG_ERR_OK 0x80
167 #define STLINK_DEBUG_ERR_FAULT 0x81
168 #define STLINK_SWD_AP_WAIT 0x10
169 #define STLINK_SWD_AP_FAULT 0x11
170 #define STLINK_SWD_AP_ERROR 0x12
171 #define STLINK_SWD_AP_PARITY_ERROR 0x13
172 #define STLINK_JTAG_GET_IDCODE_ERROR 0x09
173 #define STLINK_JTAG_WRITE_ERROR 0x0c
174 #define STLINK_JTAG_WRITE_VERIF_ERROR 0x0d
175 #define STLINK_SWD_DP_WAIT 0x14
176 #define STLINK_SWD_DP_FAULT 0x15
177 #define STLINK_SWD_DP_ERROR 0x16
178 #define STLINK_SWD_DP_PARITY_ERROR 0x17
180 #define STLINK_SWD_AP_WDATA_ERROR 0x18
181 #define STLINK_SWD_AP_STICKY_ERROR 0x19
182 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
184 #define STLINK_BAD_AP_ERROR 0x1d
186 #define STLINK_CORE_RUNNING 0x80
187 #define STLINK_CORE_HALTED 0x81
188 #define STLINK_CORE_STAT_UNKNOWN -1
190 #define STLINK_GET_VERSION 0xF1
191 #define STLINK_DEBUG_COMMAND 0xF2
192 #define STLINK_DFU_COMMAND 0xF3
193 #define STLINK_SWIM_COMMAND 0xF4
194 #define STLINK_GET_CURRENT_MODE 0xF5
195 #define STLINK_GET_TARGET_VOLTAGE 0xF7
197 #define STLINK_DEV_DFU_MODE 0x00
198 #define STLINK_DEV_MASS_MODE 0x01
199 #define STLINK_DEV_DEBUG_MODE 0x02
200 #define STLINK_DEV_SWIM_MODE 0x03
201 #define STLINK_DEV_BOOTLOADER_MODE 0x04
202 #define STLINK_DEV_UNKNOWN_MODE -1
204 #define STLINK_DFU_EXIT 0x07
207 STLINK_SWIM_ENTER_SEQ
208 1.3ms low then 750Hz then 1.5kHz
211 STM8 DM pulls reset pin low 50us
214 uint8_t (0=low|1=high)
221 send synchronization seq (16us low, response 64 clocks low)
223 #define STLINK_SWIM_ENTER 0x00
224 #define STLINK_SWIM_EXIT 0x01
225 #define STLINK_SWIM_READ_CAP 0x02
226 #define STLINK_SWIM_SPEED 0x03
227 #define STLINK_SWIM_ENTER_SEQ 0x04
228 #define STLINK_SWIM_GEN_RST 0x05
229 #define STLINK_SWIM_RESET 0x06
230 #define STLINK_SWIM_ASSERT_RESET 0x07
231 #define STLINK_SWIM_DEASSERT_RESET 0x08
232 #define STLINK_SWIM_READSTATUS 0x09
233 #define STLINK_SWIM_WRITEMEM 0x0a
234 #define STLINK_SWIM_READMEM 0x0b
235 #define STLINK_SWIM_READBUF 0x0c
237 #define STLINK_DEBUG_GETSTATUS 0x01
238 #define STLINK_DEBUG_FORCEDEBUG 0x02
239 #define STLINK_DEBUG_APIV1_RESETSYS 0x03
240 #define STLINK_DEBUG_APIV1_READALLREGS 0x04
241 #define STLINK_DEBUG_APIV1_READREG 0x05
242 #define STLINK_DEBUG_APIV1_WRITEREG 0x06
243 #define STLINK_DEBUG_READMEM_32BIT 0x07
244 #define STLINK_DEBUG_WRITEMEM_32BIT 0x08
245 #define STLINK_DEBUG_RUNCORE 0x09
246 #define STLINK_DEBUG_STEPCORE 0x0a
247 #define STLINK_DEBUG_APIV1_SETFP 0x0b
248 #define STLINK_DEBUG_READMEM_8BIT 0x0c
249 #define STLINK_DEBUG_WRITEMEM_8BIT 0x0d
250 #define STLINK_DEBUG_APIV1_CLEARFP 0x0e
251 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG 0x0f
252 #define STLINK_DEBUG_APIV1_SETWATCHPOINT 0x10
254 #define STLINK_DEBUG_ENTER_JTAG_RESET 0x00
255 #define STLINK_DEBUG_ENTER_SWD_NO_RESET 0xa3
256 #define STLINK_DEBUG_ENTER_JTAG_NO_RESET 0xa4
258 #define STLINK_DEBUG_APIV1_ENTER 0x20
259 #define STLINK_DEBUG_EXIT 0x21
260 #define STLINK_DEBUG_READCOREID 0x22
262 #define STLINK_DEBUG_APIV2_ENTER 0x30
263 #define STLINK_DEBUG_APIV2_READ_IDCODES 0x31
264 #define STLINK_DEBUG_APIV2_RESETSYS 0x32
265 #define STLINK_DEBUG_APIV2_READREG 0x33
266 #define STLINK_DEBUG_APIV2_WRITEREG 0x34
267 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG 0x35
268 #define STLINK_DEBUG_APIV2_READDEBUGREG 0x36
270 #define STLINK_DEBUG_APIV2_READALLREGS 0x3A
271 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
272 #define STLINK_DEBUG_APIV2_DRIVE_NRST 0x3C
274 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS2 0x3E
276 #define STLINK_DEBUG_APIV2_START_TRACE_RX 0x40
277 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX 0x41
278 #define STLINK_DEBUG_APIV2_GET_TRACE_NB 0x42
279 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ 0x43
280 #define STLINK_DEBUG_APIV2_JTAG_SET_FREQ 0x44
281 #define STLINK_DEBUG_APIV2_READ_DAP_REG 0x45
282 #define STLINK_DEBUG_APIV2_WRITE_DAP_REG 0x46
283 #define STLINK_DEBUG_APIV2_READMEM_16BIT 0x47
284 #define STLINK_DEBUG_APIV2_WRITEMEM_16BIT 0x48
286 #define STLINK_DEBUG_APIV2_INIT_AP 0x4B
287 #define STLINK_DEBUG_APIV2_CLOSE_AP_DBG 0x4C
289 #define STLINK_APIV3_SET_COM_FREQ 0x61
290 #define STLINK_APIV3_GET_COM_FREQ 0x62
292 #define STLINK_APIV3_GET_VERSION_EX 0xFB
294 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW 0x00
295 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH 0x01
296 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
298 #define STLINK_DEBUG_PORT_ACCESS 0xffff
300 #define STLINK_TRACE_SIZE 4096
301 #define STLINK_TRACE_MAX_HZ 2000000
302 #define STLINK_V3_TRACE_MAX_HZ 24000000
304 #define STLINK_V3_MAX_FREQ_NB 10
306 #define REQUEST_SENSE 0x03
307 #define REQUEST_SENSE_LENGTH 18
310 * Map the relevant features, quirks and workaround for specific firmware
313 #define STLINK_F_HAS_TRACE BIT(0)
314 #define STLINK_F_HAS_SWD_SET_FREQ BIT(1)
315 #define STLINK_F_HAS_JTAG_SET_FREQ BIT(2)
316 #define STLINK_F_HAS_MEM_16BIT BIT(3)
317 #define STLINK_F_HAS_GETLASTRWSTATUS2 BIT(4)
318 #define STLINK_F_HAS_DAP_REG BIT(5)
319 #define STLINK_F_QUIRK_JTAG_DP_READ BIT(6)
320 #define STLINK_F_HAS_AP_INIT BIT(7)
321 #define STLINK_F_HAS_DPBANKSEL BIT(8)
322 #define STLINK_F_HAS_RW8_512BYTES BIT(9)
323 #define STLINK_F_FIX_CLOSE_AP BIT(10)
326 #define STLINK_F_HAS_TARGET_VOLT STLINK_F_HAS_TRACE
333 /* SWD clock speed */
334 static const struct speed_map stlink_khz_to_speed_map_swd[] = {
336 {1800, 1}, /* default */
349 /* JTAG clock speed */
350 static const struct speed_map stlink_khz_to_speed_map_jtag[] = {
354 {1125, 32}, /* default */
360 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
361 static int stlink_swim_status(void *handle);
362 static void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size);
363 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map);
364 static int stlink_speed(void *handle, int khz, bool query);
365 static int stlink_usb_open_ap(void *handle, unsigned short apsel);
368 static unsigned int stlink_usb_block(void *handle)
370 struct stlink_usb_handle_s *h = handle;
372 assert(handle != NULL);
374 if (h->version.flags & STLINK_F_HAS_RW8_512BYTES)
375 return STLINKV3_MAX_RW8;
377 return STLINK_MAX_RW8;
382 #ifdef USE_LIBUSB_ASYNCIO
384 static LIBUSB_CALL void sync_transfer_cb(struct libusb_transfer *transfer)
386 int *completed = transfer->user_data;
388 /* caller interprets result and frees transfer */
392 static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
394 int r, *completed = transfer->user_data;
396 /* Assuming a single libusb context exists. There no existing interface into this
397 * module to pass a libusb context.
399 struct libusb_context *ctx = NULL;
401 while (!*completed) {
402 r = libusb_handle_events_completed(ctx, completed);
404 if (r == LIBUSB_ERROR_INTERRUPTED)
406 libusb_cancel_transfer(transfer);
413 static int transfer_error_status(const struct libusb_transfer *transfer)
417 switch (transfer->status) {
418 case LIBUSB_TRANSFER_COMPLETED:
421 case LIBUSB_TRANSFER_TIMED_OUT:
422 r = LIBUSB_ERROR_TIMEOUT;
424 case LIBUSB_TRANSFER_STALL:
425 r = LIBUSB_ERROR_PIPE;
427 case LIBUSB_TRANSFER_OVERFLOW:
428 r = LIBUSB_ERROR_OVERFLOW;
430 case LIBUSB_TRANSFER_NO_DEVICE:
431 r = LIBUSB_ERROR_NO_DEVICE;
433 case LIBUSB_TRANSFER_ERROR:
434 case LIBUSB_TRANSFER_CANCELLED:
438 r = LIBUSB_ERROR_OTHER;
452 size_t transfer_size;
453 struct libusb_transfer *transfer;
456 static int jtag_libusb_bulk_transfer_n(
457 struct libusb_device_handle *dev_handle,
458 struct jtag_xfer *transfers,
463 int returnval = ERROR_OK;
466 for (size_t i = 0; i < n_transfers; ++i) {
467 transfers[i].retval = 0;
468 transfers[i].completed = 0;
469 transfers[i].transfer_size = 0;
470 transfers[i].transfer = libusb_alloc_transfer(0);
472 if (transfers[i].transfer == NULL) {
473 for (size_t j = 0; j < i; ++j)
474 libusb_free_transfer(transfers[j].transfer);
476 LOG_DEBUG("ERROR, failed to alloc usb transfers");
477 for (size_t k = 0; k < n_transfers; ++k)
478 transfers[k].retval = LIBUSB_ERROR_NO_MEM;
483 for (size_t i = 0; i < n_transfers; ++i) {
484 libusb_fill_bulk_transfer(
485 transfers[i].transfer,
487 transfers[i].ep, transfers[i].buf, transfers[i].size,
488 sync_transfer_cb, &transfers[i].completed, timeout);
489 transfers[i].transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
491 retval = libusb_submit_transfer(transfers[i].transfer);
493 LOG_DEBUG("ERROR, failed to submit transfer %zu, error %d", i, retval);
495 /* Probably no point continuing to submit transfers once a submission fails.
496 * As a result, tag all remaining transfers as errors.
498 for (size_t j = i; j < n_transfers; ++j)
499 transfers[j].retval = retval;
501 returnval = ERROR_FAIL;
506 /* Wait for every submitted USB transfer to complete.
508 for (size_t i = 0; i < n_transfers; ++i) {
509 if (transfers[i].retval == 0) {
510 sync_transfer_wait_for_completion(transfers[i].transfer);
512 retval = transfer_error_status(transfers[i].transfer);
514 returnval = ERROR_FAIL;
515 transfers[i].retval = retval;
516 LOG_DEBUG("ERROR, transfer %zu failed, error %d", i, retval);
518 /* Assuming actual_length is only valid if there is no transfer error.
520 transfers[i].transfer_size = transfers[i].transfer->actual_length;
524 libusb_free_transfer(transfers[i].transfer);
525 transfers[i].transfer = NULL;
535 static int stlink_usb_xfer_v1_get_status(void *handle)
537 struct stlink_usb_handle_s *h = handle;
540 assert(handle != NULL);
543 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
545 ret = jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)h->cmdbuf, 13,
546 STLINK_READ_TIMEOUT, &tr);
552 t1 = buf_get_u32(h->cmdbuf, 0, 32);
555 if (t1 != 0x53425355)
563 if (h->cmdbuf[12] != 0)
569 #ifdef USE_LIBUSB_ASYNCIO
570 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
572 struct stlink_usb_handle_s *h = handle;
574 assert(handle != NULL);
576 size_t n_transfers = 0;
577 struct jtag_xfer transfers[2];
579 memset(transfers, 0, sizeof(transfers));
581 transfers[0].ep = h->tx_ep;
582 transfers[0].buf = h->cmdbuf;
583 transfers[0].size = cmdsize;
587 if (h->direction == h->tx_ep && size) {
588 transfers[1].ep = h->tx_ep;
589 transfers[1].buf = (uint8_t *)buf;
590 transfers[1].size = size;
593 } else if (h->direction == h->rx_ep && size) {
594 transfers[1].ep = h->rx_ep;
595 transfers[1].buf = (uint8_t *)buf;
596 transfers[1].size = size;
601 return jtag_libusb_bulk_transfer_n(
605 STLINK_WRITE_TIMEOUT);
608 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
610 struct stlink_usb_handle_s *h = handle;
613 assert(handle != NULL);
615 ret = jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)h->cmdbuf,
616 cmdsize, STLINK_WRITE_TIMEOUT, &tr);
617 if (ret || tr != cmdsize)
620 if (h->direction == h->tx_ep && size) {
621 ret = jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)buf,
622 size, STLINK_WRITE_TIMEOUT, &tr);
623 if (ret || tr != size) {
624 LOG_DEBUG("bulk write failed");
627 } else if (h->direction == h->rx_ep && size) {
628 ret = jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)buf,
629 size, STLINK_READ_TIMEOUT, &tr);
630 if (ret || tr != size) {
631 LOG_DEBUG("bulk read failed");
641 static int stlink_usb_xfer_v1_get_sense(void *handle)
644 struct stlink_usb_handle_s *h = handle;
646 assert(handle != NULL);
648 stlink_usb_init_buffer(handle, h->rx_ep, 16);
650 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE;
651 h->cmdbuf[h->cmdidx++] = 0;
652 h->cmdbuf[h->cmdidx++] = 0;
653 h->cmdbuf[h->cmdidx++] = 0;
654 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE_LENGTH;
656 res = stlink_usb_xfer_rw(handle, REQUEST_SENSE_LENGTH, h->databuf, 16);
661 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK)
668 transfers block in cmdbuf
669 <size> indicates number of bytes in the following
671 Ignore the (eventual) error code in the received packet.
673 static int stlink_usb_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
675 int err, cmdsize = STLINK_CMD_SIZE_V2;
676 struct stlink_usb_handle_s *h = handle;
678 assert(handle != NULL);
680 if (h->version.stlink == 1) {
681 cmdsize = STLINK_SG_SIZE;
682 /* put length in bCBWCBLength */
683 h->cmdbuf[14] = h->cmdidx-15;
686 err = stlink_usb_xfer_rw(handle, cmdsize, buf, size);
691 if (h->version.stlink == 1) {
692 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK) {
693 /* check csw status */
694 if (h->cmdbuf[12] == 1) {
695 LOG_DEBUG("get sense");
696 if (stlink_usb_xfer_v1_get_sense(handle) != ERROR_OK)
707 Converts an STLINK status code held in the first byte of a response
708 to an openocd error, logs any error/wait status as debug output.
710 static int stlink_usb_error_check(void *handle)
712 struct stlink_usb_handle_s *h = handle;
714 assert(handle != NULL);
716 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
717 switch (h->databuf[0]) {
718 case STLINK_SWIM_ERR_OK:
720 case STLINK_SWIM_BUSY:
723 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
728 /* TODO: no error checking yet on api V1 */
729 if (h->version.jtag_api == STLINK_JTAG_API_V1)
730 h->databuf[0] = STLINK_DEBUG_ERR_OK;
732 switch (h->databuf[0]) {
733 case STLINK_DEBUG_ERR_OK:
735 case STLINK_DEBUG_ERR_FAULT:
736 LOG_DEBUG("SWD fault response (0x%x)", STLINK_DEBUG_ERR_FAULT);
738 case STLINK_SWD_AP_WAIT:
739 LOG_DEBUG("wait status SWD_AP_WAIT (0x%x)", STLINK_SWD_AP_WAIT);
741 case STLINK_SWD_DP_WAIT:
742 LOG_DEBUG("wait status SWD_DP_WAIT (0x%x)", STLINK_SWD_DP_WAIT);
744 case STLINK_JTAG_GET_IDCODE_ERROR:
745 LOG_DEBUG("STLINK_JTAG_GET_IDCODE_ERROR");
747 case STLINK_JTAG_WRITE_ERROR:
748 LOG_DEBUG("Write error");
750 case STLINK_JTAG_WRITE_VERIF_ERROR:
751 LOG_DEBUG("Write verify error, ignoring");
753 case STLINK_SWD_AP_FAULT:
754 /* git://git.ac6.fr/openocd commit 657e3e885b9ee10
755 * returns ERROR_OK with the comment:
756 * Change in error status when reading outside RAM.
757 * This fix allows CDT plugin to visualize memory.
759 LOG_DEBUG("STLINK_SWD_AP_FAULT");
761 case STLINK_SWD_AP_ERROR:
762 LOG_DEBUG("STLINK_SWD_AP_ERROR");
764 case STLINK_SWD_AP_PARITY_ERROR:
765 LOG_DEBUG("STLINK_SWD_AP_PARITY_ERROR");
767 case STLINK_SWD_DP_FAULT:
768 LOG_DEBUG("STLINK_SWD_DP_FAULT");
770 case STLINK_SWD_DP_ERROR:
771 LOG_DEBUG("STLINK_SWD_DP_ERROR");
773 case STLINK_SWD_DP_PARITY_ERROR:
774 LOG_DEBUG("STLINK_SWD_DP_PARITY_ERROR");
776 case STLINK_SWD_AP_WDATA_ERROR:
777 LOG_DEBUG("STLINK_SWD_AP_WDATA_ERROR");
779 case STLINK_SWD_AP_STICKY_ERROR:
780 LOG_DEBUG("STLINK_SWD_AP_STICKY_ERROR");
782 case STLINK_SWD_AP_STICKYORUN_ERROR:
783 LOG_DEBUG("STLINK_SWD_AP_STICKYORUN_ERROR");
785 case STLINK_BAD_AP_ERROR:
786 LOG_DEBUG("STLINK_BAD_AP_ERROR");
789 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
795 * Wrapper around stlink_usb_xfer_noerrcheck()
796 * to check the error code in the received packet
798 static int stlink_usb_xfer_errcheck(void *handle, const uint8_t *buf, int size)
804 retval = stlink_usb_xfer_noerrcheck(handle, buf, size);
805 if (retval != ERROR_OK)
808 return stlink_usb_error_check(handle);
811 /** Issue an STLINK command via USB transfer, with retries on any wait status responses.
813 Works for commands where the STLINK_DEBUG status is returned in the first
814 byte of the response packet. For SWIM a SWIM_READSTATUS is requested instead.
816 Returns an openocd result code.
818 static int stlink_cmd_allow_retry(void *handle, const uint8_t *buf, int size)
822 struct stlink_usb_handle_s *h = handle;
825 if ((h->st_mode != STLINK_MODE_DEBUG_SWIM) || !retries) {
826 res = stlink_usb_xfer_noerrcheck(handle, buf, size);
831 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
832 res = stlink_swim_status(handle);
837 res = stlink_usb_error_check(handle);
838 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
839 unsigned int delay_us = (1<<retries++) * 1000;
840 LOG_DEBUG("stlink_cmd_allow_retry ERROR_WAIT, retry %d, delaying %u microseconds", retries, delay_us);
849 static int stlink_usb_read_trace(void *handle, const uint8_t *buf, int size)
851 struct stlink_usb_handle_s *h = handle;
854 assert(handle != NULL);
856 assert(h->version.flags & STLINK_F_HAS_TRACE);
858 ret = jtag_libusb_bulk_read(h->fd, h->trace_ep, (char *)buf, size,
859 STLINK_READ_TIMEOUT, &tr);
860 if (ret || tr != size) {
861 LOG_ERROR("bulk trace read failed");
869 this function writes transfer length in
870 the right place in the cb
872 static void stlink_usb_set_cbw_transfer_datalength(void *handle, uint32_t size)
874 struct stlink_usb_handle_s *h = handle;
876 buf_set_u32(h->cmdbuf+8, 0, 32, size);
879 static void stlink_usb_xfer_v1_create_cmd(void *handle, uint8_t direction, uint32_t size)
881 struct stlink_usb_handle_s *h = handle;
883 /* fill the send buffer */
884 strcpy((char *)h->cmdbuf, "USBC");
886 /* csw tag not used */
887 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, 0);
889 /* cbw data transfer length (in the following data phase in or out) */
890 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, size);
893 h->cmdbuf[h->cmdidx++] = (direction == h->rx_ep ? ENDPOINT_IN : ENDPOINT_OUT);
894 h->cmdbuf[h->cmdidx++] = 0; /* lun */
895 /* cdb clength (is filled in at xfer) */
896 h->cmdbuf[h->cmdidx++] = 0;
900 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size)
902 struct stlink_usb_handle_s *h = handle;
904 h->direction = direction;
908 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
909 memset(h->databuf, 0, STLINK_DATA_SIZE);
911 if (h->version.stlink == 1)
912 stlink_usb_xfer_v1_create_cmd(handle, direction, size);
916 static int stlink_usb_version(void *handle)
921 uint8_t v, x, y, jtag, swim, msd, bridge = 0;
922 char v_str[5 * (1 + 3) + 1]; /* VvJjMmBbSs */
924 struct stlink_usb_handle_s *h = handle;
926 assert(handle != NULL);
928 stlink_usb_init_buffer(handle, h->rx_ep, 6);
930 h->cmdbuf[h->cmdidx++] = STLINK_GET_VERSION;
932 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 6);
937 version = be_to_h_u16(h->databuf);
938 v = (version >> 12) & 0x0f;
939 x = (version >> 6) & 0x3f;
942 h->vid = le_to_h_u16(h->databuf + 2);
943 h->pid = le_to_h_u16(h->databuf + 4);
946 case STLINK_V2_1_PID:
947 case STLINK_V2_1_NO_MSD_PID:
948 if ((x <= 22 && y == 7) || (x >= 25 && y >= 7 && y <= 12)) {
949 /* MxSy : STM8 V2.1 - SWIM only */
954 /* JxMy : STM32 V2.1 - JTAG/SWD only */
967 /* STLINK-V3 requires a specific command */
968 if (v == 3 && x == 0 && y == 0) {
969 stlink_usb_init_buffer(handle, h->rx_ep, 16);
971 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_VERSION_EX;
973 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 12);
978 swim = h->databuf[1];
979 jtag = h->databuf[2];
981 bridge = h->databuf[4];
982 h->vid = le_to_h_u16(h->databuf + 8);
983 h->pid = le_to_h_u16(h->databuf + 10);
986 h->version.stlink = v;
987 h->version.jtag = jtag;
988 h->version.swim = swim;
991 switch (h->version.stlink) {
993 /* ST-LINK/V1 from J11 switch to api-v2 (and support SWD) */
994 if (h->version.jtag >= 11)
995 h->version.jtag_api = STLINK_JTAG_API_V2;
997 h->version.jtag_api = STLINK_JTAG_API_V1;
1001 /* all ST-LINK/V2 and ST-Link/V2.1 use api-v2 */
1002 h->version.jtag_api = STLINK_JTAG_API_V2;
1004 /* API for trace from J13 */
1005 /* API for target voltage from J13 */
1006 if (h->version.jtag >= 13)
1007 flags |= STLINK_F_HAS_TRACE;
1009 /* preferred API to get last R/W status from J15 */
1010 if (h->version.jtag >= 15)
1011 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1013 /* API to set SWD frequency from J22 */
1014 if (h->version.jtag >= 22)
1015 flags |= STLINK_F_HAS_SWD_SET_FREQ;
1017 /* API to set JTAG frequency from J24 */
1018 /* API to access DAP registers from J24 */
1019 if (h->version.jtag >= 24) {
1020 flags |= STLINK_F_HAS_JTAG_SET_FREQ;
1021 flags |= STLINK_F_HAS_DAP_REG;
1024 /* Quirk for read DP in JTAG mode (V2 only) from J24, fixed in J32 */
1025 if (h->version.jtag >= 24 && h->version.jtag < 32)
1026 flags |= STLINK_F_QUIRK_JTAG_DP_READ;
1028 /* API to read/write memory at 16 bit from J26 */
1029 if (h->version.jtag >= 26)
1030 flags |= STLINK_F_HAS_MEM_16BIT;
1032 /* API required to init AP before any AP access from J28 */
1033 if (h->version.jtag >= 28)
1034 flags |= STLINK_F_HAS_AP_INIT;
1036 /* API required to return proper error code on close AP from J29 */
1037 if (h->version.jtag >= 29)
1038 flags |= STLINK_F_FIX_CLOSE_AP;
1040 /* Banked regs (DPv1 & DPv2) support from V2J32 */
1041 if (h->version.jtag >= 32)
1042 flags |= STLINK_F_HAS_DPBANKSEL;
1046 /* all STLINK-V3 use api-v3 */
1047 h->version.jtag_api = STLINK_JTAG_API_V3;
1049 /* STLINK-V3 is a superset of ST-LINK/V2 */
1052 /* API for target voltage */
1053 flags |= STLINK_F_HAS_TRACE;
1055 /* preferred API to get last R/W status */
1056 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1058 /* API to access DAP registers */
1059 flags |= STLINK_F_HAS_DAP_REG;
1061 /* API to read/write memory at 16 bit */
1062 flags |= STLINK_F_HAS_MEM_16BIT;
1064 /* API required to init AP before any AP access */
1065 flags |= STLINK_F_HAS_AP_INIT;
1067 /* API required to return proper error code on close AP */
1068 flags |= STLINK_F_FIX_CLOSE_AP;
1070 /* Banked regs (DPv1 & DPv2) support from V3J2 */
1071 if (h->version.jtag >= 2)
1072 flags |= STLINK_F_HAS_DPBANKSEL;
1074 /* 8bit read/write max packet size 512 bytes from V3J6 */
1075 if (h->version.jtag >= 6)
1076 flags |= STLINK_F_HAS_RW8_512BYTES;
1082 h->version.flags = flags;
1085 p += sprintf(p, "V%d", v);
1087 p += sprintf(p, "J%d", jtag);
1089 p += sprintf(p, "M%d", msd);
1091 p += sprintf(p, "B%d", bridge);
1093 sprintf(p, "S%d", swim);
1095 LOG_INFO("STLINK %s (API v%d) VID:PID %04X:%04X",
1097 h->version.jtag_api,
1104 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
1106 struct stlink_usb_handle_s *h = handle;
1107 uint32_t adc_results[2];
1109 /* no error message, simply quit with error */
1110 if (!(h->version.flags & STLINK_F_HAS_TARGET_VOLT))
1111 return ERROR_COMMAND_NOTFOUND;
1113 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1115 h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
1117 int result = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1119 if (result != ERROR_OK)
1122 /* convert result */
1123 adc_results[0] = le_to_h_u32(h->databuf);
1124 adc_results[1] = le_to_h_u32(h->databuf + 4);
1126 *target_voltage = 0;
1129 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
1131 LOG_INFO("Target voltage: %f", (double)*target_voltage);
1136 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
1138 struct stlink_usb_handle_s *h = handle;
1140 assert(handle != NULL);
1142 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
1143 return ERROR_COMMAND_NOTFOUND;
1145 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1147 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1148 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
1149 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1152 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1154 if (result != ERROR_OK)
1160 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
1162 struct stlink_usb_handle_s *h = handle;
1164 assert(handle != NULL);
1166 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
1167 return ERROR_COMMAND_NOTFOUND;
1169 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1171 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1172 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
1173 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1176 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1178 if (result != ERROR_OK)
1185 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
1188 struct stlink_usb_handle_s *h = handle;
1190 assert(handle != NULL);
1192 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1194 h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
1196 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1198 if (res != ERROR_OK)
1201 *mode = h->databuf[0];
1207 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
1210 struct stlink_usb_handle_s *h = handle;
1212 assert(handle != NULL);
1214 /* on api V2 we are able the read the latest command
1216 * TODO: we need the test on api V1 too
1218 if (h->version.jtag_api != STLINK_JTAG_API_V1)
1221 stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
1224 case STLINK_MODE_DEBUG_JTAG:
1225 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1226 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1227 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1229 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1230 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG_NO_RESET;
1232 case STLINK_MODE_DEBUG_SWD:
1233 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1234 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1235 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1237 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1238 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD_NO_RESET;
1240 case STLINK_MODE_DEBUG_SWIM:
1241 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1242 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
1243 /* swim enter does not return any response or status */
1244 return stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1245 case STLINK_MODE_DFU:
1246 case STLINK_MODE_MASS:
1251 return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
1255 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
1258 struct stlink_usb_handle_s *h = handle;
1260 assert(handle != NULL);
1262 /* command with no reply, use a valid endpoint but zero size */
1263 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1266 case STLINK_MODE_DEBUG_JTAG:
1267 case STLINK_MODE_DEBUG_SWD:
1268 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1269 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
1271 case STLINK_MODE_DEBUG_SWIM:
1272 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1273 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
1275 case STLINK_MODE_DFU:
1276 h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
1277 h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
1279 case STLINK_MODE_MASS:
1284 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1286 if (res != ERROR_OK)
1292 static int stlink_usb_assert_srst(void *handle, int srst);
1294 static enum stlink_mode stlink_get_mode(enum hl_transports t)
1297 case HL_TRANSPORT_SWD:
1298 return STLINK_MODE_DEBUG_SWD;
1299 case HL_TRANSPORT_JTAG:
1300 return STLINK_MODE_DEBUG_JTAG;
1302 return STLINK_MODE_UNKNOWN;
1307 static int stlink_usb_exit_mode(void *handle)
1311 enum stlink_mode emode;
1313 assert(handle != NULL);
1315 res = stlink_usb_current_mode(handle, &mode);
1317 if (res != ERROR_OK)
1320 LOG_DEBUG("MODE: 0x%02X", mode);
1322 /* try to exit current mode */
1324 case STLINK_DEV_DFU_MODE:
1325 emode = STLINK_MODE_DFU;
1327 case STLINK_DEV_DEBUG_MODE:
1328 emode = STLINK_MODE_DEBUG_SWD;
1330 case STLINK_DEV_SWIM_MODE:
1331 emode = STLINK_MODE_DEBUG_SWIM;
1333 case STLINK_DEV_BOOTLOADER_MODE:
1334 case STLINK_DEV_MASS_MODE:
1336 emode = STLINK_MODE_UNKNOWN;
1340 if (emode != STLINK_MODE_UNKNOWN)
1341 return stlink_usb_mode_leave(handle, emode);
1347 static int stlink_usb_init_mode(void *handle, bool connect_under_reset, int initial_interface_speed)
1351 enum stlink_mode emode;
1352 struct stlink_usb_handle_s *h = handle;
1354 assert(handle != NULL);
1356 res = stlink_usb_exit_mode(handle);
1357 if (res != ERROR_OK)
1360 res = stlink_usb_current_mode(handle, &mode);
1362 if (res != ERROR_OK)
1365 /* we check the target voltage here as an aid to debugging connection problems.
1366 * the stlink requires the target Vdd to be connected for reliable debugging.
1367 * this cmd is supported in all modes except DFU
1369 if (mode != STLINK_DEV_DFU_MODE) {
1371 float target_voltage;
1373 /* check target voltage (if supported) */
1374 res = stlink_usb_check_voltage(h, &target_voltage);
1376 if (res != ERROR_OK) {
1377 if (res != ERROR_COMMAND_NOTFOUND)
1378 LOG_ERROR("voltage check failed");
1379 /* attempt to continue as it is not a catastrophic failure */
1381 /* check for a sensible target voltage, operating range is 1.65-5.5v
1382 * according to datasheet */
1383 if (target_voltage < 1.5)
1384 LOG_ERROR("target voltage may be too low for reliable debugging");
1388 LOG_DEBUG("MODE: 0x%02X", mode);
1390 /* set selected mode */
1393 if (emode == STLINK_MODE_UNKNOWN) {
1394 LOG_ERROR("selected mode (transport) not supported");
1398 /* set the speed before entering the mode, as the chip discovery phase should be done at this speed too */
1399 if (emode == STLINK_MODE_DEBUG_JTAG) {
1400 if (h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ) {
1401 stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
1402 stlink_speed(h, initial_interface_speed, false);
1404 } else if (emode == STLINK_MODE_DEBUG_SWD) {
1405 if (h->version.flags & STLINK_F_HAS_SWD_SET_FREQ) {
1406 stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
1407 stlink_speed(h, initial_interface_speed, false);
1411 if (h->version.jtag_api == STLINK_JTAG_API_V3) {
1412 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
1414 stlink_get_com_freq(h, (emode == STLINK_MODE_DEBUG_JTAG), map);
1415 stlink_dump_speed_map(map, ARRAY_SIZE(map));
1416 stlink_speed(h, initial_interface_speed, false);
1419 /* preliminary SRST assert:
1420 * We want SRST is asserted before activating debug signals (mode_enter).
1421 * As the required mode has not been set, the adapter may not know what pin to use.
1422 * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
1423 * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
1424 * after power on, SWIM_RST stays unchanged */
1425 if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
1426 stlink_usb_assert_srst(handle, 0);
1427 /* do not check the return status here, we will
1428 proceed and enter the desired mode below
1429 and try asserting srst again. */
1431 res = stlink_usb_mode_enter(handle, emode);
1432 if (res != ERROR_OK)
1435 /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
1436 if (connect_under_reset) {
1437 res = stlink_usb_assert_srst(handle, 0);
1438 if (res != ERROR_OK)
1442 res = stlink_usb_current_mode(handle, &mode);
1444 if (res != ERROR_OK)
1447 LOG_DEBUG("MODE: 0x%02X", mode);
1452 /* request status from last swim request */
1453 static int stlink_swim_status(void *handle)
1455 struct stlink_usb_handle_s *h = handle;
1458 stlink_usb_init_buffer(handle, h->rx_ep, 4);
1459 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1460 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
1461 /* error is checked by the caller */
1462 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1463 if (res != ERROR_OK)
1468 the purpose of this function is unknown...
1469 capabilities? anyway for swim v6 it returns
1472 __attribute__((unused))
1473 static int stlink_swim_cap(void *handle, uint8_t *cap)
1475 struct stlink_usb_handle_s *h = handle;
1478 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1479 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1480 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1481 h->cmdbuf[h->cmdidx++] = 0x01;
1482 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1483 if (res != ERROR_OK)
1485 memcpy(cap, h->databuf, 8);
1489 /* debug dongle assert/deassert sreset line */
1490 static int stlink_swim_assert_reset(void *handle, int reset)
1492 struct stlink_usb_handle_s *h = handle;
1495 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1496 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1498 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1500 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1501 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1502 if (res != ERROR_OK)
1509 1.3ms low then 750Hz then 1.5kHz
1511 static int stlink_swim_enter(void *handle)
1513 struct stlink_usb_handle_s *h = handle;
1516 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1517 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1518 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1519 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1520 if (res != ERROR_OK)
1525 /* switch high/low speed swim */
1526 static int stlink_swim_speed(void *handle, int speed)
1528 struct stlink_usb_handle_s *h = handle;
1531 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1532 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1533 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1535 h->cmdbuf[h->cmdidx++] = 1;
1537 h->cmdbuf[h->cmdidx++] = 0;
1538 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1539 if (res != ERROR_OK)
1545 initiate srst from swim.
1546 nrst is pulled low for 50us.
1548 static int stlink_swim_generate_rst(void *handle)
1550 struct stlink_usb_handle_s *h = handle;
1553 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1554 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1555 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1556 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1557 if (res != ERROR_OK)
1563 send resynchronize sequence
1564 swim is pulled low for 16us
1565 reply is 64 clks low
1567 static int stlink_swim_resync(void *handle)
1569 struct stlink_usb_handle_s *h = handle;
1572 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1573 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1574 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_RESET;
1575 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1576 if (res != ERROR_OK)
1581 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1583 struct stlink_usb_handle_s *h = handle;
1586 unsigned int datalen = 0;
1587 int cmdsize = STLINK_CMD_SIZE_V2;
1589 if (len > STLINK_DATA_SIZE)
1592 if (h->version.stlink == 1)
1593 cmdsize = STLINK_SG_SIZE;
1595 stlink_usb_init_buffer(handle, h->tx_ep, 0);
1596 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1597 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1598 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1600 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1602 for (i = 0; i < len; i++) {
1603 if (h->cmdidx == cmdsize)
1604 h->databuf[datalen++] = *(data++);
1606 h->cmdbuf[h->cmdidx++] = *(data++);
1608 if (h->version.stlink == 1)
1609 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1611 res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1612 if (res != ERROR_OK)
1617 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1619 struct stlink_usb_handle_s *h = handle;
1622 if (len > STLINK_DATA_SIZE)
1625 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1626 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1627 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1628 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1630 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1632 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1633 if (res != ERROR_OK)
1636 stlink_usb_init_buffer(handle, h->rx_ep, len);
1637 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1638 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1639 res = stlink_usb_xfer_noerrcheck(handle, data, len);
1640 if (res != ERROR_OK)
1647 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1650 struct stlink_usb_handle_s *h = handle;
1652 assert(handle != NULL);
1654 /* there is no swim read core id cmd */
1655 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
1660 stlink_usb_init_buffer(handle, h->rx_ep, 12);
1662 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1663 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1664 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1666 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1669 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_IDCODES;
1671 res = stlink_usb_xfer_errcheck(handle, h->databuf, 12);
1675 if (res != ERROR_OK)
1678 *idcode = le_to_h_u32(h->databuf + offset);
1680 LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1685 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1687 struct stlink_usb_handle_s *h = handle;
1690 assert(handle != NULL);
1692 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1694 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1695 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1696 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1699 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1700 if (res != ERROR_OK)
1703 *val = le_to_h_u32(h->databuf + 4);
1707 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1709 struct stlink_usb_handle_s *h = handle;
1711 assert(handle != NULL);
1713 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1715 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1716 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1717 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1719 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1720 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1722 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1725 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1729 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1731 struct stlink_usb_handle_s *h = handle;
1733 assert(handle != NULL);
1735 if (h->trace.enabled && (h->version.flags & STLINK_F_HAS_TRACE)) {
1738 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1740 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1741 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1743 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1744 if (res != ERROR_OK)
1747 size_t bytes_avail = le_to_h_u16(h->databuf);
1748 *size = bytes_avail < *size ? bytes_avail : *size - 1;
1751 res = stlink_usb_read_trace(handle, buf, *size);
1752 if (res != ERROR_OK)
1761 static enum target_state stlink_usb_v2_get_status(void *handle)
1766 result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1767 if (result != ERROR_OK)
1768 return TARGET_UNKNOWN;
1770 if (status & S_HALT)
1771 return TARGET_HALTED;
1772 else if (status & S_RESET_ST)
1773 return TARGET_RESET;
1775 return TARGET_RUNNING;
1779 static enum target_state stlink_usb_state(void *handle)
1782 struct stlink_usb_handle_s *h = handle;
1784 assert(handle != NULL);
1786 if (h->reconnect_pending) {
1787 LOG_INFO("Previous state query failed, trying to reconnect");
1788 res = stlink_usb_mode_enter(handle, h->st_mode);
1789 if (res != ERROR_OK)
1790 return TARGET_UNKNOWN;
1792 h->reconnect_pending = false;
1795 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1796 res = stlink_usb_v2_get_status(handle);
1797 if (res == TARGET_UNKNOWN)
1798 h->reconnect_pending = true;
1802 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1804 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1805 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
1807 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1809 if (res != ERROR_OK)
1810 return TARGET_UNKNOWN;
1812 if (h->databuf[0] == STLINK_CORE_RUNNING)
1813 return TARGET_RUNNING;
1814 if (h->databuf[0] == STLINK_CORE_HALTED)
1815 return TARGET_HALTED;
1817 h->reconnect_pending = true;
1819 return TARGET_UNKNOWN;
1822 static int stlink_usb_assert_srst(void *handle, int srst)
1824 struct stlink_usb_handle_s *h = handle;
1826 assert(handle != NULL);
1828 if (h->st_mode == STLINK_MODE_DEBUG_SWIM)
1829 return stlink_swim_assert_reset(handle, srst);
1831 if (h->version.stlink == 1)
1832 return ERROR_COMMAND_NOTFOUND;
1834 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1836 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1837 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
1838 h->cmdbuf[h->cmdidx++] = srst;
1840 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1844 static void stlink_usb_trace_disable(void *handle)
1847 struct stlink_usb_handle_s *h = handle;
1849 assert(handle != NULL);
1851 assert(h->version.flags & STLINK_F_HAS_TRACE);
1853 LOG_DEBUG("Tracing: disable");
1855 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1856 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1857 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
1858 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1860 if (res == ERROR_OK)
1861 h->trace.enabled = false;
1866 static int stlink_usb_trace_enable(void *handle)
1869 struct stlink_usb_handle_s *h = handle;
1871 assert(handle != NULL);
1873 if (h->version.flags & STLINK_F_HAS_TRACE) {
1874 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1876 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1877 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
1878 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
1880 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
1883 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1885 if (res == ERROR_OK) {
1886 h->trace.enabled = true;
1887 LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
1890 LOG_ERROR("Tracing is not supported by this version.");
1898 static int stlink_usb_reset(void *handle)
1900 struct stlink_usb_handle_s *h = handle;
1903 assert(handle != NULL);
1905 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1907 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1909 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1910 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
1912 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
1914 retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
1915 if (retval != ERROR_OK)
1918 if (h->trace.enabled) {
1919 stlink_usb_trace_disable(h);
1920 return stlink_usb_trace_enable(h);
1927 static int stlink_usb_run(void *handle)
1930 struct stlink_usb_handle_s *h = handle;
1932 assert(handle != NULL);
1934 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1935 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
1940 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1942 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1943 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
1945 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1949 static int stlink_usb_halt(void *handle)
1952 struct stlink_usb_handle_s *h = handle;
1954 assert(handle != NULL);
1956 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1957 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1962 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1964 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1965 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
1967 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1971 static int stlink_usb_step(void *handle)
1973 struct stlink_usb_handle_s *h = handle;
1975 assert(handle != NULL);
1977 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1978 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
1979 * that the Cortex-M3 currently does. */
1980 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
1981 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
1982 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1985 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1987 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1988 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
1990 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1994 static int stlink_usb_read_regs(void *handle)
1997 struct stlink_usb_handle_s *h = handle;
1999 assert(handle != NULL);
2001 stlink_usb_init_buffer(handle, h->rx_ep, 88);
2003 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2004 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2006 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
2007 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 84);
2008 /* regs data from offset 0 */
2010 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
2011 res = stlink_usb_xfer_errcheck(handle, h->databuf, 88);
2012 /* status at offset 0, regs data from offset 4 */
2019 static int stlink_usb_read_reg(void *handle, int num, uint32_t *val)
2022 struct stlink_usb_handle_s *h = handle;
2024 assert(handle != NULL);
2026 stlink_usb_init_buffer(handle, h->rx_ep, h->version.jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
2028 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2029 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2030 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
2032 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
2033 h->cmdbuf[h->cmdidx++] = num;
2035 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2036 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
2037 if (res != ERROR_OK)
2039 *val = le_to_h_u32(h->databuf);
2042 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
2043 if (res != ERROR_OK)
2045 *val = le_to_h_u32(h->databuf + 4);
2051 static int stlink_usb_write_reg(void *handle, int num, uint32_t val)
2053 struct stlink_usb_handle_s *h = handle;
2055 assert(handle != NULL);
2057 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2059 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2060 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2061 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
2063 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
2064 h->cmdbuf[h->cmdidx++] = num;
2065 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
2068 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2071 static int stlink_usb_get_rw_status(void *handle)
2073 struct stlink_usb_handle_s *h = handle;
2075 assert(handle != NULL);
2077 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2080 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2082 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2083 if (h->version.flags & STLINK_F_HAS_GETLASTRWSTATUS2) {
2084 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS2;
2085 return stlink_usb_xfer_errcheck(handle, h->databuf, 12);
2087 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
2088 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2093 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
2097 uint16_t read_len = len;
2098 struct stlink_usb_handle_s *h = handle;
2100 assert(handle != NULL);
2102 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2103 if (len > stlink_usb_block(h)) {
2104 LOG_DEBUG("max buffer (%d) length exceeded", stlink_usb_block(h));
2108 stlink_usb_init_buffer(handle, h->rx_ep, read_len);
2110 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2111 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
2112 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2114 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2117 /* we need to fix read length for single bytes */
2121 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, read_len);
2123 if (res != ERROR_OK)
2126 memcpy(buffer, h->databuf, len);
2128 return stlink_usb_get_rw_status(handle);
2132 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
2133 const uint8_t *buffer)
2136 struct stlink_usb_handle_s *h = handle;
2138 assert(handle != NULL);
2140 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2141 if (len > stlink_usb_block(h)) {
2142 LOG_DEBUG("max buffer length (%d) exceeded", stlink_usb_block(h));
2146 stlink_usb_init_buffer(handle, h->tx_ep, len);
2148 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2149 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
2150 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2152 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2155 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2157 if (res != ERROR_OK)
2160 return stlink_usb_get_rw_status(handle);
2164 static int stlink_usb_read_mem16(void *handle, uint32_t addr, uint16_t len,
2168 struct stlink_usb_handle_s *h = handle;
2170 assert(handle != NULL);
2172 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2173 return ERROR_COMMAND_NOTFOUND;
2175 /* data must be a multiple of 2 and half-word aligned */
2176 if (len % 2 || addr % 2) {
2177 LOG_DEBUG("Invalid data alignment");
2178 return ERROR_TARGET_UNALIGNED_ACCESS;
2181 stlink_usb_init_buffer(handle, h->rx_ep, len);
2183 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2184 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READMEM_16BIT;
2185 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2187 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2190 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2192 if (res != ERROR_OK)
2195 memcpy(buffer, h->databuf, len);
2197 return stlink_usb_get_rw_status(handle);
2201 static int stlink_usb_write_mem16(void *handle, uint32_t addr, uint16_t len,
2202 const uint8_t *buffer)
2205 struct stlink_usb_handle_s *h = handle;
2207 assert(handle != NULL);
2209 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2210 return ERROR_COMMAND_NOTFOUND;
2212 /* data must be a multiple of 2 and half-word aligned */
2213 if (len % 2 || addr % 2) {
2214 LOG_DEBUG("Invalid data alignment");
2215 return ERROR_TARGET_UNALIGNED_ACCESS;
2218 stlink_usb_init_buffer(handle, h->tx_ep, len);
2220 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2221 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEMEM_16BIT;
2222 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2224 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2227 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2229 if (res != ERROR_OK)
2232 return stlink_usb_get_rw_status(handle);
2236 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
2240 struct stlink_usb_handle_s *h = handle;
2242 assert(handle != NULL);
2244 /* data must be a multiple of 4 and word aligned */
2245 if (len % 4 || addr % 4) {
2246 LOG_DEBUG("Invalid data alignment");
2247 return ERROR_TARGET_UNALIGNED_ACCESS;
2250 stlink_usb_init_buffer(handle, h->rx_ep, len);
2252 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2253 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
2254 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2256 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2259 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2261 if (res != ERROR_OK)
2264 memcpy(buffer, h->databuf, len);
2266 return stlink_usb_get_rw_status(handle);
2270 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
2271 const uint8_t *buffer)
2274 struct stlink_usb_handle_s *h = handle;
2276 assert(handle != NULL);
2278 /* data must be a multiple of 4 and word aligned */
2279 if (len % 4 || addr % 4) {
2280 LOG_DEBUG("Invalid data alignment");
2281 return ERROR_TARGET_UNALIGNED_ACCESS;
2284 stlink_usb_init_buffer(handle, h->tx_ep, len);
2286 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2287 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
2288 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2290 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2293 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2295 if (res != ERROR_OK)
2298 return stlink_usb_get_rw_status(handle);
2301 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
2303 uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
2304 if (max_tar_block == 0)
2306 return max_tar_block;
2309 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
2310 uint32_t count, uint8_t *buffer)
2312 int retval = ERROR_OK;
2313 uint32_t bytes_remaining;
2315 struct stlink_usb_handle_s *h = handle;
2317 /* calculate byte count */
2320 /* switch to 8 bit if stlink does not support 16 bit memory read */
2321 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2326 bytes_remaining = (size != 1) ?
2327 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2329 if (count < bytes_remaining)
2330 bytes_remaining = count;
2333 * all stlink support 8/32bit memory read/writes and only from
2334 * stlink V2J26 there is support for 16 bit memory read/write.
2335 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2340 /* When in jtag mode the stlink uses the auto-increment functionality.
2341 * However it expects us to pass the data correctly, this includes
2342 * alignment and any page boundaries. We already do this as part of the
2343 * adi_v5 implementation, but the stlink is a hla adapter and so this
2344 * needs implementing manually.
2345 * currently this only affects jtag mode, according to ST they do single
2346 * access in SWD mode - but this may change and so we do it for both modes */
2348 /* we first need to check for any unaligned bytes */
2349 if (addr & (size - 1)) {
2351 uint32_t head_bytes = size - (addr & (size - 1));
2352 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
2353 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2354 usleep((1<<retries++) * 1000);
2357 if (retval != ERROR_OK)
2359 buffer += head_bytes;
2361 count -= head_bytes;
2362 bytes_remaining -= head_bytes;
2365 if (bytes_remaining & (size - 1))
2366 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
2368 retval = stlink_usb_read_mem16(handle, addr, bytes_remaining, buffer);
2370 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
2372 retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
2374 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2375 usleep((1<<retries++) * 1000);
2378 if (retval != ERROR_OK)
2381 buffer += bytes_remaining;
2382 addr += bytes_remaining;
2383 count -= bytes_remaining;
2389 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
2390 uint32_t count, const uint8_t *buffer)
2392 int retval = ERROR_OK;
2393 uint32_t bytes_remaining;
2395 struct stlink_usb_handle_s *h = handle;
2397 /* calculate byte count */
2400 /* switch to 8 bit if stlink does not support 16 bit memory read */
2401 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2406 bytes_remaining = (size != 1) ?
2407 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2409 if (count < bytes_remaining)
2410 bytes_remaining = count;
2413 * all stlink support 8/32bit memory read/writes and only from
2414 * stlink V2J26 there is support for 16 bit memory read/write.
2415 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2420 /* When in jtag mode the stlink uses the auto-increment functionality.
2421 * However it expects us to pass the data correctly, this includes
2422 * alignment and any page boundaries. We already do this as part of the
2423 * adi_v5 implementation, but the stlink is a hla adapter and so this
2424 * needs implementing manually.
2425 * currently this only affects jtag mode, according to ST they do single
2426 * access in SWD mode - but this may change and so we do it for both modes */
2428 /* we first need to check for any unaligned bytes */
2429 if (addr & (size - 1)) {
2431 uint32_t head_bytes = size - (addr & (size - 1));
2432 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
2433 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2434 usleep((1<<retries++) * 1000);
2437 if (retval != ERROR_OK)
2439 buffer += head_bytes;
2441 count -= head_bytes;
2442 bytes_remaining -= head_bytes;
2445 if (bytes_remaining & (size - 1))
2446 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
2448 retval = stlink_usb_write_mem16(handle, addr, bytes_remaining, buffer);
2450 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
2453 retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
2454 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2455 usleep((1<<retries++) * 1000);
2458 if (retval != ERROR_OK)
2461 buffer += bytes_remaining;
2462 addr += bytes_remaining;
2463 count -= bytes_remaining;
2470 static int stlink_usb_override_target(const char *targetname)
2472 return !strcmp(targetname, "cortex_m");
2475 static int stlink_speed_swim(void *handle, int khz, bool query)
2480 we only have low and high speed...
2481 before changing speed the SWIM_CSR HS bit
2485 retval = stlink_swim_speed(handle, (khz < SWIM_FREQ_HIGH) ? 0 : 1);
2486 if (retval != ERROR_OK)
2487 LOG_ERROR("Unable to set adapter speed");
2490 return (khz < SWIM_FREQ_HIGH) ? SWIM_FREQ_LOW : SWIM_FREQ_HIGH;
2493 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
2496 int speed_index = -1;
2497 int speed_diff = INT_MAX;
2498 int last_valid_speed = -1;
2501 for (i = 0; i < map_size; i++) {
2504 last_valid_speed = i;
2505 if (khz == map[i].speed) {
2509 int current_diff = khz - map[i].speed;
2510 /* get abs value for comparison */
2511 current_diff = (current_diff > 0) ? current_diff : -current_diff;
2512 if ((current_diff < speed_diff) && khz >= map[i].speed) {
2513 speed_diff = current_diff;
2519 if (speed_index == -1) {
2520 /* this will only be here if we cannot match the slow speed.
2521 * use the slowest speed we support.*/
2522 speed_index = last_valid_speed;
2524 } else if (i == map_size)
2527 if (!match && query) {
2528 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz",
2529 khz, map[speed_index].speed);
2535 static int stlink_speed_swd(void *handle, int khz, bool query)
2538 struct stlink_usb_handle_s *h = handle;
2540 /* old firmware cannot change it */
2541 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
2544 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
2545 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
2548 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
2549 if (result != ERROR_OK) {
2550 LOG_ERROR("Unable to set adapter speed");
2555 return stlink_khz_to_speed_map_swd[speed_index].speed;
2558 static int stlink_speed_jtag(void *handle, int khz, bool query)
2561 struct stlink_usb_handle_s *h = handle;
2563 /* old firmware cannot change it */
2564 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
2567 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2568 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2571 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2572 if (result != ERROR_OK) {
2573 LOG_ERROR("Unable to set adapter speed");
2578 return stlink_khz_to_speed_map_jtag[speed_index].speed;
2581 static void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2585 LOG_DEBUG("Supported clock speeds are:");
2586 for (i = 0; i < map_size; i++)
2588 LOG_DEBUG("%d kHz", map[i].speed);
2591 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map)
2593 struct stlink_usb_handle_s *h = handle;
2596 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2597 LOG_ERROR("Unknown command");
2601 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2603 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2604 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_COM_FREQ;
2605 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2607 int res = stlink_usb_xfer_errcheck(handle, h->databuf, 52);
2609 int size = h->databuf[8];
2611 if (size > STLINK_V3_MAX_FREQ_NB)
2612 size = STLINK_V3_MAX_FREQ_NB;
2614 for (i = 0; i < size; i++) {
2615 map[i].speed = le_to_h_u32(&h->databuf[12 + 4 * i]);
2616 map[i].speed_divisor = i;
2619 /* set to zero all the next entries */
2620 for (i = size; i < STLINK_V3_MAX_FREQ_NB; i++)
2626 static int stlink_set_com_freq(void *handle, bool is_jtag, unsigned int frequency)
2628 struct stlink_usb_handle_s *h = handle;
2630 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2631 LOG_ERROR("Unknown command");
2635 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2637 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2638 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_SET_COM_FREQ;
2639 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2640 h->cmdbuf[h->cmdidx++] = 0;
2642 h_u32_to_le(&h->cmdbuf[4], frequency);
2644 return stlink_usb_xfer_errcheck(handle, h->databuf, 8);
2647 static int stlink_speed_v3(void *handle, bool is_jtag, int khz, bool query)
2649 struct stlink_usb_handle_s *h = handle;
2651 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
2653 stlink_get_com_freq(h, is_jtag, map);
2655 speed_index = stlink_match_speed_map(map, ARRAY_SIZE(map), khz, query);
2658 int result = stlink_set_com_freq(h, is_jtag, map[speed_index].speed);
2659 if (result != ERROR_OK) {
2660 LOG_ERROR("Unable to set adapter speed");
2664 return map[speed_index].speed;
2667 static int stlink_speed(void *handle, int khz, bool query)
2669 struct stlink_usb_handle_s *h = handle;
2674 switch (h->st_mode) {
2675 case STLINK_MODE_DEBUG_SWIM:
2676 return stlink_speed_swim(handle, khz, query);
2677 case STLINK_MODE_DEBUG_SWD:
2678 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2679 return stlink_speed_v3(handle, false, khz, query);
2681 return stlink_speed_swd(handle, khz, query);
2683 case STLINK_MODE_DEBUG_JTAG:
2684 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2685 return stlink_speed_v3(handle, true, khz, query);
2687 return stlink_speed_jtag(handle, khz, query);
2697 static int stlink_usb_close(void *handle)
2699 struct stlink_usb_handle_s *h = handle;
2702 stlink_usb_exit_mode(h);
2703 /* do not check return code, it prevent
2704 us from closing jtag_libusb */
2705 jtag_libusb_close(h->fd);
2713 /* Compute ST-Link serial number from the device descriptor
2714 * this function will help to work-around a bug in old ST-Link/V2 DFU
2715 * the buggy DFU returns an incorrect serial in the USB descriptor
2716 * example for the following serial "57FF72067265575742132067"
2717 * - the correct descriptor serial is:
2718 * 0x32, 0x03, 0x35, 0x00, 0x37, 0x00, 0x46, 0x00, 0x46, 0x00, 0x37, 0x00, 0x32, 0x00 ...
2719 * this contains the length (0x32 = 50), the type (0x3 = DT_STRING) and the serial in unicode format
2720 * the serial part is: 0x0035, 0x0037, 0x0046, 0x0046, 0x0037, 0x0032 ... >> 57FF72 ...
2721 * this format could be read correctly by 'libusb_get_string_descriptor_ascii'
2722 * so this case is managed by libusb_helper::string_descriptor_equal
2723 * - the buggy DFU is not doing any unicode conversion and returns a raw serial data in the descriptor
2724 * 0x1a, 0x03, 0x57, 0x00, 0xFF, 0x00, 0x72, 0x00 ...
2726 * based on the length (0x1a = 26) we could easily decide if we have to fixup the serial
2727 * and then we have just to convert the raw data into printable characters using sprintf
2729 static char *stlink_usb_get_alternate_serial(libusb_device_handle *device,
2730 struct libusb_device_descriptor *dev_desc)
2733 unsigned char desc_serial[(STLINK_SERIAL_LEN + 1) * 2];
2735 if (dev_desc->iSerialNumber == 0)
2738 /* get the LANGID from String Descriptor Zero */
2739 usb_retval = libusb_get_string_descriptor(device, 0, 0, desc_serial,
2740 sizeof(desc_serial));
2742 if (usb_retval < LIBUSB_SUCCESS) {
2743 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
2744 libusb_error_name(usb_retval), usb_retval);
2746 } else if (usb_retval < 4) {
2747 /* the size should be least 4 bytes to contain a minimum of 1 supported LANGID */
2748 LOG_ERROR("could not get the LANGID");
2752 uint32_t langid = desc_serial[2] | (desc_serial[3] << 8);
2754 /* get the serial */
2755 usb_retval = libusb_get_string_descriptor(device, dev_desc->iSerialNumber,
2756 langid, desc_serial, sizeof(desc_serial));
2758 unsigned char len = desc_serial[0];
2760 if (usb_retval < LIBUSB_SUCCESS) {
2761 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
2762 libusb_error_name(usb_retval), usb_retval);
2764 } else if (desc_serial[1] != LIBUSB_DT_STRING || len > usb_retval) {
2765 LOG_ERROR("invalid string in ST-LINK USB serial descriptor");
2769 if (len == ((STLINK_SERIAL_LEN + 1) * 2)) {
2770 /* good ST-Link adapter, this case is managed by
2771 * libusb::libusb_get_string_descriptor_ascii */
2773 } else if (len != ((STLINK_SERIAL_LEN / 2 + 1) * 2)) {
2774 LOG_ERROR("unexpected serial length (%d) in descriptor", len);
2778 /* else (len == 26) => buggy ST-Link */
2780 char *alternate_serial = malloc((STLINK_SERIAL_LEN + 1) * sizeof(char));
2781 if (alternate_serial == NULL)
2784 for (unsigned int i = 0; i < STLINK_SERIAL_LEN; i += 2)
2785 sprintf(alternate_serial + i, "%02X", desc_serial[i + 2]);
2787 alternate_serial[STLINK_SERIAL_LEN] = '\0';
2789 return alternate_serial;
2793 static int stlink_usb_open(struct hl_interface_param_s *param, enum stlink_mode mode, void **fd)
2795 int err, retry_count = 1;
2796 struct stlink_usb_handle_s *h;
2798 LOG_DEBUG("stlink_usb_open");
2800 h = calloc(1, sizeof(struct stlink_usb_handle_s));
2803 LOG_DEBUG("malloc failed");
2809 for (unsigned i = 0; param->vid[i]; i++) {
2810 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
2811 h->st_mode, param->vid[i], param->pid[i],
2812 param->serial ? param->serial : "");
2816 On certain host USB configurations(e.g. MacBook Air)
2817 STLINKv2 dongle seems to have its FW in a funky state if,
2818 after plugging it in, you try to use openocd with it more
2819 then once (by launching and closing openocd). In cases like
2820 that initial attempt to read the FW info via
2821 stlink_usb_version will fail and the device has to be reset
2822 in order to become operational.
2825 if (jtag_libusb_open(param->vid, param->pid, param->serial,
2826 &h->fd, stlink_usb_get_alternate_serial) != ERROR_OK) {
2827 LOG_ERROR("open failed");
2831 jtag_libusb_set_configuration(h->fd, 0);
2833 if (libusb_claim_interface(h->fd, 0) != ERROR_OK) {
2834 LOG_DEBUG("claim interface failed");
2838 /* RX EP is common for all versions */
2839 h->rx_ep = STLINK_RX_EP;
2842 if (jtag_libusb_get_pid(libusb_get_device(h->fd), &pid) != ERROR_OK) {
2843 LOG_DEBUG("libusb_get_pid failed");
2847 /* wrap version for first read */
2850 h->version.stlink = 1;
2851 h->tx_ep = STLINK_TX_EP;
2853 case STLINK_V3_USBLOADER_PID:
2854 case STLINK_V3E_PID:
2855 case STLINK_V3S_PID:
2856 case STLINK_V3_2VCP_PID:
2857 h->version.stlink = 3;
2858 h->tx_ep = STLINK_V2_1_TX_EP;
2859 h->trace_ep = STLINK_V2_1_TRACE_EP;
2861 case STLINK_V2_1_PID:
2862 case STLINK_V2_1_NO_MSD_PID:
2863 h->version.stlink = 2;
2864 h->tx_ep = STLINK_V2_1_TX_EP;
2865 h->trace_ep = STLINK_V2_1_TRACE_EP;
2868 /* fall through - we assume V2 to be the default version*/
2870 h->version.stlink = 2;
2871 h->tx_ep = STLINK_TX_EP;
2872 h->trace_ep = STLINK_TRACE_EP;
2876 /* get the device version */
2877 err = stlink_usb_version(h);
2879 if (err == ERROR_OK) {
2881 } else if (h->version.stlink == 1 ||
2883 LOG_ERROR("read version failed");
2886 err = libusb_release_interface(h->fd, 0);
2887 if (err != ERROR_OK) {
2888 LOG_ERROR("release interface failed");
2892 err = libusb_reset_device(h->fd);
2893 if (err != ERROR_OK) {
2894 LOG_ERROR("reset device failed");
2898 jtag_libusb_close(h->fd);
2900 Give the device one second to settle down and
2903 usleep(1 * 1000 * 1000);
2908 /* check if mode is supported */
2911 switch (h->st_mode) {
2912 case STLINK_MODE_DEBUG_SWD:
2913 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2916 case STLINK_MODE_DEBUG_JTAG:
2917 if (h->version.jtag == 0)
2920 case STLINK_MODE_DEBUG_SWIM:
2921 if (h->version.swim == 0)
2929 if (err != ERROR_OK) {
2930 LOG_ERROR("mode (transport) not supported by device");
2934 /* initialize the debug hardware */
2935 err = stlink_usb_init_mode(h, param->connect_under_reset, param->initial_interface_speed);
2937 if (err != ERROR_OK) {
2938 LOG_ERROR("init mode failed (unable to connect to the target)");
2942 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
2943 err = stlink_swim_enter(h);
2944 if (err != ERROR_OK) {
2945 LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
2949 h->max_mem_packet = STLINK_DATA_SIZE;
2953 /* get cpuid, so we can determine the max page size
2954 * start with a safe default */
2955 h->max_mem_packet = (1 << 10);
2958 stlink_usb_open_ap(h, 0);
2959 err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
2960 if (err == ERROR_OK) {
2961 uint32_t cpuid = le_to_h_u32(buffer);
2962 int i = (cpuid >> 4) & 0xf;
2963 if (i == 4 || i == 3) {
2964 /* Cortex-M3/M4 has 4096 bytes autoincrement range */
2965 h->max_mem_packet = (1 << 12);
2969 LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
2976 stlink_usb_close(h);
2981 static int stlink_usb_hl_open(struct hl_interface_param_s *param, void **fd)
2983 return stlink_usb_open(param, stlink_get_mode(param->transport), fd);
2986 static int stlink_config_trace(void *handle, bool enabled,
2987 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
2988 unsigned int *trace_freq, unsigned int traceclkin_freq,
2989 uint16_t *prescaler)
2991 struct stlink_usb_handle_s *h = handle;
2994 if (enabled && (!(h->version.flags & STLINK_F_HAS_TRACE) ||
2995 pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART)) {
2996 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
3000 unsigned int max_trace_freq = (h->version.stlink == 3) ?
3001 STLINK_V3_TRACE_MAX_HZ : STLINK_TRACE_MAX_HZ;
3003 /* Only concern ourselves with the frequency if the STlink is processing it. */
3004 if (enabled && *trace_freq > max_trace_freq) {
3005 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
3010 stlink_usb_trace_disable(h);
3013 *trace_freq = max_trace_freq;
3015 presc = traceclkin_freq / *trace_freq;
3017 if (traceclkin_freq % *trace_freq > 0)
3020 if (presc > TPIU_ACPR_MAX_SWOSCALER) {
3021 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
3031 h->trace.source_hz = *trace_freq;
3033 return stlink_usb_trace_enable(h);
3037 static int stlink_usb_init_access_port(void *handle, unsigned char ap_num)
3039 struct stlink_usb_handle_s *h = handle;
3041 assert(handle != NULL);
3043 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3044 return ERROR_COMMAND_NOTFOUND;
3046 LOG_DEBUG_IO("init ap_num = %d", ap_num);
3047 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3048 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3049 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_INIT_AP;
3050 h->cmdbuf[h->cmdidx++] = ap_num;
3052 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3056 static int stlink_usb_close_access_port(void *handle, unsigned char ap_num)
3058 struct stlink_usb_handle_s *h = handle;
3060 assert(handle != NULL);
3062 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3063 return ERROR_COMMAND_NOTFOUND;
3065 LOG_DEBUG_IO("close ap_num = %d", ap_num);
3066 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3067 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3068 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_CLOSE_AP_DBG;
3069 h->cmdbuf[h->cmdidx++] = ap_num;
3071 /* ignore incorrectly returned error on bogus FW */
3072 if (h->version.flags & STLINK_F_FIX_CLOSE_AP)
3073 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3075 return stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
3080 static int stlink_read_dap_register(void *handle, unsigned short dap_port,
3081 unsigned short addr, uint32_t *val)
3083 struct stlink_usb_handle_s *h = handle;
3086 assert(handle != NULL);
3088 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3089 return ERROR_COMMAND_NOTFOUND;
3091 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3092 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3093 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_DAP_REG;
3094 h_u16_to_le(&h->cmdbuf[2], dap_port);
3095 h_u16_to_le(&h->cmdbuf[4], addr);
3097 retval = stlink_usb_xfer_errcheck(handle, h->databuf, 8);
3098 *val = le_to_h_u32(h->databuf + 4);
3099 LOG_DEBUG_IO("dap_port_read = %d, addr = 0x%x, value = 0x%" PRIx32, dap_port, addr, *val);
3104 static int stlink_write_dap_register(void *handle, unsigned short dap_port,
3105 unsigned short addr, uint32_t val)
3107 struct stlink_usb_handle_s *h = handle;
3109 assert(handle != NULL);
3111 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3112 return ERROR_COMMAND_NOTFOUND;
3114 LOG_DEBUG_IO("dap_write port = %d, addr = 0x%x, value = 0x%" PRIx32, dap_port, addr, val);
3115 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3116 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3117 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITE_DAP_REG;
3118 h_u16_to_le(&h->cmdbuf[2], dap_port);
3119 h_u16_to_le(&h->cmdbuf[4], addr);
3120 h_u32_to_le(&h->cmdbuf[6], val);
3121 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3125 struct hl_layout_api_s stlink_usb_layout_api = {
3127 .open = stlink_usb_hl_open,
3129 .close = stlink_usb_close,
3131 .idcode = stlink_usb_idcode,
3133 .state = stlink_usb_state,
3135 .reset = stlink_usb_reset,
3137 .assert_srst = stlink_usb_assert_srst,
3139 .run = stlink_usb_run,
3141 .halt = stlink_usb_halt,
3143 .step = stlink_usb_step,
3145 .read_regs = stlink_usb_read_regs,
3147 .read_reg = stlink_usb_read_reg,
3149 .write_reg = stlink_usb_write_reg,
3151 .read_mem = stlink_usb_read_mem,
3153 .write_mem = stlink_usb_write_mem,
3155 .write_debug_reg = stlink_usb_write_debug_reg,
3157 .override_target = stlink_usb_override_target,
3159 .speed = stlink_speed,
3161 .config_trace = stlink_config_trace,
3163 .poll_trace = stlink_usb_trace_read,
3166 /*****************************************************************************
3167 * DAP direct interface
3170 static struct stlink_usb_handle_s *stlink_dap_handle;
3171 static struct hl_interface_param_s stlink_dap_param;
3172 static DECLARE_BITMAP(opened_ap, DP_APSEL_MAX + 1);
3173 static int stlink_dap_error = ERROR_OK;
3175 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3179 static int stlink_dap_record_error(int error)
3181 if (stlink_dap_error == ERROR_OK)
3182 stlink_dap_error = error;
3187 static int stlink_dap_get_and_clear_error(void)
3189 int retval = stlink_dap_error;
3190 stlink_dap_error = ERROR_OK;
3194 static int stlink_usb_open_ap(void *handle, unsigned short apsel)
3196 struct stlink_usb_handle_s *h = handle;
3199 /* nothing to do on old versions */
3200 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3203 if (apsel > DP_APSEL_MAX)
3206 if (test_bit(apsel, opened_ap))
3209 retval = stlink_usb_init_access_port(h, apsel);
3210 if (retval != ERROR_OK)
3213 LOG_DEBUG("AP %d enabled", apsel);
3214 set_bit(apsel, opened_ap);
3218 static int stlink_dap_open_ap(unsigned short apsel)
3220 return stlink_usb_open_ap(stlink_dap_handle, apsel);
3224 static int stlink_dap_closeall_ap(void)
3228 /* nothing to do on old versions */
3229 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3232 for (apsel = 0; apsel <= DP_APSEL_MAX; apsel++) {
3233 if (!test_bit(apsel, opened_ap))
3235 retval = stlink_usb_close_access_port(stlink_dap_handle, apsel);
3236 if (retval != ERROR_OK)
3238 clear_bit(apsel, opened_ap);
3244 static int stlink_dap_reinit_interface(void)
3249 * On JTAG only, it should be enough to call stlink_usb_reset(). But on
3250 * some firmware version it does not work as expected, and there is no
3251 * equivalent for SWD.
3252 * At least for now, to reset the interface quit from JTAG/SWD mode then
3253 * select the mode again.
3256 if (!stlink_dap_handle->reconnect_pending) {
3257 stlink_dap_handle->reconnect_pending = true;
3258 stlink_usb_mode_leave(stlink_dap_handle, stlink_dap_handle->st_mode);
3261 retval = stlink_usb_mode_enter(stlink_dap_handle, stlink_dap_handle->st_mode);
3262 if (retval != ERROR_OK)
3265 stlink_dap_handle->reconnect_pending = false;
3266 /* on new FW, calling mode-leave closes all the opened AP; reopen them! */
3267 if (stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT)
3268 for (int apsel = 0; apsel <= DP_APSEL_MAX; apsel++)
3269 if (test_bit(apsel, opened_ap)) {
3270 clear_bit(apsel, opened_ap);
3271 stlink_dap_open_ap(apsel);
3277 static int stlink_dap_op_connect(struct adiv5_dap *dap)
3282 LOG_INFO("stlink_dap_op_connect(%sconnect)", dap->do_reconnect ? "re" : "");
3284 /* Check if we should reset srst already when connecting, but not if reconnecting. */
3285 if (!dap->do_reconnect) {
3286 enum reset_types jtag_reset_config = jtag_get_reset_config();
3288 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3289 if (jtag_reset_config & RESET_SRST_NO_GATING)
3290 adapter_assert_reset();
3292 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3296 dap->do_reconnect = false;
3297 dap_invalidate_cache(dap);
3299 retval = dap_dp_init(dap);
3300 if (retval != ERROR_OK) {
3301 dap->do_reconnect = true;
3305 retval = stlink_usb_idcode(stlink_dap_handle, &idcode);
3306 if (retval == ERROR_OK)
3307 LOG_INFO("%s %#8.8" PRIx32,
3308 (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) ? "JTAG IDCODE" : "SWD DPIDR",
3311 dap->do_reconnect = true;
3317 static int stlink_dap_check_reconnect(struct adiv5_dap *dap)
3321 if (!dap->do_reconnect)
3324 retval = stlink_dap_reinit_interface();
3325 if (retval != ERROR_OK)
3328 return stlink_dap_op_connect(dap);
3332 static int stlink_dap_op_send_sequence(struct adiv5_dap *dap, enum swd_special_seq seq)
3334 /* Ignore the request */
3339 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3345 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3346 if (reg & 0x000000F0) {
3347 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3348 return ERROR_COMMAND_NOTFOUND;
3351 retval = stlink_dap_check_reconnect(dap);
3352 if (retval != ERROR_OK)
3355 data = data ? : &dummy;
3356 if (stlink_dap_handle->version.flags & STLINK_F_QUIRK_JTAG_DP_READ
3357 && stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) {
3358 /* Quirk required in JTAG. Read RDBUFF to get the data */
3359 retval = stlink_read_dap_register(stlink_dap_handle,
3360 STLINK_DEBUG_PORT_ACCESS, reg, &dummy);
3361 if (retval == ERROR_OK)
3362 retval = stlink_read_dap_register(stlink_dap_handle,
3363 STLINK_DEBUG_PORT_ACCESS, DP_RDBUFF, data);
3365 retval = stlink_read_dap_register(stlink_dap_handle,
3366 STLINK_DEBUG_PORT_ACCESS, reg, data);
3369 return stlink_dap_record_error(retval);
3373 static int stlink_dap_op_queue_dp_write(struct adiv5_dap *dap, unsigned reg,
3378 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3379 if (reg & 0x000000F0) {
3380 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3381 return ERROR_COMMAND_NOTFOUND;
3384 if (reg == DP_SELECT && (data & DP_SELECT_DPBANK) != 0) {
3385 /* ignored if STLINK_F_HAS_DPBANKSEL, not properly managed otherwise */
3386 LOG_DEBUG("Ignoring DPBANKSEL while write SELECT");
3387 data &= ~DP_SELECT_DPBANK;
3390 retval = stlink_dap_check_reconnect(dap);
3391 if (retval != ERROR_OK)
3394 /* ST-Link does not like that we set CORUNDETECT */
3395 if (reg == DP_CTRL_STAT)
3396 data &= ~CORUNDETECT;
3398 retval = stlink_write_dap_register(stlink_dap_handle,
3399 STLINK_DEBUG_PORT_ACCESS, reg, data);
3400 return stlink_dap_record_error(retval);
3404 static int stlink_dap_op_queue_ap_read(struct adiv5_ap *ap, unsigned reg,
3407 struct adiv5_dap *dap = ap->dap;
3411 retval = stlink_dap_check_reconnect(dap);
3412 if (retval != ERROR_OK)
3415 if (reg != AP_REG_IDR) {
3416 retval = stlink_dap_open_ap(ap->ap_num);
3417 if (retval != ERROR_OK)
3420 data = data ? : &dummy;
3421 retval = stlink_read_dap_register(stlink_dap_handle, ap->ap_num, reg,
3423 dap->stlink_flush_ap_write = false;
3424 return stlink_dap_record_error(retval);
3428 static int stlink_dap_op_queue_ap_write(struct adiv5_ap *ap, unsigned reg,
3431 struct adiv5_dap *dap = ap->dap;
3434 retval = stlink_dap_check_reconnect(dap);
3435 if (retval != ERROR_OK)
3438 retval = stlink_dap_open_ap(ap->ap_num);
3439 if (retval != ERROR_OK)
3442 retval = stlink_write_dap_register(stlink_dap_handle, ap->ap_num, reg,
3444 dap->stlink_flush_ap_write = true;
3445 return stlink_dap_record_error(retval);
3449 static int stlink_dap_op_queue_ap_abort(struct adiv5_dap *dap, uint8_t *ack)
3451 LOG_WARNING("stlink_dap_op_queue_ap_abort()");
3456 static int stlink_dap_op_run(struct adiv5_dap *dap)
3458 uint32_t ctrlstat, pwrmask;
3459 int retval, saved_retval;
3461 /* Here no LOG_DEBUG. This is called continuously! */
3464 * ST-Link returns immediately after a DAP write, without waiting for it
3466 * Run a dummy read to DP_RDBUFF, as suggested in
3467 * http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka16363.html
3469 if (dap->stlink_flush_ap_write) {
3470 dap->stlink_flush_ap_write = false;
3471 retval = stlink_dap_op_queue_dp_read(dap, DP_RDBUFF, NULL);
3472 if (retval != ERROR_OK) {
3473 dap->do_reconnect = true;
3478 saved_retval = stlink_dap_get_and_clear_error();
3480 retval = stlink_dap_op_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
3481 if (retval != ERROR_OK) {
3482 dap->do_reconnect = true;
3485 retval = stlink_dap_get_and_clear_error();
3486 if (retval != ERROR_OK) {
3487 LOG_ERROR("Fail reading CTRL/STAT register. Force reconnect");
3488 dap->do_reconnect = true;
3492 if (ctrlstat & SSTICKYERR) {
3493 if (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG)
3494 retval = stlink_dap_op_queue_dp_write(dap, DP_CTRL_STAT,
3495 ctrlstat & (dap->dp_ctrl_stat | SSTICKYERR));
3497 retval = stlink_dap_op_queue_dp_write(dap, DP_ABORT, STKERRCLR);
3498 if (retval != ERROR_OK) {
3499 dap->do_reconnect = true;
3502 retval = stlink_dap_get_and_clear_error();
3503 if (retval != ERROR_OK) {
3504 dap->do_reconnect = true;
3509 /* check for power lost */
3510 pwrmask = dap->dp_ctrl_stat & (CDBGPWRUPREQ | CSYSPWRUPREQ);
3511 if ((ctrlstat & pwrmask) != pwrmask)
3512 dap->do_reconnect = true;
3514 return saved_retval;
3518 static void stlink_dap_op_quit(struct adiv5_dap *dap)
3522 retval = stlink_dap_closeall_ap();
3523 if (retval != ERROR_OK)
3524 LOG_ERROR("Error closing APs");
3527 static int stlink_swim_op_srst(void)
3529 return stlink_swim_generate_rst(stlink_dap_handle);
3532 static int stlink_swim_op_read_mem(uint32_t addr, uint32_t size,
3533 uint32_t count, uint8_t *buffer)
3536 uint32_t bytes_remaining;
3538 LOG_DEBUG_IO("read at 0x%08" PRIx32 " len %" PRIu32 "*0x%08" PRIx32, addr, size, count);
3542 bytes_remaining = (count > STLINK_DATA_SIZE) ? STLINK_DATA_SIZE : count;
3543 retval = stlink_swim_readbytes(stlink_dap_handle, addr, bytes_remaining, buffer);
3544 if (retval != ERROR_OK)
3547 buffer += bytes_remaining;
3548 addr += bytes_remaining;
3549 count -= bytes_remaining;
3555 static int stlink_swim_op_write_mem(uint32_t addr, uint32_t size,
3556 uint32_t count, const uint8_t *buffer)
3559 uint32_t bytes_remaining;
3561 LOG_DEBUG_IO("write at 0x%08" PRIx32 " len %" PRIu32 "*0x%08" PRIx32, addr, size, count);
3565 bytes_remaining = (count > STLINK_DATA_SIZE) ? STLINK_DATA_SIZE : count;
3566 retval = stlink_swim_writebytes(stlink_dap_handle, addr, bytes_remaining, buffer);
3567 if (retval != ERROR_OK)
3570 buffer += bytes_remaining;
3571 addr += bytes_remaining;
3572 count -= bytes_remaining;
3578 static int stlink_swim_op_reconnect(void)
3582 retval = stlink_usb_mode_enter(stlink_dap_handle, STLINK_MODE_DEBUG_SWIM);
3583 if (retval != ERROR_OK)
3586 return stlink_swim_resync(stlink_dap_handle);
3589 static int stlink_dap_config_trace(bool enabled,
3590 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
3591 unsigned int *trace_freq, unsigned int traceclkin_freq,
3592 uint16_t *prescaler)
3594 return stlink_config_trace(stlink_dap_handle, enabled, pin_protocol,
3595 port_size, trace_freq, traceclkin_freq,
3599 static int stlink_dap_trace_read(uint8_t *buf, size_t *size)
3601 return stlink_usb_trace_read(stlink_dap_handle, buf, size);
3605 COMMAND_HANDLER(stlink_dap_serial_command)
3607 LOG_DEBUG("stlink_dap_serial_command");
3609 if (CMD_ARGC != 1) {
3610 LOG_ERROR("Expected exactly one argument for \"st-link serial <serial-number>\".");
3611 return ERROR_COMMAND_SYNTAX_ERROR;
3614 if (stlink_dap_param.serial) {
3615 LOG_WARNING("Command \"st-link serial\" already used. Replacing previous value");
3616 free((void *)stlink_dap_param.serial);
3619 stlink_dap_param.serial = strdup(CMD_ARGV[0]);
3624 COMMAND_HANDLER(stlink_dap_vid_pid)
3626 unsigned int i, max_usb_ids = HLA_MAX_USB_IDS;
3628 if (CMD_ARGC > max_usb_ids * 2) {
3629 LOG_WARNING("ignoring extra IDs in vid_pid "
3630 "(maximum is %d pairs)", max_usb_ids);
3631 CMD_ARGC = max_usb_ids * 2;
3633 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
3634 LOG_WARNING("incomplete vid_pid configuration directive");
3635 return ERROR_COMMAND_SYNTAX_ERROR;
3637 for (i = 0; i < CMD_ARGC; i += 2) {
3638 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], stlink_dap_param.vid[i / 2]);
3639 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], stlink_dap_param.pid[i / 2]);
3642 /* null termination */
3643 stlink_dap_param.vid[i / 2] = stlink_dap_param.pid[i / 2] = 0;
3649 static const struct command_registration stlink_dap_subcommand_handlers[] = {
3652 .handler = stlink_dap_serial_command,
3653 .mode = COMMAND_CONFIG,
3654 .help = "set the serial number of the adapter",
3655 .usage = "<serial_number>",
3659 .handler = stlink_dap_vid_pid,
3660 .mode = COMMAND_CONFIG,
3661 .help = "USB VID and PID of the adapter",
3662 .usage = "(vid pid)+",
3664 COMMAND_REGISTRATION_DONE
3668 static const struct command_registration stlink_dap_command_handlers[] = {
3671 .mode = COMMAND_ANY,
3672 .help = "perform st-link management",
3673 .chain = stlink_dap_subcommand_handlers,
3676 COMMAND_REGISTRATION_DONE
3680 static int stlink_dap_init(void)
3682 enum reset_types jtag_reset_config = jtag_get_reset_config();
3683 enum stlink_mode mode;
3686 LOG_DEBUG("stlink_dap_init()");
3688 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3689 if (jtag_reset_config & RESET_SRST_NO_GATING)
3690 stlink_dap_param.connect_under_reset = true;
3692 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3695 if (transport_is_dapdirect_swd())
3696 mode = STLINK_MODE_DEBUG_SWD;
3697 else if (transport_is_dapdirect_jtag())
3698 mode = STLINK_MODE_DEBUG_JTAG;
3699 else if (transport_is_swim())
3700 mode = STLINK_MODE_DEBUG_SWIM;
3702 LOG_ERROR("Unsupported transport");
3706 retval = stlink_usb_open(&stlink_dap_param, mode, (void **)&stlink_dap_handle);
3707 if (retval != ERROR_OK)
3710 if ((mode != STLINK_MODE_DEBUG_SWIM) &&
3711 !(stlink_dap_handle->version.flags & STLINK_F_HAS_DAP_REG)) {
3712 LOG_ERROR("ST-Link version does not support DAP direct transport");
3719 static int stlink_dap_quit(void)
3721 LOG_DEBUG("stlink_dap_quit()");
3723 free((void *)stlink_dap_param.serial);
3724 stlink_dap_param.serial = NULL;
3726 return stlink_usb_close(stlink_dap_handle);
3730 static int stlink_dap_reset(int req_trst, int req_srst)
3732 LOG_DEBUG("stlink_dap_reset(%d)", req_srst);
3733 return stlink_usb_assert_srst(stlink_dap_handle,
3734 req_srst ? STLINK_DEBUG_APIV2_DRIVE_NRST_LOW
3735 : STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH);
3739 static int stlink_dap_speed(int speed)
3742 LOG_ERROR("RTCK not supported. Set nonzero adapter_khz.");
3743 return ERROR_JTAG_NOT_IMPLEMENTED;
3746 stlink_dap_param.initial_interface_speed = speed;
3747 stlink_speed(stlink_dap_handle, speed, false);
3752 static int stlink_dap_khz(int khz, int *jtag_speed)
3755 LOG_ERROR("RCLK not supported");
3759 *jtag_speed = stlink_speed(stlink_dap_handle, khz, true);
3764 static int stlink_dap_speed_div(int speed, int *khz)
3770 static const struct dap_ops stlink_dap_ops = {
3771 .connect = stlink_dap_op_connect,
3772 .send_sequence = stlink_dap_op_send_sequence,
3773 .queue_dp_read = stlink_dap_op_queue_dp_read,
3774 .queue_dp_write = stlink_dap_op_queue_dp_write,
3775 .queue_ap_read = stlink_dap_op_queue_ap_read,
3776 .queue_ap_write = stlink_dap_op_queue_ap_write,
3777 .queue_ap_abort = stlink_dap_op_queue_ap_abort,
3778 .run = stlink_dap_op_run,
3779 .sync = NULL, /* optional */
3780 .quit = stlink_dap_op_quit, /* optional */
3783 static const struct swim_driver stlink_swim_ops = {
3784 .srst = stlink_swim_op_srst,
3785 .read_mem = stlink_swim_op_read_mem,
3786 .write_mem = stlink_swim_op_write_mem,
3787 .reconnect = stlink_swim_op_reconnect,
3790 static const char *const stlink_dap_transport[] = { "dapdirect_swd", "dapdirect_jtag", "swim", NULL };
3792 struct adapter_driver stlink_dap_adapter_driver = {
3794 .transports = stlink_dap_transport,
3795 .commands = stlink_dap_command_handlers,
3797 .init = stlink_dap_init,
3798 .quit = stlink_dap_quit,
3799 .reset = stlink_dap_reset,
3800 .speed = stlink_dap_speed,
3801 .khz = stlink_dap_khz,
3802 .speed_div = stlink_dap_speed_div,
3803 .config_trace = stlink_dap_config_trace,
3804 .poll_trace = stlink_dap_trace_read,
3806 .dap_jtag_ops = &stlink_dap_ops,
3807 .dap_swd_ops = &stlink_dap_ops,
3808 .swim_ops = &stlink_swim_ops,