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
303 #define STLINK_V3_MAX_FREQ_NB 10
305 #define REQUEST_SENSE 0x03
306 #define REQUEST_SENSE_LENGTH 18
309 * Map the relevant features, quirks and workaround for specific firmware
312 #define STLINK_F_HAS_TRACE BIT(0)
313 #define STLINK_F_HAS_SWD_SET_FREQ BIT(1)
314 #define STLINK_F_HAS_JTAG_SET_FREQ BIT(2)
315 #define STLINK_F_HAS_MEM_16BIT BIT(3)
316 #define STLINK_F_HAS_GETLASTRWSTATUS2 BIT(4)
317 #define STLINK_F_HAS_DAP_REG BIT(5)
318 #define STLINK_F_QUIRK_JTAG_DP_READ BIT(6)
319 #define STLINK_F_HAS_AP_INIT BIT(7)
320 #define STLINK_F_HAS_DPBANKSEL BIT(8)
321 #define STLINK_F_HAS_RW8_512BYTES BIT(9)
322 #define STLINK_F_FIX_CLOSE_AP BIT(10)
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[] = {
353 {1125, 32}, /* default */
359 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
360 static int stlink_swim_status(void *handle);
361 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size);
362 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map);
363 static int stlink_speed(void *handle, int khz, bool query);
364 static int stlink_usb_open_ap(void *handle, unsigned short apsel);
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->st_mode == STLINK_MODE_DEBUG_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->st_mode != STLINK_MODE_DEBUG_SWIM) || !retries) {
825 res = stlink_usb_xfer_noerrcheck(handle, buf, size);
830 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
831 res = stlink_swim_status(handle);
836 res = stlink_usb_error_check(handle);
837 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
838 unsigned int 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 /* API required to return proper error code on close AP from J29 */
1036 if (h->version.jtag >= 29)
1037 flags |= STLINK_F_FIX_CLOSE_AP;
1039 /* Banked regs (DPv1 & DPv2) support from V2J32 */
1040 if (h->version.jtag >= 32)
1041 flags |= STLINK_F_HAS_DPBANKSEL;
1045 /* all STLINK-V3 use api-v3 */
1046 h->version.jtag_api = STLINK_JTAG_API_V3;
1048 /* STLINK-V3 is a superset of ST-LINK/V2 */
1051 /* API for target voltage */
1052 flags |= STLINK_F_HAS_TRACE;
1054 /* preferred API to get last R/W status */
1055 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1057 /* API to access DAP registers */
1058 flags |= STLINK_F_HAS_DAP_REG;
1060 /* API to read/write memory at 16 bit */
1061 flags |= STLINK_F_HAS_MEM_16BIT;
1063 /* API required to init AP before any AP access */
1064 flags |= STLINK_F_HAS_AP_INIT;
1066 /* API required to return proper error code on close AP */
1067 flags |= STLINK_F_FIX_CLOSE_AP;
1069 /* Banked regs (DPv1 & DPv2) support from V3J2 */
1070 if (h->version.jtag >= 2)
1071 flags |= STLINK_F_HAS_DPBANKSEL;
1073 /* 8bit read/write max packet size 512 bytes from V3J6 */
1074 if (h->version.jtag >= 6)
1075 flags |= STLINK_F_HAS_RW8_512BYTES;
1081 h->version.flags = flags;
1084 p += sprintf(p, "V%d", v);
1086 p += sprintf(p, "J%d", jtag);
1088 p += sprintf(p, "M%d", msd);
1090 p += sprintf(p, "B%d", bridge);
1092 sprintf(p, "S%d", swim);
1094 LOG_INFO("STLINK %s (API v%d) VID:PID %04X:%04X",
1096 h->version.jtag_api,
1103 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
1105 struct stlink_usb_handle_s *h = handle;
1106 uint32_t adc_results[2];
1108 /* no error message, simply quit with error */
1109 if (!(h->version.flags & STLINK_F_HAS_TARGET_VOLT))
1110 return ERROR_COMMAND_NOTFOUND;
1112 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1114 h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
1116 int result = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1118 if (result != ERROR_OK)
1121 /* convert result */
1122 adc_results[0] = le_to_h_u32(h->databuf);
1123 adc_results[1] = le_to_h_u32(h->databuf + 4);
1125 *target_voltage = 0;
1128 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
1130 LOG_INFO("Target voltage: %f", (double)*target_voltage);
1135 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
1137 struct stlink_usb_handle_s *h = handle;
1139 assert(handle != NULL);
1141 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
1142 return ERROR_COMMAND_NOTFOUND;
1144 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1146 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1147 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
1148 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1151 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1153 if (result != ERROR_OK)
1159 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
1161 struct stlink_usb_handle_s *h = handle;
1163 assert(handle != NULL);
1165 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
1166 return ERROR_COMMAND_NOTFOUND;
1168 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1170 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1171 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
1172 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1175 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1177 if (result != ERROR_OK)
1184 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
1187 struct stlink_usb_handle_s *h = handle;
1189 assert(handle != NULL);
1191 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1193 h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
1195 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1197 if (res != ERROR_OK)
1200 *mode = h->databuf[0];
1206 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
1209 struct stlink_usb_handle_s *h = handle;
1211 assert(handle != NULL);
1213 /* on api V2 we are able the read the latest command
1215 * TODO: we need the test on api V1 too
1217 if (h->version.jtag_api != STLINK_JTAG_API_V1)
1220 stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
1223 case STLINK_MODE_DEBUG_JTAG:
1224 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1225 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1226 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1228 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1229 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG_NO_RESET;
1231 case STLINK_MODE_DEBUG_SWD:
1232 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1233 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1234 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1236 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1237 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD_NO_RESET;
1239 case STLINK_MODE_DEBUG_SWIM:
1240 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1241 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
1242 /* swim enter does not return any response or status */
1243 return stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1244 case STLINK_MODE_DFU:
1245 case STLINK_MODE_MASS:
1250 return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
1254 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
1257 struct stlink_usb_handle_s *h = handle;
1259 assert(handle != NULL);
1261 /* command with no reply, use a valid endpoint but zero size */
1262 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1265 case STLINK_MODE_DEBUG_JTAG:
1266 case STLINK_MODE_DEBUG_SWD:
1267 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1268 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
1270 case STLINK_MODE_DEBUG_SWIM:
1271 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1272 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
1274 case STLINK_MODE_DFU:
1275 h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
1276 h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
1278 case STLINK_MODE_MASS:
1283 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1285 if (res != ERROR_OK)
1291 static int stlink_usb_assert_srst(void *handle, int srst);
1293 static enum stlink_mode stlink_get_mode(enum hl_transports t)
1296 case HL_TRANSPORT_SWD:
1297 return STLINK_MODE_DEBUG_SWD;
1298 case HL_TRANSPORT_JTAG:
1299 return STLINK_MODE_DEBUG_JTAG;
1301 return STLINK_MODE_UNKNOWN;
1306 static int stlink_usb_exit_mode(void *handle)
1310 enum stlink_mode emode;
1312 assert(handle != NULL);
1314 res = stlink_usb_current_mode(handle, &mode);
1316 if (res != ERROR_OK)
1319 LOG_DEBUG("MODE: 0x%02X", mode);
1321 /* try to exit current mode */
1323 case STLINK_DEV_DFU_MODE:
1324 emode = STLINK_MODE_DFU;
1326 case STLINK_DEV_DEBUG_MODE:
1327 emode = STLINK_MODE_DEBUG_SWD;
1329 case STLINK_DEV_SWIM_MODE:
1330 emode = STLINK_MODE_DEBUG_SWIM;
1332 case STLINK_DEV_BOOTLOADER_MODE:
1333 case STLINK_DEV_MASS_MODE:
1335 emode = STLINK_MODE_UNKNOWN;
1339 if (emode != STLINK_MODE_UNKNOWN)
1340 return stlink_usb_mode_leave(handle, emode);
1346 static int stlink_usb_init_mode(void *handle, bool connect_under_reset, int initial_interface_speed)
1350 enum stlink_mode emode;
1351 struct stlink_usb_handle_s *h = handle;
1353 assert(handle != NULL);
1355 res = stlink_usb_exit_mode(handle);
1356 if (res != ERROR_OK)
1359 res = stlink_usb_current_mode(handle, &mode);
1361 if (res != ERROR_OK)
1364 /* we check the target voltage here as an aid to debugging connection problems.
1365 * the stlink requires the target Vdd to be connected for reliable debugging.
1366 * this cmd is supported in all modes except DFU
1368 if (mode != STLINK_DEV_DFU_MODE) {
1370 float target_voltage;
1372 /* check target voltage (if supported) */
1373 res = stlink_usb_check_voltage(h, &target_voltage);
1375 if (res != ERROR_OK) {
1376 if (res != ERROR_COMMAND_NOTFOUND)
1377 LOG_ERROR("voltage check failed");
1378 /* attempt to continue as it is not a catastrophic failure */
1380 /* check for a sensible target voltage, operating range is 1.65-5.5v
1381 * according to datasheet */
1382 if (target_voltage < 1.5)
1383 LOG_ERROR("target voltage may be too low for reliable debugging");
1387 LOG_DEBUG("MODE: 0x%02X", mode);
1389 /* set selected mode */
1392 if (emode == STLINK_MODE_UNKNOWN) {
1393 LOG_ERROR("selected mode (transport) not supported");
1397 /* set the speed before entering the mode, as the chip discovery phase should be done at this speed too */
1398 if (emode == STLINK_MODE_DEBUG_JTAG) {
1399 if (h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ) {
1400 stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
1401 stlink_speed(h, initial_interface_speed, false);
1403 } else if (emode == STLINK_MODE_DEBUG_SWD) {
1404 if (h->version.flags & STLINK_F_HAS_SWD_SET_FREQ) {
1405 stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
1406 stlink_speed(h, initial_interface_speed, false);
1410 if (h->version.jtag_api == STLINK_JTAG_API_V3) {
1411 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
1413 stlink_get_com_freq(h, (emode == STLINK_MODE_DEBUG_JTAG), map);
1414 stlink_dump_speed_map(map, ARRAY_SIZE(map));
1415 stlink_speed(h, initial_interface_speed, false);
1418 /* preliminary SRST assert:
1419 * We want SRST is asserted before activating debug signals (mode_enter).
1420 * As the required mode has not been set, the adapter may not know what pin to use.
1421 * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
1422 * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
1423 * after power on, SWIM_RST stays unchanged */
1424 if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
1425 stlink_usb_assert_srst(handle, 0);
1426 /* do not check the return status here, we will
1427 proceed and enter the desired mode below
1428 and try asserting srst again. */
1430 res = stlink_usb_mode_enter(handle, emode);
1431 if (res != ERROR_OK)
1434 /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
1435 if (connect_under_reset) {
1436 res = stlink_usb_assert_srst(handle, 0);
1437 if (res != ERROR_OK)
1441 res = stlink_usb_current_mode(handle, &mode);
1443 if (res != ERROR_OK)
1446 LOG_DEBUG("MODE: 0x%02X", mode);
1451 /* request status from last swim request */
1452 static int stlink_swim_status(void *handle)
1454 struct stlink_usb_handle_s *h = handle;
1457 stlink_usb_init_buffer(handle, h->rx_ep, 4);
1458 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1459 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
1460 /* error is checked by the caller */
1461 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1462 if (res != ERROR_OK)
1467 the purpose of this function is unknown...
1468 capabilities? anyway for swim v6 it returns
1471 __attribute__((unused))
1472 static int stlink_swim_cap(void *handle, uint8_t *cap)
1474 struct stlink_usb_handle_s *h = handle;
1477 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1478 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1479 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1480 h->cmdbuf[h->cmdidx++] = 0x01;
1481 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1482 if (res != ERROR_OK)
1484 memcpy(cap, h->databuf, 8);
1488 /* debug dongle assert/deassert sreset line */
1489 static int stlink_swim_assert_reset(void *handle, int reset)
1491 struct stlink_usb_handle_s *h = handle;
1494 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1495 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1497 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1499 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1500 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1501 if (res != ERROR_OK)
1508 1.3ms low then 750Hz then 1.5kHz
1510 static int stlink_swim_enter(void *handle)
1512 struct stlink_usb_handle_s *h = handle;
1515 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1516 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1517 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1518 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1519 if (res != ERROR_OK)
1524 /* switch high/low speed swim */
1525 static int stlink_swim_speed(void *handle, int speed)
1527 struct stlink_usb_handle_s *h = handle;
1530 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1531 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1532 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1534 h->cmdbuf[h->cmdidx++] = 1;
1536 h->cmdbuf[h->cmdidx++] = 0;
1537 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1538 if (res != ERROR_OK)
1544 initiate srst from swim.
1545 nrst is pulled low for 50us.
1547 static int stlink_swim_generate_rst(void *handle)
1549 struct stlink_usb_handle_s *h = handle;
1552 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1553 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1554 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1555 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1556 if (res != ERROR_OK)
1562 send resynchronize sequence
1563 swim is pulled low for 16us
1564 reply is 64 clks low
1566 static int stlink_swim_resync(void *handle)
1568 struct stlink_usb_handle_s *h = handle;
1571 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1572 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1573 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_RESET;
1574 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1575 if (res != ERROR_OK)
1580 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1582 struct stlink_usb_handle_s *h = handle;
1585 unsigned int datalen = 0;
1586 int cmdsize = STLINK_CMD_SIZE_V2;
1588 if (len > STLINK_DATA_SIZE)
1591 if (h->version.stlink == 1)
1592 cmdsize = STLINK_SG_SIZE;
1594 stlink_usb_init_buffer(handle, h->tx_ep, 0);
1595 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1596 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1597 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1599 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1601 for (i = 0; i < len; i++) {
1602 if (h->cmdidx == cmdsize)
1603 h->databuf[datalen++] = *(data++);
1605 h->cmdbuf[h->cmdidx++] = *(data++);
1607 if (h->version.stlink == 1)
1608 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1610 res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1611 if (res != ERROR_OK)
1616 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1618 struct stlink_usb_handle_s *h = handle;
1621 if (len > STLINK_DATA_SIZE)
1624 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1625 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1626 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1627 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1629 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1631 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1632 if (res != ERROR_OK)
1635 stlink_usb_init_buffer(handle, h->rx_ep, len);
1636 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1637 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1638 res = stlink_usb_xfer_noerrcheck(handle, data, len);
1639 if (res != ERROR_OK)
1646 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1649 struct stlink_usb_handle_s *h = handle;
1651 assert(handle != NULL);
1653 /* there is no swim read core id cmd */
1654 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
1659 stlink_usb_init_buffer(handle, h->rx_ep, 12);
1661 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1662 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1663 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1665 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1668 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_IDCODES;
1670 res = stlink_usb_xfer_errcheck(handle, h->databuf, 12);
1674 if (res != ERROR_OK)
1677 *idcode = le_to_h_u32(h->databuf + offset);
1679 LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1684 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1686 struct stlink_usb_handle_s *h = handle;
1689 assert(handle != NULL);
1691 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1693 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1694 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1695 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1698 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1699 if (res != ERROR_OK)
1702 *val = le_to_h_u32(h->databuf + 4);
1706 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1708 struct stlink_usb_handle_s *h = handle;
1710 assert(handle != NULL);
1712 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1714 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1715 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1716 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1718 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1719 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1721 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1724 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1728 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1730 struct stlink_usb_handle_s *h = handle;
1732 assert(handle != NULL);
1734 if (h->trace.enabled && (h->version.flags & STLINK_F_HAS_TRACE)) {
1737 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1739 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1740 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1742 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1743 if (res != ERROR_OK)
1746 size_t bytes_avail = le_to_h_u16(h->databuf);
1747 *size = bytes_avail < *size ? bytes_avail : *size - 1;
1750 res = stlink_usb_read_trace(handle, buf, *size);
1751 if (res != ERROR_OK)
1760 static enum target_state stlink_usb_v2_get_status(void *handle)
1765 result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1766 if (result != ERROR_OK)
1767 return TARGET_UNKNOWN;
1769 if (status & S_HALT)
1770 return TARGET_HALTED;
1771 else if (status & S_RESET_ST)
1772 return TARGET_RESET;
1774 return TARGET_RUNNING;
1778 static enum target_state stlink_usb_state(void *handle)
1781 struct stlink_usb_handle_s *h = handle;
1783 assert(handle != NULL);
1785 if (h->reconnect_pending) {
1786 LOG_INFO("Previous state query failed, trying to reconnect");
1787 res = stlink_usb_mode_enter(handle, h->st_mode);
1788 if (res != ERROR_OK)
1789 return TARGET_UNKNOWN;
1791 h->reconnect_pending = false;
1794 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1795 res = stlink_usb_v2_get_status(handle);
1796 if (res == TARGET_UNKNOWN)
1797 h->reconnect_pending = true;
1801 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1803 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1804 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
1806 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1808 if (res != ERROR_OK)
1809 return TARGET_UNKNOWN;
1811 if (h->databuf[0] == STLINK_CORE_RUNNING)
1812 return TARGET_RUNNING;
1813 if (h->databuf[0] == STLINK_CORE_HALTED)
1814 return TARGET_HALTED;
1816 h->reconnect_pending = true;
1818 return TARGET_UNKNOWN;
1821 static int stlink_usb_assert_srst(void *handle, int srst)
1823 struct stlink_usb_handle_s *h = handle;
1825 assert(handle != NULL);
1827 if (h->st_mode == STLINK_MODE_DEBUG_SWIM)
1828 return stlink_swim_assert_reset(handle, srst);
1830 if (h->version.stlink == 1)
1831 return ERROR_COMMAND_NOTFOUND;
1833 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1835 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1836 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
1837 h->cmdbuf[h->cmdidx++] = srst;
1839 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1843 static void stlink_usb_trace_disable(void *handle)
1846 struct stlink_usb_handle_s *h = handle;
1848 assert(handle != NULL);
1850 assert(h->version.flags & STLINK_F_HAS_TRACE);
1852 LOG_DEBUG("Tracing: disable");
1854 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1855 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1856 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
1857 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1859 if (res == ERROR_OK)
1860 h->trace.enabled = false;
1865 static int stlink_usb_trace_enable(void *handle)
1868 struct stlink_usb_handle_s *h = handle;
1870 assert(handle != NULL);
1872 if (h->version.flags & STLINK_F_HAS_TRACE) {
1873 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1875 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1876 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
1877 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
1879 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
1882 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1884 if (res == ERROR_OK) {
1885 h->trace.enabled = true;
1886 LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
1889 LOG_ERROR("Tracing is not supported by this version.");
1897 static int stlink_usb_reset(void *handle)
1899 struct stlink_usb_handle_s *h = handle;
1902 assert(handle != NULL);
1904 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1906 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1908 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1909 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
1911 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
1913 retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
1914 if (retval != ERROR_OK)
1917 if (h->trace.enabled) {
1918 stlink_usb_trace_disable(h);
1919 return stlink_usb_trace_enable(h);
1926 static int stlink_usb_run(void *handle)
1929 struct stlink_usb_handle_s *h = handle;
1931 assert(handle != NULL);
1933 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1934 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
1939 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1941 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1942 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
1944 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1948 static int stlink_usb_halt(void *handle)
1951 struct stlink_usb_handle_s *h = handle;
1953 assert(handle != NULL);
1955 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1956 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1961 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1963 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1964 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
1966 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1970 static int stlink_usb_step(void *handle)
1972 struct stlink_usb_handle_s *h = handle;
1974 assert(handle != NULL);
1976 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1977 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
1978 * that the Cortex-M3 currently does. */
1979 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
1980 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
1981 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1984 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1986 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1987 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
1989 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1993 static int stlink_usb_read_regs(void *handle)
1996 struct stlink_usb_handle_s *h = handle;
1998 assert(handle != NULL);
2000 stlink_usb_init_buffer(handle, h->rx_ep, 88);
2002 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2003 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2005 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
2006 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 84);
2007 /* regs data from offset 0 */
2009 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
2010 res = stlink_usb_xfer_errcheck(handle, h->databuf, 88);
2011 /* status at offset 0, regs data from offset 4 */
2018 static int stlink_usb_read_reg(void *handle, int num, uint32_t *val)
2021 struct stlink_usb_handle_s *h = handle;
2023 assert(handle != NULL);
2025 stlink_usb_init_buffer(handle, h->rx_ep, h->version.jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
2027 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2028 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2029 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
2031 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
2032 h->cmdbuf[h->cmdidx++] = num;
2034 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2035 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
2036 if (res != ERROR_OK)
2038 *val = le_to_h_u32(h->databuf);
2041 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
2042 if (res != ERROR_OK)
2044 *val = le_to_h_u32(h->databuf + 4);
2050 static int stlink_usb_write_reg(void *handle, int num, uint32_t val)
2052 struct stlink_usb_handle_s *h = handle;
2054 assert(handle != NULL);
2056 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2058 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2059 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2060 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
2062 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
2063 h->cmdbuf[h->cmdidx++] = num;
2064 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
2067 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2070 static int stlink_usb_get_rw_status(void *handle)
2072 struct stlink_usb_handle_s *h = handle;
2074 assert(handle != NULL);
2076 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2079 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2081 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2082 if (h->version.flags & STLINK_F_HAS_GETLASTRWSTATUS2) {
2083 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS2;
2084 return stlink_usb_xfer_errcheck(handle, h->databuf, 12);
2086 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
2087 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2092 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
2096 uint16_t read_len = len;
2097 struct stlink_usb_handle_s *h = handle;
2099 assert(handle != NULL);
2101 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2102 if (len > stlink_usb_block(h)) {
2103 LOG_DEBUG("max buffer (%d) length exceeded", stlink_usb_block(h));
2107 stlink_usb_init_buffer(handle, h->rx_ep, read_len);
2109 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2110 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
2111 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2113 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2116 /* we need to fix read length for single bytes */
2120 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, read_len);
2122 if (res != ERROR_OK)
2125 memcpy(buffer, h->databuf, len);
2127 return stlink_usb_get_rw_status(handle);
2131 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
2132 const uint8_t *buffer)
2135 struct stlink_usb_handle_s *h = handle;
2137 assert(handle != NULL);
2139 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2140 if (len > stlink_usb_block(h)) {
2141 LOG_DEBUG("max buffer length (%d) exceeded", stlink_usb_block(h));
2145 stlink_usb_init_buffer(handle, h->tx_ep, len);
2147 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2148 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
2149 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2151 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2154 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2156 if (res != ERROR_OK)
2159 return stlink_usb_get_rw_status(handle);
2163 static int stlink_usb_read_mem16(void *handle, uint32_t addr, uint16_t len,
2167 struct stlink_usb_handle_s *h = handle;
2169 assert(handle != NULL);
2171 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2172 return ERROR_COMMAND_NOTFOUND;
2174 /* data must be a multiple of 2 and half-word aligned */
2175 if (len % 2 || addr % 2) {
2176 LOG_DEBUG("Invalid data alignment");
2177 return ERROR_TARGET_UNALIGNED_ACCESS;
2180 stlink_usb_init_buffer(handle, h->rx_ep, len);
2182 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2183 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READMEM_16BIT;
2184 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2186 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2189 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2191 if (res != ERROR_OK)
2194 memcpy(buffer, h->databuf, len);
2196 return stlink_usb_get_rw_status(handle);
2200 static int stlink_usb_write_mem16(void *handle, uint32_t addr, uint16_t len,
2201 const uint8_t *buffer)
2204 struct stlink_usb_handle_s *h = handle;
2206 assert(handle != NULL);
2208 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2209 return ERROR_COMMAND_NOTFOUND;
2211 /* data must be a multiple of 2 and half-word aligned */
2212 if (len % 2 || addr % 2) {
2213 LOG_DEBUG("Invalid data alignment");
2214 return ERROR_TARGET_UNALIGNED_ACCESS;
2217 stlink_usb_init_buffer(handle, h->tx_ep, len);
2219 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2220 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEMEM_16BIT;
2221 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2223 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2226 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2228 if (res != ERROR_OK)
2231 return stlink_usb_get_rw_status(handle);
2235 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
2239 struct stlink_usb_handle_s *h = handle;
2241 assert(handle != NULL);
2243 /* data must be a multiple of 4 and word aligned */
2244 if (len % 4 || addr % 4) {
2245 LOG_DEBUG("Invalid data alignment");
2246 return ERROR_TARGET_UNALIGNED_ACCESS;
2249 stlink_usb_init_buffer(handle, h->rx_ep, len);
2251 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2252 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
2253 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2255 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2258 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2260 if (res != ERROR_OK)
2263 memcpy(buffer, h->databuf, len);
2265 return stlink_usb_get_rw_status(handle);
2269 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
2270 const uint8_t *buffer)
2273 struct stlink_usb_handle_s *h = handle;
2275 assert(handle != NULL);
2277 /* data must be a multiple of 4 and word aligned */
2278 if (len % 4 || addr % 4) {
2279 LOG_DEBUG("Invalid data alignment");
2280 return ERROR_TARGET_UNALIGNED_ACCESS;
2283 stlink_usb_init_buffer(handle, h->tx_ep, len);
2285 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2286 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
2287 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2289 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2292 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2294 if (res != ERROR_OK)
2297 return stlink_usb_get_rw_status(handle);
2300 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
2302 uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
2303 if (max_tar_block == 0)
2305 return max_tar_block;
2308 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
2309 uint32_t count, uint8_t *buffer)
2311 int retval = ERROR_OK;
2312 uint32_t bytes_remaining;
2314 struct stlink_usb_handle_s *h = handle;
2316 /* calculate byte count */
2319 /* switch to 8 bit if stlink does not support 16 bit memory read */
2320 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2325 bytes_remaining = (size != 1) ?
2326 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2328 if (count < bytes_remaining)
2329 bytes_remaining = count;
2332 * all stlink support 8/32bit memory read/writes and only from
2333 * stlink V2J26 there is support for 16 bit memory read/write.
2334 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2339 /* When in jtag mode the stlink uses the auto-increment functionality.
2340 * However it expects us to pass the data correctly, this includes
2341 * alignment and any page boundaries. We already do this as part of the
2342 * adi_v5 implementation, but the stlink is a hla adapter and so this
2343 * needs implementing manually.
2344 * currently this only affects jtag mode, according to ST they do single
2345 * access in SWD mode - but this may change and so we do it for both modes */
2347 /* we first need to check for any unaligned bytes */
2348 if (addr & (size - 1)) {
2350 uint32_t head_bytes = size - (addr & (size - 1));
2351 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
2352 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2353 usleep((1<<retries++) * 1000);
2356 if (retval != ERROR_OK)
2358 buffer += head_bytes;
2360 count -= head_bytes;
2361 bytes_remaining -= head_bytes;
2364 if (bytes_remaining & (size - 1))
2365 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
2367 retval = stlink_usb_read_mem16(handle, addr, bytes_remaining, buffer);
2369 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
2371 retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
2373 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2374 usleep((1<<retries++) * 1000);
2377 if (retval != ERROR_OK)
2380 buffer += bytes_remaining;
2381 addr += bytes_remaining;
2382 count -= bytes_remaining;
2388 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
2389 uint32_t count, const uint8_t *buffer)
2391 int retval = ERROR_OK;
2392 uint32_t bytes_remaining;
2394 struct stlink_usb_handle_s *h = handle;
2396 /* calculate byte count */
2399 /* switch to 8 bit if stlink does not support 16 bit memory read */
2400 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2405 bytes_remaining = (size != 1) ?
2406 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2408 if (count < bytes_remaining)
2409 bytes_remaining = count;
2412 * all stlink support 8/32bit memory read/writes and only from
2413 * stlink V2J26 there is support for 16 bit memory read/write.
2414 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2419 /* When in jtag mode the stlink uses the auto-increment functionality.
2420 * However it expects us to pass the data correctly, this includes
2421 * alignment and any page boundaries. We already do this as part of the
2422 * adi_v5 implementation, but the stlink is a hla adapter and so this
2423 * needs implementing manually.
2424 * currently this only affects jtag mode, according to ST they do single
2425 * access in SWD mode - but this may change and so we do it for both modes */
2427 /* we first need to check for any unaligned bytes */
2428 if (addr & (size - 1)) {
2430 uint32_t head_bytes = size - (addr & (size - 1));
2431 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
2432 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2433 usleep((1<<retries++) * 1000);
2436 if (retval != ERROR_OK)
2438 buffer += head_bytes;
2440 count -= head_bytes;
2441 bytes_remaining -= head_bytes;
2444 if (bytes_remaining & (size - 1))
2445 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
2447 retval = stlink_usb_write_mem16(handle, addr, bytes_remaining, buffer);
2449 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
2452 retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
2453 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2454 usleep((1<<retries++) * 1000);
2457 if (retval != ERROR_OK)
2460 buffer += bytes_remaining;
2461 addr += bytes_remaining;
2462 count -= bytes_remaining;
2469 static int stlink_usb_override_target(const char *targetname)
2471 return !strcmp(targetname, "cortex_m");
2474 static int stlink_speed_swim(void *handle, int khz, bool query)
2479 we only have low and high speed...
2480 before changing speed the SWIM_CSR HS bit
2484 retval = stlink_swim_speed(handle, (khz < SWIM_FREQ_HIGH) ? 0 : 1);
2485 if (retval != ERROR_OK)
2486 LOG_ERROR("Unable to set adapter speed");
2489 return (khz < SWIM_FREQ_HIGH) ? SWIM_FREQ_LOW : SWIM_FREQ_HIGH;
2492 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
2495 int speed_index = -1;
2496 int speed_diff = INT_MAX;
2497 int last_valid_speed = -1;
2500 for (i = 0; i < map_size; i++) {
2503 last_valid_speed = i;
2504 if (khz == map[i].speed) {
2508 int current_diff = khz - map[i].speed;
2509 /* get abs value for comparison */
2510 current_diff = (current_diff > 0) ? current_diff : -current_diff;
2511 if ((current_diff < speed_diff) && khz >= map[i].speed) {
2512 speed_diff = current_diff;
2518 if (speed_index == -1) {
2519 /* this will only be here if we cannot match the slow speed.
2520 * use the slowest speed we support.*/
2521 speed_index = last_valid_speed;
2523 } else if (i == map_size)
2526 if (!match && query) {
2527 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz",
2528 khz, map[speed_index].speed);
2534 static int stlink_speed_swd(void *handle, int khz, bool query)
2537 struct stlink_usb_handle_s *h = handle;
2539 /* old firmware cannot change it */
2540 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
2543 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
2544 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
2547 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
2548 if (result != ERROR_OK) {
2549 LOG_ERROR("Unable to set adapter speed");
2554 return stlink_khz_to_speed_map_swd[speed_index].speed;
2557 static int stlink_speed_jtag(void *handle, int khz, bool query)
2560 struct stlink_usb_handle_s *h = handle;
2562 /* old firmware cannot change it */
2563 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
2566 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2567 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2570 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2571 if (result != ERROR_OK) {
2572 LOG_ERROR("Unable to set adapter speed");
2577 return stlink_khz_to_speed_map_jtag[speed_index].speed;
2580 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2584 LOG_DEBUG("Supported clock speeds are:");
2585 for (i = 0; i < map_size; i++)
2587 LOG_DEBUG("%d kHz", map[i].speed);
2590 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map)
2592 struct stlink_usb_handle_s *h = handle;
2595 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2596 LOG_ERROR("Unknown command");
2600 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2602 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2603 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_COM_FREQ;
2604 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2606 int res = stlink_usb_xfer_errcheck(handle, h->databuf, 52);
2608 int size = h->databuf[8];
2610 if (size > STLINK_V3_MAX_FREQ_NB)
2611 size = STLINK_V3_MAX_FREQ_NB;
2613 for (i = 0; i < size; i++) {
2614 map[i].speed = le_to_h_u32(&h->databuf[12 + 4 * i]);
2615 map[i].speed_divisor = i;
2618 /* set to zero all the next entries */
2619 for (i = size; i < STLINK_V3_MAX_FREQ_NB; i++)
2625 static int stlink_set_com_freq(void *handle, bool is_jtag, unsigned int frequency)
2627 struct stlink_usb_handle_s *h = handle;
2629 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2630 LOG_ERROR("Unknown command");
2634 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2636 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2637 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_SET_COM_FREQ;
2638 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2639 h->cmdbuf[h->cmdidx++] = 0;
2641 h_u32_to_le(&h->cmdbuf[4], frequency);
2643 return stlink_usb_xfer_errcheck(handle, h->databuf, 8);
2646 static int stlink_speed_v3(void *handle, bool is_jtag, int khz, bool query)
2648 struct stlink_usb_handle_s *h = handle;
2650 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
2652 stlink_get_com_freq(h, is_jtag, map);
2654 speed_index = stlink_match_speed_map(map, ARRAY_SIZE(map), khz, query);
2657 int result = stlink_set_com_freq(h, is_jtag, map[speed_index].speed);
2658 if (result != ERROR_OK) {
2659 LOG_ERROR("Unable to set adapter speed");
2663 return map[speed_index].speed;
2666 static int stlink_speed(void *handle, int khz, bool query)
2668 struct stlink_usb_handle_s *h = handle;
2673 switch (h->st_mode) {
2674 case STLINK_MODE_DEBUG_SWIM:
2675 return stlink_speed_swim(handle, khz, query);
2676 case STLINK_MODE_DEBUG_SWD:
2677 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2678 return stlink_speed_v3(handle, false, khz, query);
2680 return stlink_speed_swd(handle, khz, query);
2682 case STLINK_MODE_DEBUG_JTAG:
2683 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2684 return stlink_speed_v3(handle, true, khz, query);
2686 return stlink_speed_jtag(handle, khz, query);
2696 static int stlink_usb_close(void *handle)
2698 struct stlink_usb_handle_s *h = handle;
2701 stlink_usb_exit_mode(h);
2702 /* do not check return code, it prevent
2703 us from closing jtag_libusb */
2704 jtag_libusb_close(h->fd);
2712 /* Compute ST-Link serial number from the device descriptor
2713 * this function will help to work-around a bug in old ST-Link/V2 DFU
2714 * the buggy DFU returns an incorrect serial in the USB descriptor
2715 * example for the following serial "57FF72067265575742132067"
2716 * - the correct descriptor serial is:
2717 * 0x32, 0x03, 0x35, 0x00, 0x37, 0x00, 0x46, 0x00, 0x46, 0x00, 0x37, 0x00, 0x32, 0x00 ...
2718 * this contains the length (0x32 = 50), the type (0x3 = DT_STRING) and the serial in unicode format
2719 * the serial part is: 0x0035, 0x0037, 0x0046, 0x0046, 0x0037, 0x0032 ... >> 57FF72 ...
2720 * this format could be read correctly by 'libusb_get_string_descriptor_ascii'
2721 * so this case is managed by libusb_helper::string_descriptor_equal
2722 * - the buggy DFU is not doing any unicode conversion and returns a raw serial data in the descriptor
2723 * 0x1a, 0x03, 0x57, 0x00, 0xFF, 0x00, 0x72, 0x00 ...
2725 * based on the length (0x1a = 26) we could easily decide if we have to fixup the serial
2726 * and then we have just to convert the raw data into printable characters using sprintf
2728 char *stlink_usb_get_alternate_serial(libusb_device_handle *device,
2729 struct libusb_device_descriptor *dev_desc)
2732 unsigned char desc_serial[(STLINK_SERIAL_LEN + 1) * 2];
2734 if (dev_desc->iSerialNumber == 0)
2737 /* get the LANGID from String Descriptor Zero */
2738 usb_retval = libusb_get_string_descriptor(device, 0, 0, desc_serial,
2739 sizeof(desc_serial));
2741 if (usb_retval < LIBUSB_SUCCESS) {
2742 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
2743 libusb_error_name(usb_retval), usb_retval);
2745 } else if (usb_retval < 4) {
2746 /* the size should be least 4 bytes to contain a minimum of 1 supported LANGID */
2747 LOG_ERROR("could not get the LANGID");
2751 uint32_t langid = desc_serial[2] | (desc_serial[3] << 8);
2753 /* get the serial */
2754 usb_retval = libusb_get_string_descriptor(device, dev_desc->iSerialNumber,
2755 langid, desc_serial, sizeof(desc_serial));
2757 unsigned char len = desc_serial[0];
2759 if (usb_retval < LIBUSB_SUCCESS) {
2760 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
2761 libusb_error_name(usb_retval), usb_retval);
2763 } else if (desc_serial[1] != LIBUSB_DT_STRING || len > usb_retval) {
2764 LOG_ERROR("invalid string in ST-LINK USB serial descriptor");
2768 if (len == ((STLINK_SERIAL_LEN + 1) * 2)) {
2769 /* good ST-Link adapter, this case is managed by
2770 * libusb::libusb_get_string_descriptor_ascii */
2772 } else if (len != ((STLINK_SERIAL_LEN / 2 + 1) * 2)) {
2773 LOG_ERROR("unexpected serial length (%d) in descriptor", len);
2777 /* else (len == 26) => buggy ST-Link */
2779 char *alternate_serial = malloc((STLINK_SERIAL_LEN + 1) * sizeof(char));
2780 if (alternate_serial == NULL)
2783 for (unsigned int i = 0; i < STLINK_SERIAL_LEN; i += 2)
2784 sprintf(alternate_serial + i, "%02X", desc_serial[i + 2]);
2786 alternate_serial[STLINK_SERIAL_LEN] = '\0';
2788 return alternate_serial;
2792 static int stlink_usb_open(struct hl_interface_param_s *param, enum stlink_mode mode, void **fd)
2794 int err, retry_count = 1;
2795 struct stlink_usb_handle_s *h;
2797 LOG_DEBUG("stlink_usb_open");
2799 h = calloc(1, sizeof(struct stlink_usb_handle_s));
2802 LOG_DEBUG("malloc failed");
2808 for (unsigned i = 0; param->vid[i]; i++) {
2809 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
2810 h->st_mode, param->vid[i], param->pid[i],
2811 param->serial ? param->serial : "");
2815 On certain host USB configurations(e.g. MacBook Air)
2816 STLINKv2 dongle seems to have its FW in a funky state if,
2817 after plugging it in, you try to use openocd with it more
2818 then once (by launching and closing openocd). In cases like
2819 that initial attempt to read the FW info via
2820 stlink_usb_version will fail and the device has to be reset
2821 in order to become operational.
2824 if (jtag_libusb_open(param->vid, param->pid, param->serial,
2825 &h->fd, stlink_usb_get_alternate_serial) != ERROR_OK) {
2826 LOG_ERROR("open failed");
2830 jtag_libusb_set_configuration(h->fd, 0);
2832 if (libusb_claim_interface(h->fd, 0) != ERROR_OK) {
2833 LOG_DEBUG("claim interface failed");
2837 /* RX EP is common for all versions */
2838 h->rx_ep = STLINK_RX_EP;
2841 if (jtag_libusb_get_pid(libusb_get_device(h->fd), &pid) != ERROR_OK) {
2842 LOG_DEBUG("libusb_get_pid failed");
2846 /* wrap version for first read */
2849 h->version.stlink = 1;
2850 h->tx_ep = STLINK_TX_EP;
2852 case STLINK_V3_USBLOADER_PID:
2853 case STLINK_V3E_PID:
2854 case STLINK_V3S_PID:
2855 case STLINK_V3_2VCP_PID:
2856 h->version.stlink = 3;
2857 h->tx_ep = STLINK_V2_1_TX_EP;
2858 h->trace_ep = STLINK_V2_1_TRACE_EP;
2860 case STLINK_V2_1_PID:
2861 case STLINK_V2_1_NO_MSD_PID:
2862 h->version.stlink = 2;
2863 h->tx_ep = STLINK_V2_1_TX_EP;
2864 h->trace_ep = STLINK_V2_1_TRACE_EP;
2867 /* fall through - we assume V2 to be the default version*/
2869 h->version.stlink = 2;
2870 h->tx_ep = STLINK_TX_EP;
2871 h->trace_ep = STLINK_TRACE_EP;
2875 /* get the device version */
2876 err = stlink_usb_version(h);
2878 if (err == ERROR_OK) {
2880 } else if (h->version.stlink == 1 ||
2882 LOG_ERROR("read version failed");
2885 err = libusb_release_interface(h->fd, 0);
2886 if (err != ERROR_OK) {
2887 LOG_ERROR("release interface failed");
2891 err = libusb_reset_device(h->fd);
2892 if (err != ERROR_OK) {
2893 LOG_ERROR("reset device failed");
2897 jtag_libusb_close(h->fd);
2899 Give the device one second to settle down and
2902 usleep(1 * 1000 * 1000);
2907 /* check if mode is supported */
2910 switch (h->st_mode) {
2911 case STLINK_MODE_DEBUG_SWD:
2912 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2915 case STLINK_MODE_DEBUG_JTAG:
2916 if (h->version.jtag == 0)
2919 case STLINK_MODE_DEBUG_SWIM:
2920 if (h->version.swim == 0)
2928 if (err != ERROR_OK) {
2929 LOG_ERROR("mode (transport) not supported by device");
2933 /* initialize the debug hardware */
2934 err = stlink_usb_init_mode(h, param->connect_under_reset, param->initial_interface_speed);
2936 if (err != ERROR_OK) {
2937 LOG_ERROR("init mode failed (unable to connect to the target)");
2941 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
2942 err = stlink_swim_enter(h);
2943 if (err != ERROR_OK) {
2944 LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
2948 h->max_mem_packet = STLINK_DATA_SIZE;
2952 /* get cpuid, so we can determine the max page size
2953 * start with a safe default */
2954 h->max_mem_packet = (1 << 10);
2957 stlink_usb_open_ap(h, 0);
2958 err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
2959 if (err == ERROR_OK) {
2960 uint32_t cpuid = le_to_h_u32(buffer);
2961 int i = (cpuid >> 4) & 0xf;
2962 if (i == 4 || i == 3) {
2963 /* Cortex-M3/M4 has 4096 bytes autoincrement range */
2964 h->max_mem_packet = (1 << 12);
2968 LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
2975 stlink_usb_close(h);
2980 static int stlink_usb_hl_open(struct hl_interface_param_s *param, void **fd)
2982 return stlink_usb_open(param, stlink_get_mode(param->transport), fd);
2985 int stlink_config_trace(void *handle, bool enabled,
2986 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
2987 unsigned int *trace_freq, unsigned int traceclkin_freq,
2988 uint16_t *prescaler)
2990 struct stlink_usb_handle_s *h = handle;
2993 if (enabled && (!(h->version.flags & STLINK_F_HAS_TRACE) ||
2994 pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART)) {
2995 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
2999 /* Only concern ourselves with the frequency if the STlink is processing it. */
3000 if (enabled && *trace_freq > STLINK_TRACE_MAX_HZ) {
3001 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
3002 STLINK_TRACE_MAX_HZ);
3006 stlink_usb_trace_disable(h);
3009 *trace_freq = STLINK_TRACE_MAX_HZ;
3011 presc = traceclkin_freq / *trace_freq;
3013 if (traceclkin_freq % *trace_freq > 0)
3016 if (presc > TPIU_ACPR_MAX_SWOSCALER) {
3017 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
3027 h->trace.source_hz = *trace_freq;
3029 return stlink_usb_trace_enable(h);
3033 static int stlink_usb_init_access_port(void *handle, unsigned char ap_num)
3035 struct stlink_usb_handle_s *h = handle;
3037 assert(handle != NULL);
3039 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3040 return ERROR_COMMAND_NOTFOUND;
3042 LOG_DEBUG_IO("init ap_num = %d", ap_num);
3043 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3044 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3045 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_INIT_AP;
3046 h->cmdbuf[h->cmdidx++] = ap_num;
3048 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3052 static int stlink_usb_close_access_port(void *handle, unsigned char ap_num)
3054 struct stlink_usb_handle_s *h = handle;
3056 assert(handle != NULL);
3058 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3059 return ERROR_COMMAND_NOTFOUND;
3061 LOG_DEBUG_IO("close ap_num = %d", ap_num);
3062 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3063 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3064 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_CLOSE_AP_DBG;
3065 h->cmdbuf[h->cmdidx++] = ap_num;
3067 /* ignore incorrectly returned error on bogus FW */
3068 if (h->version.flags & STLINK_F_FIX_CLOSE_AP)
3069 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3071 return stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
3076 static int stlink_read_dap_register(void *handle, unsigned short dap_port,
3077 unsigned short addr, uint32_t *val)
3079 struct stlink_usb_handle_s *h = handle;
3082 assert(handle != NULL);
3084 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3085 return ERROR_COMMAND_NOTFOUND;
3087 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3088 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3089 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_DAP_REG;
3090 h_u16_to_le(&h->cmdbuf[2], dap_port);
3091 h_u16_to_le(&h->cmdbuf[4], addr);
3093 retval = stlink_usb_xfer_errcheck(handle, h->databuf, 8);
3094 *val = le_to_h_u32(h->databuf + 4);
3095 LOG_DEBUG_IO("dap_port_read = %d, addr = 0x%x, value = 0x%" PRIx32, dap_port, addr, *val);
3100 static int stlink_write_dap_register(void *handle, unsigned short dap_port,
3101 unsigned short addr, uint32_t val)
3103 struct stlink_usb_handle_s *h = handle;
3105 assert(handle != NULL);
3107 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3108 return ERROR_COMMAND_NOTFOUND;
3110 LOG_DEBUG_IO("dap_write port = %d, addr = 0x%x, value = 0x%" PRIx32, dap_port, addr, val);
3111 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3112 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3113 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITE_DAP_REG;
3114 h_u16_to_le(&h->cmdbuf[2], dap_port);
3115 h_u16_to_le(&h->cmdbuf[4], addr);
3116 h_u32_to_le(&h->cmdbuf[6], val);
3117 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3121 struct hl_layout_api_s stlink_usb_layout_api = {
3123 .open = stlink_usb_hl_open,
3125 .close = stlink_usb_close,
3127 .idcode = stlink_usb_idcode,
3129 .state = stlink_usb_state,
3131 .reset = stlink_usb_reset,
3133 .assert_srst = stlink_usb_assert_srst,
3135 .run = stlink_usb_run,
3137 .halt = stlink_usb_halt,
3139 .step = stlink_usb_step,
3141 .read_regs = stlink_usb_read_regs,
3143 .read_reg = stlink_usb_read_reg,
3145 .write_reg = stlink_usb_write_reg,
3147 .read_mem = stlink_usb_read_mem,
3149 .write_mem = stlink_usb_write_mem,
3151 .write_debug_reg = stlink_usb_write_debug_reg,
3153 .override_target = stlink_usb_override_target,
3155 .speed = stlink_speed,
3157 .config_trace = stlink_config_trace,
3159 .poll_trace = stlink_usb_trace_read,
3162 /*****************************************************************************
3163 * DAP direct interface
3166 static struct stlink_usb_handle_s *stlink_dap_handle;
3167 static struct hl_interface_param_s stlink_dap_param;
3168 static DECLARE_BITMAP(opened_ap, DP_APSEL_MAX + 1);
3169 static int stlink_dap_error = ERROR_OK;
3171 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3175 static int stlink_dap_record_error(int error)
3177 if (stlink_dap_error == ERROR_OK)
3178 stlink_dap_error = error;
3183 static int stlink_dap_get_and_clear_error(void)
3185 int retval = stlink_dap_error;
3186 stlink_dap_error = ERROR_OK;
3190 static int stlink_usb_open_ap(void *handle, unsigned short apsel)
3192 struct stlink_usb_handle_s *h = handle;
3195 /* nothing to do on old versions */
3196 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3199 if (apsel > DP_APSEL_MAX)
3202 if (test_bit(apsel, opened_ap))
3205 retval = stlink_usb_init_access_port(h, apsel);
3206 if (retval != ERROR_OK)
3209 LOG_DEBUG("AP %d enabled", apsel);
3210 set_bit(apsel, opened_ap);
3214 static int stlink_dap_open_ap(unsigned short apsel)
3216 return stlink_usb_open_ap(stlink_dap_handle, apsel);
3220 static int stlink_dap_closeall_ap(void)
3224 /* nothing to do on old versions */
3225 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3228 for (apsel = 0; apsel <= DP_APSEL_MAX; apsel++) {
3229 if (!test_bit(apsel, opened_ap))
3231 retval = stlink_usb_close_access_port(stlink_dap_handle, apsel);
3232 if (retval != ERROR_OK)
3234 clear_bit(apsel, opened_ap);
3240 static int stlink_dap_reinit_interface(void)
3245 * On JTAG only, it should be enough to call stlink_usb_reset(). But on
3246 * some firmware version it does not work as expected, and there is no
3247 * equivalent for SWD.
3248 * At least for now, to reset the interface quit from JTAG/SWD mode then
3249 * select the mode again.
3252 if (!stlink_dap_handle->reconnect_pending) {
3253 stlink_dap_handle->reconnect_pending = true;
3254 stlink_usb_mode_leave(stlink_dap_handle, stlink_dap_handle->st_mode);
3257 retval = stlink_usb_mode_enter(stlink_dap_handle, stlink_dap_handle->st_mode);
3258 if (retval != ERROR_OK)
3261 stlink_dap_handle->reconnect_pending = false;
3262 /* on new FW, calling mode-leave closes all the opened AP; reopen them! */
3263 if (stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT)
3264 for (int apsel = 0; apsel <= DP_APSEL_MAX; apsel++)
3265 if (test_bit(apsel, opened_ap)) {
3266 clear_bit(apsel, opened_ap);
3267 stlink_dap_open_ap(apsel);
3273 static int stlink_dap_op_connect(struct adiv5_dap *dap)
3278 LOG_INFO("stlink_dap_op_connect(%sconnect)", dap->do_reconnect ? "re" : "");
3280 /* Check if we should reset srst already when connecting, but not if reconnecting. */
3281 if (!dap->do_reconnect) {
3282 enum reset_types jtag_reset_config = jtag_get_reset_config();
3284 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3285 if (jtag_reset_config & RESET_SRST_NO_GATING)
3286 adapter_assert_reset();
3288 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3292 dap->do_reconnect = false;
3293 dap_invalidate_cache(dap);
3295 retval = dap_dp_init(dap);
3296 if (retval != ERROR_OK) {
3297 dap->do_reconnect = true;
3301 retval = stlink_usb_idcode(stlink_dap_handle, &idcode);
3302 if (retval == ERROR_OK)
3303 LOG_INFO("%s %#8.8" PRIx32,
3304 (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) ? "JTAG IDCODE" : "SWD DPIDR",
3307 dap->do_reconnect = true;
3313 static int stlink_dap_check_reconnect(struct adiv5_dap *dap)
3317 if (!dap->do_reconnect)
3320 retval = stlink_dap_reinit_interface();
3321 if (retval != ERROR_OK)
3324 return stlink_dap_op_connect(dap);
3328 static int stlink_dap_op_send_sequence(struct adiv5_dap *dap, enum swd_special_seq seq)
3330 /* Ignore the request */
3335 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3341 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3342 if (reg & 0x000000F0) {
3343 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3344 return ERROR_COMMAND_NOTFOUND;
3347 retval = stlink_dap_check_reconnect(dap);
3348 if (retval != ERROR_OK)
3351 data = data ? : &dummy;
3352 if (stlink_dap_handle->version.flags & STLINK_F_QUIRK_JTAG_DP_READ
3353 && stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) {
3354 /* Quirk required in JTAG. Read RDBUFF to get the data */
3355 retval = stlink_read_dap_register(stlink_dap_handle,
3356 STLINK_DEBUG_PORT_ACCESS, reg, &dummy);
3357 if (retval == ERROR_OK)
3358 retval = stlink_read_dap_register(stlink_dap_handle,
3359 STLINK_DEBUG_PORT_ACCESS, DP_RDBUFF, data);
3361 retval = stlink_read_dap_register(stlink_dap_handle,
3362 STLINK_DEBUG_PORT_ACCESS, reg, data);
3365 return stlink_dap_record_error(retval);
3369 static int stlink_dap_op_queue_dp_write(struct adiv5_dap *dap, unsigned reg,
3374 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3375 if (reg & 0x000000F0) {
3376 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3377 return ERROR_COMMAND_NOTFOUND;
3380 if (reg == DP_SELECT && (data & DP_SELECT_DPBANK) != 0) {
3381 /* ignored if STLINK_F_HAS_DPBANKSEL, not properly managed otherwise */
3382 LOG_DEBUG("Ignoring DPBANKSEL while write SELECT");
3383 data &= ~DP_SELECT_DPBANK;
3386 retval = stlink_dap_check_reconnect(dap);
3387 if (retval != ERROR_OK)
3390 /* ST-Link does not like that we set CORUNDETECT */
3391 if (reg == DP_CTRL_STAT)
3392 data &= ~CORUNDETECT;
3394 retval = stlink_write_dap_register(stlink_dap_handle,
3395 STLINK_DEBUG_PORT_ACCESS, reg, data);
3396 return stlink_dap_record_error(retval);
3400 static int stlink_dap_op_queue_ap_read(struct adiv5_ap *ap, unsigned reg,
3403 struct adiv5_dap *dap = ap->dap;
3407 retval = stlink_dap_check_reconnect(dap);
3408 if (retval != ERROR_OK)
3411 if (reg != AP_REG_IDR) {
3412 retval = stlink_dap_open_ap(ap->ap_num);
3413 if (retval != ERROR_OK)
3416 data = data ? : &dummy;
3417 retval = stlink_read_dap_register(stlink_dap_handle, ap->ap_num, reg,
3419 dap->stlink_flush_ap_write = false;
3420 return stlink_dap_record_error(retval);
3424 static int stlink_dap_op_queue_ap_write(struct adiv5_ap *ap, unsigned reg,
3427 struct adiv5_dap *dap = ap->dap;
3430 retval = stlink_dap_check_reconnect(dap);
3431 if (retval != ERROR_OK)
3434 retval = stlink_dap_open_ap(ap->ap_num);
3435 if (retval != ERROR_OK)
3438 retval = stlink_write_dap_register(stlink_dap_handle, ap->ap_num, reg,
3440 dap->stlink_flush_ap_write = true;
3441 return stlink_dap_record_error(retval);
3445 static int stlink_dap_op_queue_ap_abort(struct adiv5_dap *dap, uint8_t *ack)
3447 LOG_WARNING("stlink_dap_op_queue_ap_abort()");
3452 static int stlink_dap_op_run(struct adiv5_dap *dap)
3454 uint32_t ctrlstat, pwrmask;
3455 int retval, saved_retval;
3457 /* Here no LOG_DEBUG. This is called continuously! */
3460 * ST-Link returns immediately after a DAP write, without waiting for it
3462 * Run a dummy read to DP_RDBUFF, as suggested in
3463 * http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka16363.html
3465 if (dap->stlink_flush_ap_write) {
3466 dap->stlink_flush_ap_write = false;
3467 retval = stlink_dap_op_queue_dp_read(dap, DP_RDBUFF, NULL);
3468 if (retval != ERROR_OK) {
3469 dap->do_reconnect = true;
3474 saved_retval = stlink_dap_get_and_clear_error();
3476 retval = stlink_dap_op_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
3477 if (retval != ERROR_OK) {
3478 dap->do_reconnect = true;
3481 retval = stlink_dap_get_and_clear_error();
3482 if (retval != ERROR_OK) {
3483 LOG_ERROR("Fail reading CTRL/STAT register. Force reconnect");
3484 dap->do_reconnect = true;
3488 if (ctrlstat & SSTICKYERR) {
3489 if (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG)
3490 retval = stlink_dap_op_queue_dp_write(dap, DP_CTRL_STAT,
3491 ctrlstat & (dap->dp_ctrl_stat | SSTICKYERR));
3493 retval = stlink_dap_op_queue_dp_write(dap, DP_ABORT, STKERRCLR);
3494 if (retval != ERROR_OK) {
3495 dap->do_reconnect = true;
3498 retval = stlink_dap_get_and_clear_error();
3499 if (retval != ERROR_OK) {
3500 dap->do_reconnect = true;
3505 /* check for power lost */
3506 pwrmask = dap->dp_ctrl_stat & (CDBGPWRUPREQ | CSYSPWRUPREQ);
3507 if ((ctrlstat & pwrmask) != pwrmask)
3508 dap->do_reconnect = true;
3510 return saved_retval;
3514 static void stlink_dap_op_quit(struct adiv5_dap *dap)
3518 retval = stlink_dap_closeall_ap();
3519 if (retval != ERROR_OK)
3520 LOG_ERROR("Error closing APs");
3523 static int stlink_swim_op_srst(void)
3525 return stlink_swim_generate_rst(stlink_dap_handle);
3528 static int stlink_swim_op_read_mem(uint32_t addr, uint32_t size,
3529 uint32_t count, uint8_t *buffer)
3532 uint32_t bytes_remaining;
3534 LOG_DEBUG_IO("read at 0x%08" PRIx32 " len %" PRIu32 "*0x%08" PRIx32, addr, size, count);
3538 bytes_remaining = (count > STLINK_DATA_SIZE) ? STLINK_DATA_SIZE : count;
3539 retval = stlink_swim_readbytes(stlink_dap_handle, addr, bytes_remaining, buffer);
3540 if (retval != ERROR_OK)
3543 buffer += bytes_remaining;
3544 addr += bytes_remaining;
3545 count -= bytes_remaining;
3551 static int stlink_swim_op_write_mem(uint32_t addr, uint32_t size,
3552 uint32_t count, const uint8_t *buffer)
3555 uint32_t bytes_remaining;
3557 LOG_DEBUG_IO("write at 0x%08" PRIx32 " len %" PRIu32 "*0x%08" PRIx32, addr, size, count);
3561 bytes_remaining = (count > STLINK_DATA_SIZE) ? STLINK_DATA_SIZE : count;
3562 retval = stlink_swim_writebytes(stlink_dap_handle, addr, bytes_remaining, buffer);
3563 if (retval != ERROR_OK)
3566 buffer += bytes_remaining;
3567 addr += bytes_remaining;
3568 count -= bytes_remaining;
3574 static int stlink_swim_op_reconnect(void)
3578 retval = stlink_usb_mode_enter(stlink_dap_handle, STLINK_MODE_DEBUG_SWIM);
3579 if (retval != ERROR_OK)
3582 return stlink_swim_resync(stlink_dap_handle);
3585 static int stlink_dap_config_trace(bool enabled,
3586 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
3587 unsigned int *trace_freq, unsigned int traceclkin_freq,
3588 uint16_t *prescaler)
3590 return stlink_config_trace(stlink_dap_handle, enabled, pin_protocol,
3591 port_size, trace_freq, traceclkin_freq,
3595 static int stlink_dap_trace_read(uint8_t *buf, size_t *size)
3597 return stlink_usb_trace_read(stlink_dap_handle, buf, size);
3601 COMMAND_HANDLER(stlink_dap_serial_command)
3603 LOG_DEBUG("stlink_dap_serial_command");
3605 if (CMD_ARGC != 1) {
3606 LOG_ERROR("Expected exactly one argument for \"st-link serial <serial-number>\".");
3607 return ERROR_COMMAND_SYNTAX_ERROR;
3610 if (stlink_dap_param.serial) {
3611 LOG_WARNING("Command \"st-link serial\" already used. Replacing previous value");
3612 free((void *)stlink_dap_param.serial);
3615 stlink_dap_param.serial = strdup(CMD_ARGV[0]);
3620 COMMAND_HANDLER(stlink_dap_vid_pid)
3622 unsigned int i, max_usb_ids = HLA_MAX_USB_IDS;
3624 if (CMD_ARGC > max_usb_ids * 2) {
3625 LOG_WARNING("ignoring extra IDs in vid_pid "
3626 "(maximum is %d pairs)", max_usb_ids);
3627 CMD_ARGC = max_usb_ids * 2;
3629 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
3630 LOG_WARNING("incomplete vid_pid configuration directive");
3631 return ERROR_COMMAND_SYNTAX_ERROR;
3633 for (i = 0; i < CMD_ARGC; i += 2) {
3634 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], stlink_dap_param.vid[i / 2]);
3635 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], stlink_dap_param.pid[i / 2]);
3638 /* null termination */
3639 stlink_dap_param.vid[i / 2] = stlink_dap_param.pid[i / 2] = 0;
3645 static const struct command_registration stlink_dap_subcommand_handlers[] = {
3648 .handler = stlink_dap_serial_command,
3649 .mode = COMMAND_CONFIG,
3650 .help = "set the serial number of the adapter",
3651 .usage = "<serial_number>",
3655 .handler = stlink_dap_vid_pid,
3656 .mode = COMMAND_CONFIG,
3657 .help = "USB VID and PID of the adapter",
3658 .usage = "(vid pid)+",
3660 COMMAND_REGISTRATION_DONE
3664 static const struct command_registration stlink_dap_command_handlers[] = {
3667 .mode = COMMAND_ANY,
3668 .help = "perform st-link management",
3669 .chain = stlink_dap_subcommand_handlers,
3672 COMMAND_REGISTRATION_DONE
3676 static int stlink_dap_init(void)
3678 enum reset_types jtag_reset_config = jtag_get_reset_config();
3679 enum stlink_mode mode;
3682 LOG_DEBUG("stlink_dap_init()");
3684 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3685 if (jtag_reset_config & RESET_SRST_NO_GATING)
3686 stlink_dap_param.connect_under_reset = true;
3688 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3691 if (transport_is_dapdirect_swd())
3692 mode = STLINK_MODE_DEBUG_SWD;
3693 else if (transport_is_dapdirect_jtag())
3694 mode = STLINK_MODE_DEBUG_JTAG;
3695 else if (transport_is_swim())
3696 mode = STLINK_MODE_DEBUG_SWIM;
3698 LOG_ERROR("Unsupported transport");
3702 retval = stlink_usb_open(&stlink_dap_param, mode, (void **)&stlink_dap_handle);
3703 if (retval != ERROR_OK)
3706 if ((mode != STLINK_MODE_DEBUG_SWIM) &&
3707 !(stlink_dap_handle->version.flags & STLINK_F_HAS_DAP_REG)) {
3708 LOG_ERROR("ST-Link version does not support DAP direct transport");
3715 static int stlink_dap_quit(void)
3717 LOG_DEBUG("stlink_dap_quit()");
3719 free((void *)stlink_dap_param.serial);
3720 stlink_dap_param.serial = NULL;
3722 return stlink_usb_close(stlink_dap_handle);
3726 static int stlink_dap_reset(int req_trst, int req_srst)
3728 LOG_DEBUG("stlink_dap_reset(%d)", req_srst);
3729 return stlink_usb_assert_srst(stlink_dap_handle,
3730 req_srst ? STLINK_DEBUG_APIV2_DRIVE_NRST_LOW
3731 : STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH);
3735 static int stlink_dap_speed(int speed)
3738 LOG_ERROR("RTCK not supported. Set nonzero adapter_khz.");
3739 return ERROR_JTAG_NOT_IMPLEMENTED;
3742 stlink_dap_param.initial_interface_speed = speed;
3743 stlink_speed(stlink_dap_handle, speed, false);
3748 static int stlink_dap_khz(int khz, int *jtag_speed)
3751 LOG_ERROR("RCLK not supported");
3755 *jtag_speed = stlink_speed(stlink_dap_handle, khz, true);
3760 static int stlink_dap_speed_div(int speed, int *khz)
3766 static const struct dap_ops stlink_dap_ops = {
3767 .connect = stlink_dap_op_connect,
3768 .send_sequence = stlink_dap_op_send_sequence,
3769 .queue_dp_read = stlink_dap_op_queue_dp_read,
3770 .queue_dp_write = stlink_dap_op_queue_dp_write,
3771 .queue_ap_read = stlink_dap_op_queue_ap_read,
3772 .queue_ap_write = stlink_dap_op_queue_ap_write,
3773 .queue_ap_abort = stlink_dap_op_queue_ap_abort,
3774 .run = stlink_dap_op_run,
3775 .sync = NULL, /* optional */
3776 .quit = stlink_dap_op_quit, /* optional */
3779 static const struct swim_driver stlink_swim_ops = {
3780 .srst = stlink_swim_op_srst,
3781 .read_mem = stlink_swim_op_read_mem,
3782 .write_mem = stlink_swim_op_write_mem,
3783 .reconnect = stlink_swim_op_reconnect,
3786 static const char *const stlink_dap_transport[] = { "dapdirect_swd", "dapdirect_jtag", "swim", NULL };
3788 struct adapter_driver stlink_dap_adapter_driver = {
3790 .transports = stlink_dap_transport,
3791 .commands = stlink_dap_command_handlers,
3793 .init = stlink_dap_init,
3794 .quit = stlink_dap_quit,
3795 .reset = stlink_dap_reset,
3796 .speed = stlink_dap_speed,
3797 .khz = stlink_dap_khz,
3798 .speed_div = stlink_dap_speed_div,
3799 .config_trace = stlink_dap_config_trace,
3800 .poll_trace = stlink_dap_trace_read,
3802 .dap_jtag_ops = &stlink_dap_ops,
3803 .dap_swd_ops = &stlink_dap_ops,
3804 .swim_ops = &stlink_swim_ops,