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 <target/target.h>
40 #include <transport/transport.h>
42 #include <target/cortex_m.h>
44 #include "libusb_helper.h"
47 #define USE_LIBUSB_ASYNCIO
50 #define STLINK_SERIAL_LEN 24
52 #define ENDPOINT_IN 0x80
53 #define ENDPOINT_OUT 0x00
55 #define STLINK_WRITE_TIMEOUT 1000
56 #define STLINK_READ_TIMEOUT 1000
58 #define STLINK_NULL_EP 0
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 struct stlink_usb_version {
107 /** jtag api version supported */
108 enum stlink_jtag_api_version jtag_api;
109 /** one bit for each feature supported. See macros STLINK_F_* */
114 struct stlink_usb_handle_s {
116 struct libusb_device_handle *fd;
118 struct libusb_transfer *trans;
126 uint8_t cmdbuf[STLINK_SG_SIZE];
132 uint8_t databuf[STLINK_DATA_SIZE];
134 uint32_t max_mem_packet;
136 enum hl_transports transport;
138 struct stlink_usb_version version;
145 /** whether SWO tracing is enabled or not */
147 /** trace module source clock */
150 /** reconnect is needed next time we try to query the
152 bool reconnect_pending;
155 #define STLINK_SWIM_ERR_OK 0x00
156 #define STLINK_SWIM_BUSY 0x01
157 #define STLINK_DEBUG_ERR_OK 0x80
158 #define STLINK_DEBUG_ERR_FAULT 0x81
159 #define STLINK_SWD_AP_WAIT 0x10
160 #define STLINK_SWD_AP_FAULT 0x11
161 #define STLINK_SWD_AP_ERROR 0x12
162 #define STLINK_SWD_AP_PARITY_ERROR 0x13
163 #define STLINK_JTAG_GET_IDCODE_ERROR 0x09
164 #define STLINK_JTAG_WRITE_ERROR 0x0c
165 #define STLINK_JTAG_WRITE_VERIF_ERROR 0x0d
166 #define STLINK_SWD_DP_WAIT 0x14
167 #define STLINK_SWD_DP_FAULT 0x15
168 #define STLINK_SWD_DP_ERROR 0x16
169 #define STLINK_SWD_DP_PARITY_ERROR 0x17
171 #define STLINK_SWD_AP_WDATA_ERROR 0x18
172 #define STLINK_SWD_AP_STICKY_ERROR 0x19
173 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
175 #define STLINK_BAD_AP_ERROR 0x1d
177 #define STLINK_CORE_RUNNING 0x80
178 #define STLINK_CORE_HALTED 0x81
179 #define STLINK_CORE_STAT_UNKNOWN -1
181 #define STLINK_GET_VERSION 0xF1
182 #define STLINK_DEBUG_COMMAND 0xF2
183 #define STLINK_DFU_COMMAND 0xF3
184 #define STLINK_SWIM_COMMAND 0xF4
185 #define STLINK_GET_CURRENT_MODE 0xF5
186 #define STLINK_GET_TARGET_VOLTAGE 0xF7
188 #define STLINK_DEV_DFU_MODE 0x00
189 #define STLINK_DEV_MASS_MODE 0x01
190 #define STLINK_DEV_DEBUG_MODE 0x02
191 #define STLINK_DEV_SWIM_MODE 0x03
192 #define STLINK_DEV_BOOTLOADER_MODE 0x04
193 #define STLINK_DEV_UNKNOWN_MODE -1
195 #define STLINK_DFU_EXIT 0x07
198 STLINK_SWIM_ENTER_SEQ
199 1.3ms low then 750Hz then 1.5kHz
202 STM8 DM pulls reset pin low 50us
205 uint8_t (0=low|1=high)
212 send syncronization seq (16us low, response 64 clocks low)
214 #define STLINK_SWIM_ENTER 0x00
215 #define STLINK_SWIM_EXIT 0x01
216 #define STLINK_SWIM_READ_CAP 0x02
217 #define STLINK_SWIM_SPEED 0x03
218 #define STLINK_SWIM_ENTER_SEQ 0x04
219 #define STLINK_SWIM_GEN_RST 0x05
220 #define STLINK_SWIM_RESET 0x06
221 #define STLINK_SWIM_ASSERT_RESET 0x07
222 #define STLINK_SWIM_DEASSERT_RESET 0x08
223 #define STLINK_SWIM_READSTATUS 0x09
224 #define STLINK_SWIM_WRITEMEM 0x0a
225 #define STLINK_SWIM_READMEM 0x0b
226 #define STLINK_SWIM_READBUF 0x0c
228 #define STLINK_DEBUG_GETSTATUS 0x01
229 #define STLINK_DEBUG_FORCEDEBUG 0x02
230 #define STLINK_DEBUG_APIV1_RESETSYS 0x03
231 #define STLINK_DEBUG_APIV1_READALLREGS 0x04
232 #define STLINK_DEBUG_APIV1_READREG 0x05
233 #define STLINK_DEBUG_APIV1_WRITEREG 0x06
234 #define STLINK_DEBUG_READMEM_32BIT 0x07
235 #define STLINK_DEBUG_WRITEMEM_32BIT 0x08
236 #define STLINK_DEBUG_RUNCORE 0x09
237 #define STLINK_DEBUG_STEPCORE 0x0a
238 #define STLINK_DEBUG_APIV1_SETFP 0x0b
239 #define STLINK_DEBUG_READMEM_8BIT 0x0c
240 #define STLINK_DEBUG_WRITEMEM_8BIT 0x0d
241 #define STLINK_DEBUG_APIV1_CLEARFP 0x0e
242 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG 0x0f
243 #define STLINK_DEBUG_APIV1_SETWATCHPOINT 0x10
245 #define STLINK_DEBUG_ENTER_JTAG_RESET 0x00
246 #define STLINK_DEBUG_ENTER_SWD_NO_RESET 0xa3
247 #define STLINK_DEBUG_ENTER_JTAG_NO_RESET 0xa4
249 #define STLINK_DEBUG_APIV1_ENTER 0x20
250 #define STLINK_DEBUG_EXIT 0x21
251 #define STLINK_DEBUG_READCOREID 0x22
253 #define STLINK_DEBUG_APIV2_ENTER 0x30
254 #define STLINK_DEBUG_APIV2_READ_IDCODES 0x31
255 #define STLINK_DEBUG_APIV2_RESETSYS 0x32
256 #define STLINK_DEBUG_APIV2_READREG 0x33
257 #define STLINK_DEBUG_APIV2_WRITEREG 0x34
258 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG 0x35
259 #define STLINK_DEBUG_APIV2_READDEBUGREG 0x36
261 #define STLINK_DEBUG_APIV2_READALLREGS 0x3A
262 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
263 #define STLINK_DEBUG_APIV2_DRIVE_NRST 0x3C
265 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS2 0x3E
267 #define STLINK_DEBUG_APIV2_START_TRACE_RX 0x40
268 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX 0x41
269 #define STLINK_DEBUG_APIV2_GET_TRACE_NB 0x42
270 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ 0x43
271 #define STLINK_DEBUG_APIV2_JTAG_SET_FREQ 0x44
272 #define STLINK_DEBUG_APIV2_READ_DAP_REG 0x45
273 #define STLINK_DEBUG_APIV2_WRITE_DAP_REG 0x46
274 #define STLINK_DEBUG_APIV2_READMEM_16BIT 0x47
275 #define STLINK_DEBUG_APIV2_WRITEMEM_16BIT 0x48
277 #define STLINK_DEBUG_APIV2_INIT_AP 0x4B
278 #define STLINK_DEBUG_APIV2_CLOSE_AP_DBG 0x4C
280 #define STLINK_APIV3_SET_COM_FREQ 0x61
281 #define STLINK_APIV3_GET_COM_FREQ 0x62
283 #define STLINK_APIV3_GET_VERSION_EX 0xFB
285 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW 0x00
286 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH 0x01
287 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
289 #define STLINK_DEBUG_PORT_ACCESS 0xffff
291 #define STLINK_TRACE_SIZE 4096
292 #define STLINK_TRACE_MAX_HZ 2000000
294 #define STLINK_V3_MAX_FREQ_NB 10
298 STLINK_MODE_UNKNOWN = 0,
301 STLINK_MODE_DEBUG_JTAG,
302 STLINK_MODE_DEBUG_SWD,
303 STLINK_MODE_DEBUG_SWIM
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)
325 #define STLINK_F_HAS_TARGET_VOLT STLINK_F_HAS_TRACE
332 /* SWD clock speed */
333 static const struct speed_map stlink_khz_to_speed_map_swd[] = {
335 {1800, 1}, /* default */
348 /* JTAG clock speed */
349 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 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);
367 static unsigned int stlink_usb_block(void *handle)
369 struct stlink_usb_handle_s *h = handle;
371 assert(handle != NULL);
373 if (h->version.flags & STLINK_F_HAS_RW8_512BYTES)
374 return STLINKV3_MAX_RW8;
376 return STLINK_MAX_RW8;
381 #ifdef USE_LIBUSB_ASYNCIO
383 static LIBUSB_CALL void sync_transfer_cb(struct libusb_transfer *transfer)
385 int *completed = transfer->user_data;
387 /* caller interprets result and frees transfer */
391 static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
393 int r, *completed = transfer->user_data;
395 /* Assuming a single libusb context exists. There no existing interface into this
396 * module to pass a libusb context.
398 struct libusb_context *ctx = NULL;
400 while (!*completed) {
401 r = libusb_handle_events_completed(ctx, completed);
403 if (r == LIBUSB_ERROR_INTERRUPTED)
405 libusb_cancel_transfer(transfer);
412 static int transfer_error_status(const struct libusb_transfer *transfer)
416 switch (transfer->status) {
417 case LIBUSB_TRANSFER_COMPLETED:
420 case LIBUSB_TRANSFER_TIMED_OUT:
421 r = LIBUSB_ERROR_TIMEOUT;
423 case LIBUSB_TRANSFER_STALL:
424 r = LIBUSB_ERROR_PIPE;
426 case LIBUSB_TRANSFER_OVERFLOW:
427 r = LIBUSB_ERROR_OVERFLOW;
429 case LIBUSB_TRANSFER_NO_DEVICE:
430 r = LIBUSB_ERROR_NO_DEVICE;
432 case LIBUSB_TRANSFER_ERROR:
433 case LIBUSB_TRANSFER_CANCELLED:
437 r = LIBUSB_ERROR_OTHER;
451 size_t transfer_size;
452 struct libusb_transfer *transfer;
455 static int jtag_libusb_bulk_transfer_n(
456 struct libusb_device_handle *dev_handle,
457 struct jtag_xfer *transfers,
462 int returnval = ERROR_OK;
465 for (size_t i = 0; i < n_transfers; ++i) {
466 transfers[i].retval = 0;
467 transfers[i].completed = 0;
468 transfers[i].transfer_size = 0;
469 transfers[i].transfer = libusb_alloc_transfer(0);
471 if (transfers[i].transfer == NULL) {
472 for (size_t j = 0; j < i; ++j)
473 libusb_free_transfer(transfers[j].transfer);
475 LOG_DEBUG("ERROR, failed to alloc usb transfers");
476 for (size_t k = 0; k < n_transfers; ++k)
477 transfers[k].retval = LIBUSB_ERROR_NO_MEM;
482 for (size_t i = 0; i < n_transfers; ++i) {
483 libusb_fill_bulk_transfer(
484 transfers[i].transfer,
486 transfers[i].ep, transfers[i].buf, transfers[i].size,
487 sync_transfer_cb, &transfers[i].completed, timeout);
488 transfers[i].transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
490 retval = libusb_submit_transfer(transfers[i].transfer);
492 LOG_DEBUG("ERROR, failed to submit transfer %zu, error %d", i, retval);
494 /* Probably no point continuing to submit transfers once a submission fails.
495 * As a result, tag all remaining transfers as errors.
497 for (size_t j = i; j < n_transfers; ++j)
498 transfers[j].retval = retval;
500 returnval = ERROR_FAIL;
505 /* Wait for every submitted USB transfer to complete.
507 for (size_t i = 0; i < n_transfers; ++i) {
508 if (transfers[i].retval == 0) {
509 sync_transfer_wait_for_completion(transfers[i].transfer);
511 retval = transfer_error_status(transfers[i].transfer);
513 returnval = ERROR_FAIL;
514 transfers[i].retval = retval;
515 LOG_DEBUG("ERROR, transfer %zu failed, error %d", i, retval);
517 /* Assuming actual_length is only valid if there is no transfer error.
519 transfers[i].transfer_size = transfers[i].transfer->actual_length;
523 libusb_free_transfer(transfers[i].transfer);
524 transfers[i].transfer = NULL;
534 static int stlink_usb_xfer_v1_get_status(void *handle)
536 struct stlink_usb_handle_s *h = handle;
539 assert(handle != NULL);
542 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
544 ret = jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)h->cmdbuf, 13,
545 STLINK_READ_TIMEOUT, &tr);
551 t1 = buf_get_u32(h->cmdbuf, 0, 32);
554 if (t1 != 0x53425355)
562 if (h->cmdbuf[12] != 0)
568 #ifdef USE_LIBUSB_ASYNCIO
569 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
571 struct stlink_usb_handle_s *h = handle;
573 assert(handle != NULL);
575 size_t n_transfers = 0;
576 struct jtag_xfer transfers[2];
578 memset(transfers, 0, sizeof(transfers));
580 transfers[0].ep = h->tx_ep;
581 transfers[0].buf = h->cmdbuf;
582 transfers[0].size = cmdsize;
586 if (h->direction == h->tx_ep && size) {
587 transfers[1].ep = h->tx_ep;
588 transfers[1].buf = (uint8_t *)buf;
589 transfers[1].size = size;
592 } else if (h->direction == h->rx_ep && size) {
593 transfers[1].ep = h->rx_ep;
594 transfers[1].buf = (uint8_t *)buf;
595 transfers[1].size = size;
600 return jtag_libusb_bulk_transfer_n(
604 STLINK_WRITE_TIMEOUT);
607 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
609 struct stlink_usb_handle_s *h = handle;
612 assert(handle != NULL);
614 ret = jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)h->cmdbuf,
615 cmdsize, STLINK_WRITE_TIMEOUT, &tr);
616 if (ret || tr != cmdsize)
619 if (h->direction == h->tx_ep && size) {
620 ret = jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)buf,
621 size, STLINK_WRITE_TIMEOUT, &tr);
622 if (ret || tr != size) {
623 LOG_DEBUG("bulk write failed");
626 } else if (h->direction == h->rx_ep && size) {
627 ret = jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)buf,
628 size, STLINK_READ_TIMEOUT, &tr);
629 if (ret || tr != size) {
630 LOG_DEBUG("bulk read failed");
640 static int stlink_usb_xfer_v1_get_sense(void *handle)
643 struct stlink_usb_handle_s *h = handle;
645 assert(handle != NULL);
647 stlink_usb_init_buffer(handle, h->rx_ep, 16);
649 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE;
650 h->cmdbuf[h->cmdidx++] = 0;
651 h->cmdbuf[h->cmdidx++] = 0;
652 h->cmdbuf[h->cmdidx++] = 0;
653 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE_LENGTH;
655 res = stlink_usb_xfer_rw(handle, REQUEST_SENSE_LENGTH, h->databuf, 16);
660 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK)
667 transfers block in cmdbuf
668 <size> indicates number of bytes in the following
670 Ignore the (eventual) error code in the received packet.
672 static int stlink_usb_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
674 int err, cmdsize = STLINK_CMD_SIZE_V2;
675 struct stlink_usb_handle_s *h = handle;
677 assert(handle != NULL);
679 if (h->version.stlink == 1) {
680 cmdsize = STLINK_SG_SIZE;
681 /* put length in bCBWCBLength */
682 h->cmdbuf[14] = h->cmdidx-15;
685 err = stlink_usb_xfer_rw(handle, cmdsize, buf, size);
690 if (h->version.stlink == 1) {
691 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK) {
692 /* check csw status */
693 if (h->cmdbuf[12] == 1) {
694 LOG_DEBUG("get sense");
695 if (stlink_usb_xfer_v1_get_sense(handle) != ERROR_OK)
706 Converts an STLINK status code held in the first byte of a response
707 to an openocd error, logs any error/wait status as debug output.
709 static int stlink_usb_error_check(void *handle)
711 struct stlink_usb_handle_s *h = handle;
713 assert(handle != NULL);
715 if (h->transport == HL_TRANSPORT_SWIM) {
716 switch (h->databuf[0]) {
717 case STLINK_SWIM_ERR_OK:
719 case STLINK_SWIM_BUSY:
722 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
727 /* TODO: no error checking yet on api V1 */
728 if (h->version.jtag_api == STLINK_JTAG_API_V1)
729 h->databuf[0] = STLINK_DEBUG_ERR_OK;
731 switch (h->databuf[0]) {
732 case STLINK_DEBUG_ERR_OK:
734 case STLINK_DEBUG_ERR_FAULT:
735 LOG_DEBUG("SWD fault response (0x%x)", STLINK_DEBUG_ERR_FAULT);
737 case STLINK_SWD_AP_WAIT:
738 LOG_DEBUG("wait status SWD_AP_WAIT (0x%x)", STLINK_SWD_AP_WAIT);
740 case STLINK_SWD_DP_WAIT:
741 LOG_DEBUG("wait status SWD_DP_WAIT (0x%x)", STLINK_SWD_DP_WAIT);
743 case STLINK_JTAG_GET_IDCODE_ERROR:
744 LOG_DEBUG("STLINK_JTAG_GET_IDCODE_ERROR");
746 case STLINK_JTAG_WRITE_ERROR:
747 LOG_DEBUG("Write error");
749 case STLINK_JTAG_WRITE_VERIF_ERROR:
750 LOG_DEBUG("Write verify error, ignoring");
752 case STLINK_SWD_AP_FAULT:
753 /* git://git.ac6.fr/openocd commit 657e3e885b9ee10
754 * returns ERROR_OK with the comment:
755 * Change in error status when reading outside RAM.
756 * This fix allows CDT plugin to visualize memory.
758 LOG_DEBUG("STLINK_SWD_AP_FAULT");
760 case STLINK_SWD_AP_ERROR:
761 LOG_DEBUG("STLINK_SWD_AP_ERROR");
763 case STLINK_SWD_AP_PARITY_ERROR:
764 LOG_DEBUG("STLINK_SWD_AP_PARITY_ERROR");
766 case STLINK_SWD_DP_FAULT:
767 LOG_DEBUG("STLINK_SWD_DP_FAULT");
769 case STLINK_SWD_DP_ERROR:
770 LOG_DEBUG("STLINK_SWD_DP_ERROR");
772 case STLINK_SWD_DP_PARITY_ERROR:
773 LOG_DEBUG("STLINK_SWD_DP_PARITY_ERROR");
775 case STLINK_SWD_AP_WDATA_ERROR:
776 LOG_DEBUG("STLINK_SWD_AP_WDATA_ERROR");
778 case STLINK_SWD_AP_STICKY_ERROR:
779 LOG_DEBUG("STLINK_SWD_AP_STICKY_ERROR");
781 case STLINK_SWD_AP_STICKYORUN_ERROR:
782 LOG_DEBUG("STLINK_SWD_AP_STICKYORUN_ERROR");
784 case STLINK_BAD_AP_ERROR:
785 LOG_DEBUG("STLINK_BAD_AP_ERROR");
788 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
794 * Wrapper around stlink_usb_xfer_noerrcheck()
795 * to check the error code in the received packet
797 static int stlink_usb_xfer_errcheck(void *handle, const uint8_t *buf, int size)
803 retval = stlink_usb_xfer_noerrcheck(handle, buf, size);
804 if (retval != ERROR_OK)
807 return stlink_usb_error_check(handle);
810 /** Issue an STLINK command via USB transfer, with retries on any wait status responses.
812 Works for commands where the STLINK_DEBUG status is returned in the first
813 byte of the response packet. For SWIM a SWIM_READSTATUS is requested instead.
815 Returns an openocd result code.
817 static int stlink_cmd_allow_retry(void *handle, const uint8_t *buf, int size)
821 struct stlink_usb_handle_s *h = handle;
824 if ((h->transport != HL_TRANSPORT_SWIM) || !retries) {
825 res = stlink_usb_xfer_noerrcheck(handle, buf, size);
830 if (h->transport == HL_TRANSPORT_SWIM) {
831 res = stlink_swim_status(handle);
836 res = stlink_usb_error_check(handle);
837 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
838 useconds_t delay_us = (1<<retries++) * 1000;
839 LOG_DEBUG("stlink_cmd_allow_retry ERROR_WAIT, retry %d, delaying %u microseconds", retries, delay_us);
848 static int stlink_usb_read_trace(void *handle, const uint8_t *buf, int size)
850 struct stlink_usb_handle_s *h = handle;
853 assert(handle != NULL);
855 assert(h->version.flags & STLINK_F_HAS_TRACE);
857 ret = jtag_libusb_bulk_read(h->fd, h->trace_ep, (char *)buf, size,
858 STLINK_READ_TIMEOUT, &tr);
859 if (ret || tr != size) {
860 LOG_ERROR("bulk trace read failed");
868 this function writes transfer length in
869 the right place in the cb
871 static void stlink_usb_set_cbw_transfer_datalength(void *handle, uint32_t size)
873 struct stlink_usb_handle_s *h = handle;
875 buf_set_u32(h->cmdbuf+8, 0, 32, size);
878 static void stlink_usb_xfer_v1_create_cmd(void *handle, uint8_t direction, uint32_t size)
880 struct stlink_usb_handle_s *h = handle;
882 /* fill the send buffer */
883 strcpy((char *)h->cmdbuf, "USBC");
885 /* csw tag not used */
886 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, 0);
888 /* cbw data transfer length (in the following data phase in or out) */
889 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, size);
892 h->cmdbuf[h->cmdidx++] = (direction == h->rx_ep ? ENDPOINT_IN : ENDPOINT_OUT);
893 h->cmdbuf[h->cmdidx++] = 0; /* lun */
894 /* cdb clength (is filled in at xfer) */
895 h->cmdbuf[h->cmdidx++] = 0;
899 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size)
901 struct stlink_usb_handle_s *h = handle;
903 h->direction = direction;
907 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
908 memset(h->databuf, 0, STLINK_DATA_SIZE);
910 if (h->version.stlink == 1)
911 stlink_usb_xfer_v1_create_cmd(handle, direction, size);
915 static int stlink_usb_version(void *handle)
920 uint8_t v, x, y, jtag, swim, msd, bridge = 0;
921 char v_str[5 * (1 + 3) + 1]; /* VvJjMmBbSs */
923 struct stlink_usb_handle_s *h = handle;
925 assert(handle != NULL);
927 stlink_usb_init_buffer(handle, h->rx_ep, 6);
929 h->cmdbuf[h->cmdidx++] = STLINK_GET_VERSION;
931 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 6);
936 version = be_to_h_u16(h->databuf);
937 v = (version >> 12) & 0x0f;
938 x = (version >> 6) & 0x3f;
941 h->vid = le_to_h_u16(h->databuf + 2);
942 h->pid = le_to_h_u16(h->databuf + 4);
945 case STLINK_V2_1_PID:
946 case STLINK_V2_1_NO_MSD_PID:
947 if ((x <= 22 && y == 7) || (x >= 25 && y >= 7 && y <= 12)) {
948 /* MxSy : STM8 V2.1 - SWIM only */
953 /* JxMy : STM32 V2.1 - JTAG/SWD only */
966 /* STLINK-V3 requires a specific command */
967 if (v == 3 && x == 0 && y == 0) {
968 stlink_usb_init_buffer(handle, h->rx_ep, 16);
970 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_VERSION_EX;
972 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 12);
977 swim = h->databuf[1];
978 jtag = h->databuf[2];
980 bridge = h->databuf[4];
981 h->vid = le_to_h_u16(h->databuf + 8);
982 h->pid = le_to_h_u16(h->databuf + 10);
985 h->version.stlink = v;
986 h->version.jtag = jtag;
987 h->version.swim = swim;
990 switch (h->version.stlink) {
992 /* ST-LINK/V1 from J11 switch to api-v2 (and support SWD) */
993 if (h->version.jtag >= 11)
994 h->version.jtag_api = STLINK_JTAG_API_V2;
996 h->version.jtag_api = STLINK_JTAG_API_V1;
1000 /* all ST-LINK/V2 and ST-Link/V2.1 use api-v2 */
1001 h->version.jtag_api = STLINK_JTAG_API_V2;
1003 /* API for trace from J13 */
1004 /* API for target voltage from J13 */
1005 if (h->version.jtag >= 13)
1006 flags |= STLINK_F_HAS_TRACE;
1008 /* preferred API to get last R/W status from J15 */
1009 if (h->version.jtag >= 15)
1010 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1012 /* API to set SWD frequency from J22 */
1013 if (h->version.jtag >= 22)
1014 flags |= STLINK_F_HAS_SWD_SET_FREQ;
1016 /* API to set JTAG frequency from J24 */
1017 /* API to access DAP registers from J24 */
1018 if (h->version.jtag >= 24) {
1019 flags |= STLINK_F_HAS_JTAG_SET_FREQ;
1020 flags |= STLINK_F_HAS_DAP_REG;
1023 /* Quirk for read DP in JTAG mode (V2 only) from J24, fixed in J32 */
1024 if (h->version.jtag >= 24 && h->version.jtag < 32)
1025 flags |= STLINK_F_QUIRK_JTAG_DP_READ;
1027 /* API to read/write memory at 16 bit from J26 */
1028 if (h->version.jtag >= 26)
1029 flags |= STLINK_F_HAS_MEM_16BIT;
1031 /* API required to init AP before any AP access from J28 */
1032 if (h->version.jtag >= 28)
1033 flags |= STLINK_F_HAS_AP_INIT;
1035 /* Banked regs (DPv1 & DPv2) support from V2J32 */
1036 if (h->version.jtag >= 32)
1037 flags |= STLINK_F_HAS_DPBANKSEL;
1041 /* all STLINK-V3 use api-v3 */
1042 h->version.jtag_api = STLINK_JTAG_API_V3;
1044 /* STLINK-V3 is a superset of ST-LINK/V2 */
1047 /* API for target voltage */
1048 flags |= STLINK_F_HAS_TRACE;
1050 /* preferred API to get last R/W status */
1051 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1053 /* API to access DAP registers */
1054 flags |= STLINK_F_HAS_DAP_REG;
1056 /* API to read/write memory at 16 bit */
1057 flags |= STLINK_F_HAS_MEM_16BIT;
1059 /* API required to init AP before any AP access */
1060 flags |= STLINK_F_HAS_AP_INIT;
1062 /* Banked regs (DPv1 & DPv2) support from V3J2 */
1063 if (h->version.jtag >= 2)
1064 flags |= STLINK_F_HAS_DPBANKSEL;
1066 /* 8bit read/write max packet size 512 bytes from V3J6 */
1067 if (h->version.jtag >= 6)
1068 flags |= STLINK_F_HAS_RW8_512BYTES;
1074 h->version.flags = flags;
1077 p += sprintf(p, "V%d", v);
1079 p += sprintf(p, "J%d", jtag);
1081 p += sprintf(p, "M%d", msd);
1083 p += sprintf(p, "B%d", bridge);
1085 sprintf(p, "S%d", swim);
1087 LOG_INFO("STLINK %s (API v%d) VID:PID %04X:%04X",
1089 h->version.jtag_api,
1096 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
1098 struct stlink_usb_handle_s *h = handle;
1099 uint32_t adc_results[2];
1101 /* no error message, simply quit with error */
1102 if (!(h->version.flags & STLINK_F_HAS_TARGET_VOLT))
1103 return ERROR_COMMAND_NOTFOUND;
1105 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1107 h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
1109 int result = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1111 if (result != ERROR_OK)
1114 /* convert result */
1115 adc_results[0] = le_to_h_u32(h->databuf);
1116 adc_results[1] = le_to_h_u32(h->databuf + 4);
1118 *target_voltage = 0;
1121 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
1123 LOG_INFO("Target voltage: %f", (double)*target_voltage);
1128 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
1130 struct stlink_usb_handle_s *h = handle;
1132 assert(handle != NULL);
1134 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
1135 return ERROR_COMMAND_NOTFOUND;
1137 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1139 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1140 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
1141 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1144 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1146 if (result != ERROR_OK)
1152 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
1154 struct stlink_usb_handle_s *h = handle;
1156 assert(handle != NULL);
1158 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
1159 return ERROR_COMMAND_NOTFOUND;
1161 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1163 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1164 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
1165 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1168 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1170 if (result != ERROR_OK)
1177 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
1180 struct stlink_usb_handle_s *h = handle;
1182 assert(handle != NULL);
1184 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1186 h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
1188 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1190 if (res != ERROR_OK)
1193 *mode = h->databuf[0];
1199 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
1202 struct stlink_usb_handle_s *h = handle;
1204 assert(handle != NULL);
1206 /* on api V2 we are able the read the latest command
1208 * TODO: we need the test on api V1 too
1210 if (h->version.jtag_api != STLINK_JTAG_API_V1)
1213 stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
1216 case STLINK_MODE_DEBUG_JTAG:
1217 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1218 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1219 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1221 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1222 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG_NO_RESET;
1224 case STLINK_MODE_DEBUG_SWD:
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_SWD_NO_RESET;
1232 case STLINK_MODE_DEBUG_SWIM:
1233 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1234 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
1235 /* no answer for this function... */
1238 case STLINK_MODE_DFU:
1239 case STLINK_MODE_MASS:
1244 return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
1248 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
1251 struct stlink_usb_handle_s *h = handle;
1253 assert(handle != NULL);
1255 stlink_usb_init_buffer(handle, STLINK_NULL_EP, 0);
1258 case STLINK_MODE_DEBUG_JTAG:
1259 case STLINK_MODE_DEBUG_SWD:
1260 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1261 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
1263 case STLINK_MODE_DEBUG_SWIM:
1264 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1265 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
1267 case STLINK_MODE_DFU:
1268 h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
1269 h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
1271 case STLINK_MODE_MASS:
1276 res = stlink_usb_xfer_noerrcheck(handle, 0, 0);
1278 if (res != ERROR_OK)
1284 static int stlink_usb_assert_srst(void *handle, int srst);
1286 static enum stlink_mode stlink_get_mode(enum hl_transports t)
1289 case HL_TRANSPORT_SWD:
1290 return STLINK_MODE_DEBUG_SWD;
1291 case HL_TRANSPORT_JTAG:
1292 return STLINK_MODE_DEBUG_JTAG;
1293 case HL_TRANSPORT_SWIM:
1294 return STLINK_MODE_DEBUG_SWIM;
1296 return STLINK_MODE_UNKNOWN;
1301 static int stlink_usb_init_mode(void *handle, bool connect_under_reset, int initial_interface_speed)
1305 enum stlink_mode emode;
1306 struct stlink_usb_handle_s *h = handle;
1308 assert(handle != NULL);
1310 res = stlink_usb_current_mode(handle, &mode);
1312 if (res != ERROR_OK)
1315 LOG_DEBUG("MODE: 0x%02X", mode);
1317 /* try to exit current mode */
1319 case STLINK_DEV_DFU_MODE:
1320 emode = STLINK_MODE_DFU;
1322 case STLINK_DEV_DEBUG_MODE:
1323 emode = STLINK_MODE_DEBUG_SWD;
1325 case STLINK_DEV_SWIM_MODE:
1326 emode = STLINK_MODE_DEBUG_SWIM;
1328 case STLINK_DEV_BOOTLOADER_MODE:
1329 case STLINK_DEV_MASS_MODE:
1331 emode = STLINK_MODE_UNKNOWN;
1335 if (emode != STLINK_MODE_UNKNOWN) {
1336 res = stlink_usb_mode_leave(handle, emode);
1338 if (res != ERROR_OK)
1342 res = stlink_usb_current_mode(handle, &mode);
1344 if (res != ERROR_OK)
1347 /* we check the target voltage here as an aid to debugging connection problems.
1348 * the stlink requires the target Vdd to be connected for reliable debugging.
1349 * this cmd is supported in all modes except DFU
1351 if (mode != STLINK_DEV_DFU_MODE) {
1353 float target_voltage;
1355 /* check target voltage (if supported) */
1356 res = stlink_usb_check_voltage(h, &target_voltage);
1358 if (res != ERROR_OK) {
1359 if (res != ERROR_COMMAND_NOTFOUND)
1360 LOG_ERROR("voltage check failed");
1361 /* attempt to continue as it is not a catastrophic failure */
1363 /* check for a sensible target voltage, operating range is 1.65-5.5v
1364 * according to datasheet */
1365 if (target_voltage < 1.5)
1366 LOG_ERROR("target voltage may be too low for reliable debugging");
1370 LOG_DEBUG("MODE: 0x%02X", mode);
1372 /* set selected mode */
1373 emode = stlink_get_mode(h->transport);
1375 if (emode == STLINK_MODE_UNKNOWN) {
1376 LOG_ERROR("selected mode (transport) not supported");
1380 /* set the speed before entering the mode, as the chip discovery phase should be done at this speed too */
1381 if (h->transport == HL_TRANSPORT_JTAG) {
1382 if (h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ) {
1383 stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
1384 stlink_speed(h, initial_interface_speed, false);
1386 } else if (h->transport == HL_TRANSPORT_SWD) {
1387 if (h->version.flags & STLINK_F_HAS_SWD_SET_FREQ) {
1388 stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
1389 stlink_speed(h, initial_interface_speed, false);
1393 if (h->version.jtag_api == STLINK_JTAG_API_V3) {
1394 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
1396 stlink_get_com_freq(h, (h->transport == HL_TRANSPORT_JTAG), map);
1397 stlink_dump_speed_map(map, ARRAY_SIZE(map));
1398 stlink_speed(h, initial_interface_speed, false);
1401 /* preliminary SRST assert:
1402 * We want SRST is asserted before activating debug signals (mode_enter).
1403 * As the required mode has not been set, the adapter may not know what pin to use.
1404 * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
1405 * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
1406 * after power on, SWIM_RST stays unchanged */
1407 if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
1408 stlink_usb_assert_srst(handle, 0);
1409 /* do not check the return status here, we will
1410 proceed and enter the desired mode below
1411 and try asserting srst again. */
1413 res = stlink_usb_mode_enter(handle, emode);
1414 if (res != ERROR_OK)
1417 /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
1418 if (connect_under_reset) {
1419 res = stlink_usb_assert_srst(handle, 0);
1420 if (res != ERROR_OK)
1424 res = stlink_usb_current_mode(handle, &mode);
1426 if (res != ERROR_OK)
1429 LOG_DEBUG("MODE: 0x%02X", mode);
1434 /* request status from last swim request */
1435 static int stlink_swim_status(void *handle)
1437 struct stlink_usb_handle_s *h = handle;
1440 stlink_usb_init_buffer(handle, h->rx_ep, 4);
1441 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1442 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
1443 /* error is checked by the caller */
1444 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1445 if (res != ERROR_OK)
1450 the purpose of this function is unknown...
1451 capabilites? anyway for swim v6 it returns
1454 __attribute__((unused))
1455 static int stlink_swim_cap(void *handle, uint8_t *cap)
1457 struct stlink_usb_handle_s *h = handle;
1460 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1461 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1462 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1463 h->cmdbuf[h->cmdidx++] = 0x01;
1464 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1465 if (res != ERROR_OK)
1467 memcpy(cap, h->databuf, 8);
1471 /* debug dongle assert/deassert sreset line */
1472 static int stlink_swim_assert_reset(void *handle, int reset)
1474 struct stlink_usb_handle_s *h = handle;
1477 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1478 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1480 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1482 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1483 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1484 if (res != ERROR_OK)
1491 1.3ms low then 750Hz then 1.5kHz
1493 static int stlink_swim_enter(void *handle)
1495 struct stlink_usb_handle_s *h = handle;
1498 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1499 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1500 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1501 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1502 if (res != ERROR_OK)
1507 /* switch high/low speed swim */
1508 static int stlink_swim_speed(void *handle, int speed)
1510 struct stlink_usb_handle_s *h = handle;
1513 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1514 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1515 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1517 h->cmdbuf[h->cmdidx++] = 1;
1519 h->cmdbuf[h->cmdidx++] = 0;
1520 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1521 if (res != ERROR_OK)
1527 initiate srst from swim.
1528 nrst is pulled low for 50us.
1530 static int stlink_swim_generate_rst(void *handle)
1532 struct stlink_usb_handle_s *h = handle;
1535 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1536 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1537 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1538 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1539 if (res != ERROR_OK)
1545 send resyncronize sequence
1546 swim is pulled low for 16us
1547 reply is 64 clks low
1549 static int stlink_swim_resync(void *handle)
1551 struct stlink_usb_handle_s *h = handle;
1554 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1555 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1556 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_RESET;
1557 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1558 if (res != ERROR_OK)
1563 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1565 struct stlink_usb_handle_s *h = handle;
1568 unsigned int datalen = 0;
1569 int cmdsize = STLINK_CMD_SIZE_V2;
1571 if (len > STLINK_DATA_SIZE)
1574 if (h->version.stlink == 1)
1575 cmdsize = STLINK_SG_SIZE;
1577 stlink_usb_init_buffer(handle, h->tx_ep, 0);
1578 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1579 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1580 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1582 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1584 for (i = 0; i < len; i++) {
1585 if (h->cmdidx == cmdsize)
1586 h->databuf[datalen++] = *(data++);
1588 h->cmdbuf[h->cmdidx++] = *(data++);
1590 if (h->version.stlink == 1)
1591 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1593 res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1594 if (res != ERROR_OK)
1599 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1601 struct stlink_usb_handle_s *h = handle;
1604 if (len > STLINK_DATA_SIZE)
1607 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1608 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1609 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1610 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1612 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1614 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1615 if (res != ERROR_OK)
1618 stlink_usb_init_buffer(handle, h->rx_ep, len);
1619 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1620 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1621 res = stlink_usb_xfer_noerrcheck(handle, data, len);
1622 if (res != ERROR_OK)
1629 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1632 struct stlink_usb_handle_s *h = handle;
1634 assert(handle != NULL);
1636 /* there is no swim read core id cmd */
1637 if (h->transport == HL_TRANSPORT_SWIM) {
1642 stlink_usb_init_buffer(handle, h->rx_ep, 12);
1644 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1645 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1646 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1648 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1651 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_IDCODES;
1653 res = stlink_usb_xfer_errcheck(handle, h->databuf, 12);
1657 if (res != ERROR_OK)
1660 *idcode = le_to_h_u32(h->databuf + offset);
1662 LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1667 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1669 struct stlink_usb_handle_s *h = handle;
1672 assert(handle != NULL);
1674 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1676 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1677 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1678 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1681 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1682 if (res != ERROR_OK)
1685 *val = le_to_h_u32(h->databuf + 4);
1689 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1691 struct stlink_usb_handle_s *h = handle;
1693 assert(handle != NULL);
1695 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1697 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1698 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1699 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1701 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1702 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1704 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1707 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1711 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1713 struct stlink_usb_handle_s *h = handle;
1715 assert(handle != NULL);
1717 if (h->trace.enabled && (h->version.flags & STLINK_F_HAS_TRACE)) {
1720 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1722 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1723 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1725 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1726 if (res != ERROR_OK)
1729 size_t bytes_avail = le_to_h_u16(h->databuf);
1730 *size = bytes_avail < *size ? bytes_avail : *size - 1;
1733 res = stlink_usb_read_trace(handle, buf, *size);
1734 if (res != ERROR_OK)
1743 static enum target_state stlink_usb_v2_get_status(void *handle)
1748 result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1749 if (result != ERROR_OK)
1750 return TARGET_UNKNOWN;
1752 if (status & S_HALT)
1753 return TARGET_HALTED;
1754 else if (status & S_RESET_ST)
1755 return TARGET_RESET;
1757 return TARGET_RUNNING;
1761 static enum target_state stlink_usb_state(void *handle)
1764 struct stlink_usb_handle_s *h = handle;
1766 assert(handle != NULL);
1768 if (h->transport == HL_TRANSPORT_SWIM) {
1769 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1770 if (res != ERROR_OK)
1771 return TARGET_UNKNOWN;
1773 res = stlink_swim_resync(handle);
1774 if (res != ERROR_OK)
1775 return TARGET_UNKNOWN;
1780 if (h->reconnect_pending) {
1781 LOG_INFO("Previous state query failed, trying to reconnect");
1782 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1784 if (res != ERROR_OK)
1785 return TARGET_UNKNOWN;
1787 h->reconnect_pending = false;
1790 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1791 res = stlink_usb_v2_get_status(handle);
1792 if (res == TARGET_UNKNOWN)
1793 h->reconnect_pending = true;
1797 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1799 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1800 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
1802 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1804 if (res != ERROR_OK)
1805 return TARGET_UNKNOWN;
1807 if (h->databuf[0] == STLINK_CORE_RUNNING)
1808 return TARGET_RUNNING;
1809 if (h->databuf[0] == STLINK_CORE_HALTED)
1810 return TARGET_HALTED;
1812 h->reconnect_pending = true;
1814 return TARGET_UNKNOWN;
1817 static int stlink_usb_assert_srst(void *handle, int srst)
1819 struct stlink_usb_handle_s *h = handle;
1821 assert(handle != NULL);
1823 if (h->transport == HL_TRANSPORT_SWIM)
1824 return stlink_swim_assert_reset(handle, srst);
1826 if (h->version.stlink == 1)
1827 return ERROR_COMMAND_NOTFOUND;
1829 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1831 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1832 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
1833 h->cmdbuf[h->cmdidx++] = srst;
1835 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1839 static void stlink_usb_trace_disable(void *handle)
1842 struct stlink_usb_handle_s *h = handle;
1844 assert(handle != NULL);
1846 assert(h->version.flags & STLINK_F_HAS_TRACE);
1848 LOG_DEBUG("Tracing: disable");
1850 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1851 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1852 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
1853 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1855 if (res == ERROR_OK)
1856 h->trace.enabled = false;
1861 static int stlink_usb_trace_enable(void *handle)
1864 struct stlink_usb_handle_s *h = handle;
1866 assert(handle != NULL);
1868 if (h->version.flags & STLINK_F_HAS_TRACE) {
1869 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1871 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1872 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
1873 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
1875 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
1878 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1880 if (res == ERROR_OK) {
1881 h->trace.enabled = true;
1882 LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
1885 LOG_ERROR("Tracing is not supported by this version.");
1893 static int stlink_usb_reset(void *handle)
1895 struct stlink_usb_handle_s *h = handle;
1898 assert(handle != NULL);
1900 if (h->transport == HL_TRANSPORT_SWIM)
1901 return stlink_swim_generate_rst(handle);
1903 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1905 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1907 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1908 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
1910 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
1912 retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
1913 if (retval != ERROR_OK)
1916 if (h->trace.enabled) {
1917 stlink_usb_trace_disable(h);
1918 return stlink_usb_trace_enable(h);
1925 static int stlink_usb_run(void *handle)
1928 struct stlink_usb_handle_s *h = handle;
1930 assert(handle != NULL);
1932 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1933 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
1938 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1940 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1941 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
1943 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1947 static int stlink_usb_halt(void *handle)
1950 struct stlink_usb_handle_s *h = handle;
1952 assert(handle != NULL);
1954 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1955 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1960 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1962 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1963 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
1965 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1969 static int stlink_usb_step(void *handle)
1971 struct stlink_usb_handle_s *h = handle;
1973 assert(handle != NULL);
1975 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1976 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
1977 * that the Cortex-M3 currently does. */
1978 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
1979 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
1980 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1983 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1985 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1986 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
1988 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1992 static int stlink_usb_read_regs(void *handle)
1995 struct stlink_usb_handle_s *h = handle;
1997 assert(handle != NULL);
1999 stlink_usb_init_buffer(handle, h->rx_ep, 88);
2001 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2002 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2004 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
2005 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 84);
2006 /* regs data from offset 0 */
2008 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
2009 res = stlink_usb_xfer_errcheck(handle, h->databuf, 88);
2010 /* status at offset 0, regs data from offset 4 */
2017 static int stlink_usb_read_reg(void *handle, int num, uint32_t *val)
2020 struct stlink_usb_handle_s *h = handle;
2022 assert(handle != NULL);
2024 stlink_usb_init_buffer(handle, h->rx_ep, h->version.jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
2026 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2027 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2028 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
2030 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
2031 h->cmdbuf[h->cmdidx++] = num;
2033 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2034 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
2035 if (res != ERROR_OK)
2037 *val = le_to_h_u32(h->databuf);
2040 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
2041 if (res != ERROR_OK)
2043 *val = le_to_h_u32(h->databuf + 4);
2049 static int stlink_usb_write_reg(void *handle, int num, uint32_t val)
2051 struct stlink_usb_handle_s *h = handle;
2053 assert(handle != NULL);
2055 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2057 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2058 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2059 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
2061 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
2062 h->cmdbuf[h->cmdidx++] = num;
2063 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
2066 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2069 static int stlink_usb_get_rw_status(void *handle)
2071 struct stlink_usb_handle_s *h = handle;
2073 assert(handle != NULL);
2075 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2078 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2080 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2081 if (h->version.flags & STLINK_F_HAS_GETLASTRWSTATUS2) {
2082 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS2;
2083 return stlink_usb_xfer_errcheck(handle, h->databuf, 12);
2085 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
2086 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2091 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
2095 uint16_t read_len = len;
2096 struct stlink_usb_handle_s *h = handle;
2098 assert(handle != NULL);
2100 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2101 if (len > stlink_usb_block(h)) {
2102 LOG_DEBUG("max buffer (%d) length exceeded", stlink_usb_block(h));
2106 stlink_usb_init_buffer(handle, h->rx_ep, read_len);
2108 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2109 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
2110 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2112 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2115 /* we need to fix read length for single bytes */
2119 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, read_len);
2121 if (res != ERROR_OK)
2124 memcpy(buffer, h->databuf, len);
2126 return stlink_usb_get_rw_status(handle);
2130 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
2131 const uint8_t *buffer)
2134 struct stlink_usb_handle_s *h = handle;
2136 assert(handle != NULL);
2138 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2139 if (len > stlink_usb_block(h)) {
2140 LOG_DEBUG("max buffer length (%d) exceeded", stlink_usb_block(h));
2144 stlink_usb_init_buffer(handle, h->tx_ep, len);
2146 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2147 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
2148 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2150 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2153 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2155 if (res != ERROR_OK)
2158 return stlink_usb_get_rw_status(handle);
2162 static int stlink_usb_read_mem16(void *handle, uint32_t addr, uint16_t len,
2166 struct stlink_usb_handle_s *h = handle;
2168 assert(handle != NULL);
2170 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2171 return ERROR_COMMAND_NOTFOUND;
2173 /* data must be a multiple of 2 and half-word aligned */
2174 if (len % 2 || addr % 2) {
2175 LOG_DEBUG("Invalid data alignment");
2176 return ERROR_TARGET_UNALIGNED_ACCESS;
2179 stlink_usb_init_buffer(handle, h->rx_ep, len);
2181 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2182 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READMEM_16BIT;
2183 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2185 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2188 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2190 if (res != ERROR_OK)
2193 memcpy(buffer, h->databuf, len);
2195 return stlink_usb_get_rw_status(handle);
2199 static int stlink_usb_write_mem16(void *handle, uint32_t addr, uint16_t len,
2200 const uint8_t *buffer)
2203 struct stlink_usb_handle_s *h = handle;
2205 assert(handle != NULL);
2207 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2208 return ERROR_COMMAND_NOTFOUND;
2210 /* data must be a multiple of 2 and half-word aligned */
2211 if (len % 2 || addr % 2) {
2212 LOG_DEBUG("Invalid data alignment");
2213 return ERROR_TARGET_UNALIGNED_ACCESS;
2216 stlink_usb_init_buffer(handle, h->tx_ep, len);
2218 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2219 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEMEM_16BIT;
2220 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2222 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2225 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2227 if (res != ERROR_OK)
2230 return stlink_usb_get_rw_status(handle);
2234 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
2238 struct stlink_usb_handle_s *h = handle;
2240 assert(handle != NULL);
2242 /* data must be a multiple of 4 and word aligned */
2243 if (len % 4 || addr % 4) {
2244 LOG_DEBUG("Invalid data alignment");
2245 return ERROR_TARGET_UNALIGNED_ACCESS;
2248 stlink_usb_init_buffer(handle, h->rx_ep, len);
2250 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2251 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
2252 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2254 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2257 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2259 if (res != ERROR_OK)
2262 memcpy(buffer, h->databuf, len);
2264 return stlink_usb_get_rw_status(handle);
2268 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
2269 const uint8_t *buffer)
2272 struct stlink_usb_handle_s *h = handle;
2274 assert(handle != NULL);
2276 /* data must be a multiple of 4 and word aligned */
2277 if (len % 4 || addr % 4) {
2278 LOG_DEBUG("Invalid data alignment");
2279 return ERROR_TARGET_UNALIGNED_ACCESS;
2282 stlink_usb_init_buffer(handle, h->tx_ep, len);
2284 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2285 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
2286 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2288 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2291 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2293 if (res != ERROR_OK)
2296 return stlink_usb_get_rw_status(handle);
2299 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
2301 uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
2302 if (max_tar_block == 0)
2304 return max_tar_block;
2307 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
2308 uint32_t count, uint8_t *buffer)
2310 int retval = ERROR_OK;
2311 uint32_t bytes_remaining;
2313 struct stlink_usb_handle_s *h = handle;
2315 /* calculate byte count */
2318 /* switch to 8 bit if stlink does not support 16 bit memory read */
2319 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2324 bytes_remaining = (size != 1) ? \
2325 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2327 if (count < bytes_remaining)
2328 bytes_remaining = count;
2330 if (h->transport == HL_TRANSPORT_SWIM) {
2331 retval = stlink_swim_readbytes(handle, addr, bytes_remaining, buffer);
2332 if (retval != ERROR_OK)
2336 * all stlink support 8/32bit memory read/writes and only from
2337 * stlink V2J26 there is support for 16 bit memory read/write.
2338 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2343 /* When in jtag mode the stlink uses the auto-increment functionality.
2344 * However it expects us to pass the data correctly, this includes
2345 * alignment and any page boundaries. We already do this as part of the
2346 * adi_v5 implementation, but the stlink is a hla adapter and so this
2347 * needs implementing manually.
2348 * currently this only affects jtag mode, according to ST they do single
2349 * access in SWD mode - but this may change and so we do it for both modes */
2351 /* we first need to check for any unaligned bytes */
2352 if (addr & (size - 1)) {
2354 uint32_t head_bytes = size - (addr & (size - 1));
2355 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
2356 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2357 usleep((1<<retries++) * 1000);
2360 if (retval != ERROR_OK)
2362 buffer += head_bytes;
2364 count -= head_bytes;
2365 bytes_remaining -= head_bytes;
2368 if (bytes_remaining & (size - 1))
2369 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
2371 retval = stlink_usb_read_mem16(handle, addr, bytes_remaining, buffer);
2373 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
2375 retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
2377 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2378 usleep((1<<retries++) * 1000);
2381 if (retval != ERROR_OK)
2384 buffer += bytes_remaining;
2385 addr += bytes_remaining;
2386 count -= bytes_remaining;
2392 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
2393 uint32_t count, const uint8_t *buffer)
2395 int retval = ERROR_OK;
2396 uint32_t bytes_remaining;
2398 struct stlink_usb_handle_s *h = handle;
2400 /* calculate byte count */
2403 /* switch to 8 bit if stlink does not support 16 bit memory read */
2404 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2409 bytes_remaining = (size != 1) ? \
2410 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2412 if (count < bytes_remaining)
2413 bytes_remaining = count;
2415 if (h->transport == HL_TRANSPORT_SWIM) {
2416 retval = stlink_swim_writebytes(handle, addr, bytes_remaining, buffer);
2417 if (retval != ERROR_OK)
2421 * all stlink support 8/32bit memory read/writes and only from
2422 * stlink V2J26 there is support for 16 bit memory read/write.
2423 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2428 /* When in jtag mode the stlink uses the auto-increment functionality.
2429 * However it expects us to pass the data correctly, this includes
2430 * alignment and any page boundaries. We already do this as part of the
2431 * adi_v5 implementation, but the stlink is a hla adapter and so this
2432 * needs implementing manually.
2433 * currently this only affects jtag mode, according to ST they do single
2434 * access in SWD mode - but this may change and so we do it for both modes */
2436 /* we first need to check for any unaligned bytes */
2437 if (addr & (size - 1)) {
2439 uint32_t head_bytes = size - (addr & (size - 1));
2440 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
2441 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2442 usleep((1<<retries++) * 1000);
2445 if (retval != ERROR_OK)
2447 buffer += head_bytes;
2449 count -= head_bytes;
2450 bytes_remaining -= head_bytes;
2453 if (bytes_remaining & (size - 1))
2454 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
2456 retval = stlink_usb_write_mem16(handle, addr, bytes_remaining, buffer);
2458 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
2461 retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
2462 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2463 usleep((1<<retries++) * 1000);
2466 if (retval != ERROR_OK)
2469 buffer += bytes_remaining;
2470 addr += bytes_remaining;
2471 count -= bytes_remaining;
2478 static int stlink_usb_override_target(const char *targetname)
2480 return !strcmp(targetname, "cortex_m");
2483 static int stlink_speed_swim(void *handle, int khz, bool query)
2486 we dont care what the khz rate is
2487 we only have low and high speed...
2488 before changing speed the SWIM_CSR HS bit
2492 stlink_swim_speed(handle, 0);
2494 stlink_swim_speed(handle, 1);
2498 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
2501 int speed_index = -1;
2502 int speed_diff = INT_MAX;
2503 int last_valid_speed = -1;
2506 for (i = 0; i < map_size; i++) {
2509 last_valid_speed = i;
2510 if (khz == map[i].speed) {
2514 int current_diff = khz - map[i].speed;
2515 /* get abs value for comparison */
2516 current_diff = (current_diff > 0) ? current_diff : -current_diff;
2517 if ((current_diff < speed_diff) && khz >= map[i].speed) {
2518 speed_diff = current_diff;
2524 if (speed_index == -1) {
2525 /* this will only be here if we cannot match the slow speed.
2526 * use the slowest speed we support.*/
2527 speed_index = last_valid_speed;
2529 } else if (i == map_size)
2532 if (!match && query) {
2533 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz", \
2534 khz, map[speed_index].speed);
2540 static int stlink_speed_swd(void *handle, int khz, bool query)
2543 struct stlink_usb_handle_s *h = handle;
2545 /* old firmware cannot change it */
2546 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
2549 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
2550 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
2553 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
2554 if (result != ERROR_OK) {
2555 LOG_ERROR("Unable to set adapter speed");
2560 return stlink_khz_to_speed_map_swd[speed_index].speed;
2563 static int stlink_speed_jtag(void *handle, int khz, bool query)
2566 struct stlink_usb_handle_s *h = handle;
2568 /* old firmware cannot change it */
2569 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
2572 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2573 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2576 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2577 if (result != ERROR_OK) {
2578 LOG_ERROR("Unable to set adapter speed");
2583 return stlink_khz_to_speed_map_jtag[speed_index].speed;
2586 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2590 LOG_DEBUG("Supported clock speeds are:");
2591 for (i = 0; i < map_size; i++)
2593 LOG_DEBUG("%d kHz", map[i].speed);
2596 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map)
2598 struct stlink_usb_handle_s *h = handle;
2601 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2602 LOG_ERROR("Unknown command");
2606 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2608 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2609 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_COM_FREQ;
2610 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2612 int res = stlink_usb_xfer_errcheck(handle, h->databuf, 52);
2614 int size = h->databuf[8];
2616 if (size > STLINK_V3_MAX_FREQ_NB)
2617 size = STLINK_V3_MAX_FREQ_NB;
2619 for (i = 0; i < size; i++) {
2620 map[i].speed = le_to_h_u32(&h->databuf[12 + 4 * i]);
2621 map[i].speed_divisor = i;
2624 /* set to zero all the next entries */
2625 for (i = size; i < STLINK_V3_MAX_FREQ_NB; i++)
2631 static int stlink_set_com_freq(void *handle, bool is_jtag, unsigned int frequency)
2633 struct stlink_usb_handle_s *h = handle;
2635 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2636 LOG_ERROR("Unknown command");
2640 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2642 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2643 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_SET_COM_FREQ;
2644 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2645 h->cmdbuf[h->cmdidx++] = 0;
2647 h_u32_to_le(&h->cmdbuf[4], frequency);
2649 return stlink_usb_xfer_errcheck(handle, h->databuf, 8);
2652 static int stlink_speed_v3(void *handle, bool is_jtag, int khz, bool query)
2654 struct stlink_usb_handle_s *h = handle;
2656 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
2658 stlink_get_com_freq(h, is_jtag, map);
2660 speed_index = stlink_match_speed_map(map, ARRAY_SIZE(map), khz, query);
2663 int result = stlink_set_com_freq(h, is_jtag, map[speed_index].speed);
2664 if (result != ERROR_OK) {
2665 LOG_ERROR("Unable to set adapter speed");
2669 return map[speed_index].speed;
2672 static int stlink_speed(void *handle, int khz, bool query)
2674 struct stlink_usb_handle_s *h = handle;
2679 switch (h->transport) {
2680 case HL_TRANSPORT_SWIM:
2681 return stlink_speed_swim(handle, khz, query);
2683 case HL_TRANSPORT_SWD:
2684 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2685 return stlink_speed_v3(handle, false, khz, query);
2687 return stlink_speed_swd(handle, khz, query);
2689 case HL_TRANSPORT_JTAG:
2690 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2691 return stlink_speed_v3(handle, true, khz, query);
2693 return stlink_speed_jtag(handle, khz, query);
2703 static int stlink_usb_close(void *handle)
2707 enum stlink_mode emode;
2708 struct stlink_usb_handle_s *h = handle;
2711 res = stlink_usb_current_mode(handle, &mode);
2714 /* do not exit if return code != ERROR_OK,
2715 it prevents us from closing jtag_libusb */
2717 if (res == ERROR_OK) {
2718 /* try to exit current mode */
2720 case STLINK_DEV_DFU_MODE:
2721 emode = STLINK_MODE_DFU;
2723 case STLINK_DEV_DEBUG_MODE:
2724 emode = STLINK_MODE_DEBUG_SWD;
2726 case STLINK_DEV_SWIM_MODE:
2727 emode = STLINK_MODE_DEBUG_SWIM;
2729 case STLINK_DEV_BOOTLOADER_MODE:
2730 case STLINK_DEV_MASS_MODE:
2732 emode = STLINK_MODE_UNKNOWN;
2736 if (emode != STLINK_MODE_UNKNOWN)
2737 stlink_usb_mode_leave(handle, emode);
2738 /* do not check return code, it prevent
2739 us from closing jtag_libusb */
2743 jtag_libusb_close(h->fd);
2750 /* Compute ST-Link serial number from the device descriptor
2751 * this function will help to work-around a bug in old ST-Link/V2 DFU
2752 * the buggy DFU returns an incorrect serial in the USB descriptor
2753 * example for the following serial "57FF72067265575742132067"
2754 * - the correct descriptor serial is:
2755 * 0x32, 0x03, 0x35, 0x00, 0x37, 0x00, 0x46, 0x00, 0x46, 0x00, 0x37, 0x00, 0x32, 0x00 ...
2756 * this contains the length (0x32 = 50), the type (0x3 = DT_STRING) and the serial in unicode format
2757 * the serial part is: 0x0035, 0x0037, 0x0046, 0x0046, 0x0037, 0x0032 ... >> 57FF72 ...
2758 * this format could be read correctly by 'libusb_get_string_descriptor_ascii'
2759 * so this case is managed by libusb_helper::string_descriptor_equal
2760 * - the buggy DFU is not doing any unicode conversion and returns a raw serial data in the descriptor
2761 * 0x1a, 0x03, 0x57, 0x00, 0xFF, 0x00, 0x72, 0x00 ...
2763 * based on the length (0x1a = 26) we could easily decide if we have to fixup the serial
2764 * and then we have just to convert the raw data into printable characters using sprintf
2766 char *stlink_usb_get_alternate_serial(libusb_device_handle *device,
2767 struct libusb_device_descriptor *dev_desc)
2770 unsigned char desc_serial[(STLINK_SERIAL_LEN + 1) * 2];
2772 if (dev_desc->iSerialNumber == 0)
2775 /* get the LANGID from String Descriptor Zero */
2776 usb_retval = libusb_get_string_descriptor(device, 0, 0, desc_serial,
2777 sizeof(desc_serial));
2779 if (usb_retval < LIBUSB_SUCCESS) {
2780 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
2781 libusb_error_name(usb_retval), usb_retval);
2783 } else if (usb_retval < 4) {
2784 /* the size should be least 4 bytes to contain a minimum of 1 supported LANGID */
2785 LOG_ERROR("could not get the LANGID");
2789 uint32_t langid = desc_serial[2] | (desc_serial[3] << 8);
2791 /* get the serial */
2792 usb_retval = libusb_get_string_descriptor(device, dev_desc->iSerialNumber,
2793 langid, desc_serial, sizeof(desc_serial));
2795 unsigned char len = desc_serial[0];
2797 if (usb_retval < LIBUSB_SUCCESS) {
2798 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
2799 libusb_error_name(usb_retval), usb_retval);
2801 } else if (desc_serial[1] != LIBUSB_DT_STRING || len > usb_retval) {
2802 LOG_ERROR("invalid string in ST-LINK USB serial descriptor");
2806 if (len == ((STLINK_SERIAL_LEN + 1) * 2)) {
2807 /* good ST-Link adapter, this case is managed by
2808 * libusb::libusb_get_string_descriptor_ascii */
2810 } else if (len != ((STLINK_SERIAL_LEN / 2 + 1) * 2)) {
2811 LOG_ERROR("unexpected serial length (%d) in descriptor", len);
2815 /* else (len == 26) => buggy ST-Link */
2817 char *alternate_serial = malloc((STLINK_SERIAL_LEN + 1) * sizeof(char));
2818 if (alternate_serial == NULL)
2821 for (unsigned int i = 0; i < STLINK_SERIAL_LEN; i += 2)
2822 sprintf(alternate_serial + i, "%02X", desc_serial[i + 2]);
2824 alternate_serial[STLINK_SERIAL_LEN] = '\0';
2826 return alternate_serial;
2830 static int stlink_usb_open(struct hl_interface_param_s *param, void **fd)
2832 int err, retry_count = 1;
2833 struct stlink_usb_handle_s *h;
2835 LOG_DEBUG("stlink_usb_open");
2837 h = calloc(1, sizeof(struct stlink_usb_handle_s));
2840 LOG_DEBUG("malloc failed");
2844 h->transport = param->transport;
2846 for (unsigned i = 0; param->vid[i]; i++) {
2847 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
2848 param->transport, param->vid[i], param->pid[i],
2849 param->serial ? param->serial : "");
2853 On certain host USB configurations(e.g. MacBook Air)
2854 STLINKv2 dongle seems to have its FW in a funky state if,
2855 after plugging it in, you try to use openocd with it more
2856 then once (by launching and closing openocd). In cases like
2857 that initial attempt to read the FW info via
2858 stlink_usb_version will fail and the device has to be reset
2859 in order to become operational.
2862 if (jtag_libusb_open(param->vid, param->pid, param->serial,
2863 &h->fd, stlink_usb_get_alternate_serial) != ERROR_OK) {
2864 LOG_ERROR("open failed");
2868 jtag_libusb_set_configuration(h->fd, 0);
2870 if (libusb_claim_interface(h->fd, 0) != ERROR_OK) {
2871 LOG_DEBUG("claim interface failed");
2875 /* RX EP is common for all versions */
2876 h->rx_ep = STLINK_RX_EP;
2879 if (jtag_libusb_get_pid(libusb_get_device(h->fd), &pid) != ERROR_OK) {
2880 LOG_DEBUG("libusb_get_pid failed");
2884 /* wrap version for first read */
2887 h->version.stlink = 1;
2888 h->tx_ep = STLINK_TX_EP;
2890 case STLINK_V3_USBLOADER_PID:
2891 case STLINK_V3E_PID:
2892 case STLINK_V3S_PID:
2893 case STLINK_V3_2VCP_PID:
2894 h->version.stlink = 3;
2895 h->tx_ep = STLINK_V2_1_TX_EP;
2896 h->trace_ep = STLINK_V2_1_TRACE_EP;
2898 case STLINK_V2_1_PID:
2899 case STLINK_V2_1_NO_MSD_PID:
2900 h->version.stlink = 2;
2901 h->tx_ep = STLINK_V2_1_TX_EP;
2902 h->trace_ep = STLINK_V2_1_TRACE_EP;
2905 /* fall through - we assume V2 to be the default version*/
2907 h->version.stlink = 2;
2908 h->tx_ep = STLINK_TX_EP;
2909 h->trace_ep = STLINK_TRACE_EP;
2913 /* get the device version */
2914 err = stlink_usb_version(h);
2916 if (err == ERROR_OK) {
2918 } else if (h->version.stlink == 1 ||
2920 LOG_ERROR("read version failed");
2923 err = libusb_release_interface(h->fd, 0);
2924 if (err != ERROR_OK) {
2925 LOG_ERROR("release interface failed");
2929 err = libusb_reset_device(h->fd);
2930 if (err != ERROR_OK) {
2931 LOG_ERROR("reset device failed");
2935 jtag_libusb_close(h->fd);
2937 Give the device one second to settle down and
2940 usleep(1 * 1000 * 1000);
2945 /* check if mode is supported */
2948 switch (h->transport) {
2949 case HL_TRANSPORT_SWD:
2950 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2953 case HL_TRANSPORT_JTAG:
2954 if (h->version.jtag == 0)
2957 case HL_TRANSPORT_SWIM:
2958 if (h->version.swim == 0)
2966 if (err != ERROR_OK) {
2967 LOG_ERROR("mode (transport) not supported by device");
2971 /* initialize the debug hardware */
2972 err = stlink_usb_init_mode(h, param->connect_under_reset, param->initial_interface_speed);
2974 if (err != ERROR_OK) {
2975 LOG_ERROR("init mode failed (unable to connect to the target)");
2979 if (h->transport == HL_TRANSPORT_SWIM) {
2980 err = stlink_swim_enter(h);
2981 if (err != ERROR_OK) {
2982 LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
2986 h->max_mem_packet = STLINK_DATA_SIZE;
2990 /* get cpuid, so we can determine the max page size
2991 * start with a safe default */
2992 h->max_mem_packet = (1 << 10);
2995 err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
2996 if (err == ERROR_OK) {
2997 uint32_t cpuid = le_to_h_u32(buffer);
2998 int i = (cpuid >> 4) & 0xf;
2999 if (i == 4 || i == 3) {
3000 /* Cortex-M3/M4 has 4096 bytes autoincrement range */
3001 h->max_mem_packet = (1 << 12);
3005 LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
3012 stlink_usb_close(h);
3017 int stlink_config_trace(void *handle, bool enabled,
3018 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
3019 unsigned int *trace_freq, unsigned int traceclkin_freq,
3020 uint16_t *prescaler)
3022 struct stlink_usb_handle_s *h = handle;
3025 if (enabled && (!(h->version.flags & STLINK_F_HAS_TRACE) ||
3026 pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART)) {
3027 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
3032 stlink_usb_trace_disable(h);
3036 if (*trace_freq > STLINK_TRACE_MAX_HZ) {
3037 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
3038 STLINK_TRACE_MAX_HZ);
3042 stlink_usb_trace_disable(h);
3045 *trace_freq = STLINK_TRACE_MAX_HZ;
3047 presc = traceclkin_freq / *trace_freq;
3049 if (traceclkin_freq % *trace_freq > 0)
3052 if (presc > TPIU_ACPR_MAX_SWOSCALER) {
3053 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
3059 h->trace.source_hz = *trace_freq;
3061 return stlink_usb_trace_enable(h);
3065 static int stlink_usb_init_access_port(void *handle, unsigned char ap_num)
3067 struct stlink_usb_handle_s *h = handle;
3069 assert(handle != NULL);
3071 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3072 return ERROR_COMMAND_NOTFOUND;
3074 LOG_DEBUG_IO("init ap_num = %d", ap_num);
3075 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3076 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3077 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_INIT_AP;
3078 h->cmdbuf[h->cmdidx++] = ap_num;
3080 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3084 static int stlink_usb_close_access_port(void *handle, unsigned char ap_num)
3086 struct stlink_usb_handle_s *h = handle;
3088 assert(handle != NULL);
3090 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3091 return ERROR_COMMAND_NOTFOUND;
3093 LOG_DEBUG_IO("close ap_num = %d", ap_num);
3094 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3095 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3096 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_CLOSE_AP_DBG;
3097 h->cmdbuf[h->cmdidx++] = ap_num;
3099 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3103 static int stlink_read_dap_register(void *handle, unsigned short dap_port,
3104 unsigned short addr, uint32_t *val)
3106 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 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3115 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3116 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_DAP_REG;
3117 h_u16_to_le(&h->cmdbuf[2], dap_port);
3118 h_u16_to_le(&h->cmdbuf[4], addr);
3120 retval = stlink_usb_xfer_errcheck(handle, h->databuf, 8);
3121 *val = le_to_h_u32(h->databuf + 4);
3122 LOG_DEBUG_IO("dap_port_read = %d, addr = 0x%x, value = 0x%x", dap_port, addr, *val);
3127 static int stlink_write_dap_register(void *handle, unsigned short dap_port,
3128 unsigned short addr, uint32_t val)
3130 struct stlink_usb_handle_s *h = handle;
3132 assert(handle != NULL);
3134 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3135 return ERROR_COMMAND_NOTFOUND;
3137 LOG_DEBUG_IO("dap_write port = %d, addr = 0x%x, value = 0x%x", dap_port, addr, val);
3138 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3139 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3140 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITE_DAP_REG;
3141 h_u16_to_le(&h->cmdbuf[2], dap_port);
3142 h_u16_to_le(&h->cmdbuf[4], addr);
3143 h_u32_to_le(&h->cmdbuf[6], val);
3144 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3148 struct hl_layout_api_s stlink_usb_layout_api = {
3150 .open = stlink_usb_open,
3152 .close = stlink_usb_close,
3154 .idcode = stlink_usb_idcode,
3156 .state = stlink_usb_state,
3158 .reset = stlink_usb_reset,
3160 .assert_srst = stlink_usb_assert_srst,
3162 .run = stlink_usb_run,
3164 .halt = stlink_usb_halt,
3166 .step = stlink_usb_step,
3168 .read_regs = stlink_usb_read_regs,
3170 .read_reg = stlink_usb_read_reg,
3172 .write_reg = stlink_usb_write_reg,
3174 .read_mem = stlink_usb_read_mem,
3176 .write_mem = stlink_usb_write_mem,
3178 .write_debug_reg = stlink_usb_write_debug_reg,
3180 .override_target = stlink_usb_override_target,
3182 .speed = stlink_speed,
3184 .config_trace = stlink_config_trace,
3186 .poll_trace = stlink_usb_trace_read,
3189 /*****************************************************************************
3190 * DAP direct interface
3193 static struct stlink_usb_handle_s *stlink_dap_handle;
3194 static struct hl_interface_param_s stlink_dap_param;
3195 static DECLARE_BITMAP(opened_ap, DP_APSEL_MAX + 1);
3196 static int stlink_dap_error = ERROR_OK;
3198 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3202 static int stlink_dap_record_error(int error)
3204 if (stlink_dap_error == ERROR_OK)
3205 stlink_dap_error = error;
3210 static int stlink_dap_get_and_clear_error(void)
3212 int retval = stlink_dap_error;
3213 stlink_dap_error = ERROR_OK;
3218 static int stlink_dap_open_ap(unsigned short apsel)
3222 /* nothing to do on old versions */
3223 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3226 if (apsel > DP_APSEL_MAX)
3229 if (test_bit(apsel, opened_ap))
3232 retval = stlink_usb_init_access_port(stlink_dap_handle, apsel);
3233 if (retval != ERROR_OK)
3236 LOG_DEBUG("AP %d enabled", apsel);
3237 set_bit(apsel, opened_ap);
3242 static int stlink_dap_closeall_ap(void)
3246 /* nothing to do on old versions */
3247 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3250 for (apsel = 0; apsel <= DP_APSEL_MAX; apsel++) {
3251 if (!test_bit(apsel, opened_ap))
3253 retval = stlink_usb_close_access_port(stlink_dap_handle, apsel);
3254 if (retval != ERROR_OK)
3256 clear_bit(apsel, opened_ap);
3262 static int stlink_dap_reinit_interface(void)
3265 enum stlink_mode mode;
3268 * On JTAG only, it should be enough to call stlink_usb_reset(). But on
3269 * some firmware version it does not work as expected, and there is no
3270 * equivalent for SWD.
3271 * At least for now, to reset the interface quit from JTAG/SWD mode then
3272 * select the mode again.
3275 mode = stlink_get_mode(stlink_dap_param.transport);
3276 if (!stlink_dap_handle->reconnect_pending) {
3277 stlink_dap_handle->reconnect_pending = true;
3278 stlink_usb_mode_leave(stlink_dap_handle, mode);
3281 retval = stlink_usb_mode_enter(stlink_dap_handle, mode);
3282 if (retval != ERROR_OK)
3285 stlink_dap_handle->reconnect_pending = false;
3286 /* on new FW, calling mode-leave closes all the opened AP; reopen them! */
3287 if (stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT)
3288 for (int apsel = 0; apsel <= DP_APSEL_MAX; apsel++)
3289 if (test_bit(apsel, opened_ap)) {
3290 clear_bit(apsel, opened_ap);
3291 stlink_dap_open_ap(apsel);
3297 static int stlink_dap_op_connect(struct adiv5_dap *dap)
3302 LOG_INFO("stlink_dap_op_connect(%sconnect)", dap->do_reconnect ? "re" : "");
3304 /* Check if we should reset srst already when connecting, but not if reconnecting. */
3305 if (!dap->do_reconnect) {
3306 enum reset_types jtag_reset_config = jtag_get_reset_config();
3308 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3309 if (jtag_reset_config & RESET_SRST_NO_GATING)
3310 adapter_assert_reset();
3312 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3316 dap->do_reconnect = false;
3317 dap_invalidate_cache(dap);
3319 retval = dap_dp_init(dap);
3320 if (retval != ERROR_OK) {
3321 dap->do_reconnect = true;
3325 retval = stlink_usb_idcode(stlink_dap_handle, &idcode);
3326 if (retval == ERROR_OK)
3327 LOG_INFO("%s %#8.8" PRIx32,
3328 (stlink_dap_handle->transport == HL_TRANSPORT_JTAG) ? "JTAG IDCODE" : "SWD DPIDR",
3331 dap->do_reconnect = true;
3337 static int stlink_dap_check_reconnect(struct adiv5_dap *dap)
3341 if (!dap->do_reconnect)
3344 retval = stlink_dap_reinit_interface();
3345 if (retval != ERROR_OK)
3348 return stlink_dap_op_connect(dap);
3352 static int stlink_dap_op_send_sequence(struct adiv5_dap *dap, enum swd_special_seq seq)
3354 /* Ignore the request */
3359 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3365 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3366 if (reg & 0x000000F0) {
3367 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3368 return ERROR_COMMAND_NOTFOUND;
3371 retval = stlink_dap_check_reconnect(dap);
3372 if (retval != ERROR_OK)
3375 data = data ? : &dummy;
3376 if (stlink_dap_handle->version.flags & STLINK_F_QUIRK_JTAG_DP_READ
3377 && stlink_dap_handle->transport == HL_TRANSPORT_JTAG) {
3378 /* Quirk required in JTAG. Read RDBUFF to get the data */
3379 retval = stlink_read_dap_register(stlink_dap_handle,
3380 STLINK_DEBUG_PORT_ACCESS, reg, &dummy);
3381 if (retval == ERROR_OK)
3382 retval = stlink_read_dap_register(stlink_dap_handle,
3383 STLINK_DEBUG_PORT_ACCESS, DP_RDBUFF, data);
3385 retval = stlink_read_dap_register(stlink_dap_handle,
3386 STLINK_DEBUG_PORT_ACCESS, reg, data);
3389 return stlink_dap_record_error(retval);
3393 static int stlink_dap_op_queue_dp_write(struct adiv5_dap *dap, unsigned reg,
3398 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3399 if (reg & 0x000000F0) {
3400 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3401 return ERROR_COMMAND_NOTFOUND;
3404 if (reg == DP_SELECT && (data & DP_SELECT_DPBANK) != 0) {
3405 /* ignored if STLINK_F_HAS_DPBANKSEL, not properly managed otherwise */
3406 LOG_DEBUG("Ignoring DPBANKSEL while write SELECT");
3407 data &= ~DP_SELECT_DPBANK;
3410 retval = stlink_dap_check_reconnect(dap);
3411 if (retval != ERROR_OK)
3414 /* ST-Link does not like that we set CORUNDETECT */
3415 if (reg == DP_CTRL_STAT)
3416 data &= ~CORUNDETECT;
3418 retval = stlink_write_dap_register(stlink_dap_handle,
3419 STLINK_DEBUG_PORT_ACCESS, reg, data);
3420 return stlink_dap_record_error(retval);
3424 static int stlink_dap_op_queue_ap_read(struct adiv5_ap *ap, unsigned reg,
3427 struct adiv5_dap *dap = ap->dap;
3431 retval = stlink_dap_check_reconnect(dap);
3432 if (retval != ERROR_OK)
3435 if (reg != AP_REG_IDR) {
3436 retval = stlink_dap_open_ap(ap->ap_num);
3437 if (retval != ERROR_OK)
3440 data = data ? : &dummy;
3441 retval = stlink_read_dap_register(stlink_dap_handle, ap->ap_num, reg,
3443 dap->stlink_flush_ap_write = false;
3444 return stlink_dap_record_error(retval);
3448 static int stlink_dap_op_queue_ap_write(struct adiv5_ap *ap, unsigned reg,
3451 struct adiv5_dap *dap = ap->dap;
3454 retval = stlink_dap_check_reconnect(dap);
3455 if (retval != ERROR_OK)
3458 retval = stlink_dap_open_ap(ap->ap_num);
3459 if (retval != ERROR_OK)
3462 retval = stlink_write_dap_register(stlink_dap_handle, ap->ap_num, reg,
3464 dap->stlink_flush_ap_write = true;
3465 return stlink_dap_record_error(retval);
3469 static int stlink_dap_op_queue_ap_abort(struct adiv5_dap *dap, uint8_t *ack)
3471 LOG_WARNING("stlink_dap_op_queue_ap_abort()");
3476 static int stlink_dap_op_run(struct adiv5_dap *dap)
3478 uint32_t ctrlstat, pwrmask;
3479 int retval, saved_retval;
3481 /* Here no LOG_DEBUG. This is called continuously! */
3484 * ST-Link returns immediately after a DAP write, without waiting for it
3486 * Run a dummy read to DP_RDBUFF, as suggested in
3487 * http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka16363.html
3489 if (dap->stlink_flush_ap_write) {
3490 dap->stlink_flush_ap_write = false;
3491 retval = stlink_dap_op_queue_dp_read(dap, DP_RDBUFF, NULL);
3492 if (retval != ERROR_OK) {
3493 dap->do_reconnect = true;
3498 saved_retval = stlink_dap_get_and_clear_error();
3500 retval = stlink_dap_op_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
3501 if (retval != ERROR_OK) {
3502 dap->do_reconnect = true;
3505 retval = stlink_dap_get_and_clear_error();
3506 if (retval != ERROR_OK) {
3507 LOG_ERROR("Fail reading CTRL/STAT register. Force reconnect");
3508 dap->do_reconnect = true;
3512 if (ctrlstat & SSTICKYERR) {
3513 if (stlink_dap_param.transport == HL_TRANSPORT_JTAG)
3514 retval = stlink_dap_op_queue_dp_write(dap, DP_CTRL_STAT,
3515 ctrlstat & (dap->dp_ctrl_stat | SSTICKYERR));
3517 retval = stlink_dap_op_queue_dp_write(dap, DP_ABORT, STKERRCLR);
3518 if (retval != ERROR_OK) {
3519 dap->do_reconnect = true;
3522 retval = stlink_dap_get_and_clear_error();
3523 if (retval != ERROR_OK) {
3524 dap->do_reconnect = true;
3529 /* check for power lost */
3530 pwrmask = dap->dp_ctrl_stat & (CDBGPWRUPREQ | CSYSPWRUPREQ);
3531 if ((ctrlstat & pwrmask) != pwrmask)
3532 dap->do_reconnect = true;
3534 return saved_retval;
3538 static void stlink_dap_op_quit(struct adiv5_dap *dap)
3542 retval = stlink_dap_closeall_ap();
3543 if (retval != ERROR_OK)
3544 LOG_ERROR("Error closing APs");
3547 static int stlink_dap_config_trace(bool enabled,
3548 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
3549 unsigned int *trace_freq, unsigned int traceclkin_freq,
3550 uint16_t *prescaler)
3552 return stlink_config_trace(stlink_dap_handle, enabled, pin_protocol,
3553 port_size, trace_freq, traceclkin_freq,
3557 static int stlink_dap_trace_read(uint8_t *buf, size_t *size)
3559 return stlink_usb_trace_read(stlink_dap_handle, buf, size);
3563 COMMAND_HANDLER(stlink_dap_serial_command)
3565 LOG_DEBUG("stlink_dap_serial_command");
3567 if (CMD_ARGC != 1) {
3568 LOG_ERROR("Expected exactly one argument for \"st-link serial <serial-number>\".");
3569 return ERROR_COMMAND_SYNTAX_ERROR;
3572 if (stlink_dap_param.serial) {
3573 LOG_WARNING("Command \"st-link serial\" already used. Replacing previous value");
3574 free((void *)stlink_dap_param.serial);
3577 stlink_dap_param.serial = strdup(CMD_ARGV[0]);
3582 COMMAND_HANDLER(stlink_dap_vid_pid)
3584 unsigned int i, max_usb_ids = HLA_MAX_USB_IDS;
3586 if (CMD_ARGC > max_usb_ids * 2) {
3587 LOG_WARNING("ignoring extra IDs in vid_pid "
3588 "(maximum is %d pairs)", max_usb_ids);
3589 CMD_ARGC = max_usb_ids * 2;
3591 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
3592 LOG_WARNING("incomplete vid_pid configuration directive");
3593 return ERROR_COMMAND_SYNTAX_ERROR;
3595 for (i = 0; i < CMD_ARGC; i += 2) {
3596 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], stlink_dap_param.vid[i / 2]);
3597 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], stlink_dap_param.pid[i / 2]);
3600 /* null termination */
3601 stlink_dap_param.vid[i / 2] = stlink_dap_param.pid[i / 2] = 0;
3607 static const struct command_registration stlink_dap_subcommand_handlers[] = {
3610 .handler = stlink_dap_serial_command,
3611 .mode = COMMAND_CONFIG,
3612 .help = "set the serial number of the adapter",
3613 .usage = "<serial_number>",
3617 .handler = stlink_dap_vid_pid,
3618 .mode = COMMAND_CONFIG,
3619 .help = "USB VID and PID of the adapter",
3620 .usage = "(vid pid)+",
3622 COMMAND_REGISTRATION_DONE
3626 static const struct command_registration stlink_dap_command_handlers[] = {
3629 .mode = COMMAND_ANY,
3630 .help = "perform st-link management",
3631 .chain = stlink_dap_subcommand_handlers,
3634 COMMAND_REGISTRATION_DONE
3638 static int stlink_dap_init(void)
3640 enum reset_types jtag_reset_config = jtag_get_reset_config();
3643 LOG_DEBUG("stlink_dap_init()");
3645 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3646 if (jtag_reset_config & RESET_SRST_NO_GATING)
3647 stlink_dap_param.connect_under_reset = true;
3649 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3652 if (transport_is_dapdirect_swd())
3653 stlink_dap_param.transport = HL_TRANSPORT_SWD;
3654 else if (transport_is_dapdirect_jtag())
3655 stlink_dap_param.transport = HL_TRANSPORT_JTAG;
3657 LOG_ERROR("Unsupported transport");
3661 retval = stlink_usb_open(&stlink_dap_param, (void **)&stlink_dap_handle);
3662 if (retval != ERROR_OK)
3665 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DAP_REG)) {
3666 LOG_ERROR("ST-Link version does not support DAP direct transport");
3673 static int stlink_dap_quit(void)
3675 LOG_DEBUG("stlink_dap_quit()");
3677 free((void *)stlink_dap_param.serial);
3678 stlink_dap_param.serial = NULL;
3680 return stlink_usb_close(stlink_dap_handle);
3684 static int stlink_dap_reset(int req_trst, int req_srst)
3686 LOG_DEBUG("stlink_dap_reset(%d)", req_srst);
3687 return stlink_usb_assert_srst(stlink_dap_handle,
3688 req_srst ? STLINK_DEBUG_APIV2_DRIVE_NRST_LOW
3689 : STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH);
3693 static int stlink_dap_speed(int speed)
3696 LOG_ERROR("RTCK not supported. Set nonzero adapter_khz.");
3697 return ERROR_JTAG_NOT_IMPLEMENTED;
3700 stlink_dap_param.initial_interface_speed = speed;
3701 stlink_speed(stlink_dap_handle, speed, false);
3706 static int stlink_dap_khz(int khz, int *jtag_speed)
3713 static int stlink_dap_speed_div(int speed, int *khz)
3719 static const struct dap_ops stlink_dap_ops = {
3720 .connect = stlink_dap_op_connect,
3721 .send_sequence = stlink_dap_op_send_sequence,
3722 .queue_dp_read = stlink_dap_op_queue_dp_read,
3723 .queue_dp_write = stlink_dap_op_queue_dp_write,
3724 .queue_ap_read = stlink_dap_op_queue_ap_read,
3725 .queue_ap_write = stlink_dap_op_queue_ap_write,
3726 .queue_ap_abort = stlink_dap_op_queue_ap_abort,
3727 .run = stlink_dap_op_run,
3728 .sync = NULL, /* optional */
3729 .quit = stlink_dap_op_quit, /* optional */
3732 static const char *const stlink_dap_transport[] = { "dapdirect_jtag", "dapdirect_swd", NULL };
3734 struct adapter_driver stlink_dap_adapter_driver = {
3736 .transports = stlink_dap_transport,
3737 .commands = stlink_dap_command_handlers,
3739 .init = stlink_dap_init,
3740 .quit = stlink_dap_quit,
3741 .reset = stlink_dap_reset,
3742 .speed = stlink_dap_speed,
3743 .khz = stlink_dap_khz,
3744 .speed_div = stlink_dap_speed_div,
3745 .config_trace = stlink_dap_config_trace,
3746 .poll_trace = stlink_dap_trace_read,
3748 .dap_jtag_ops = &stlink_dap_ops,
3749 .dap_swd_ops = &stlink_dap_ops,