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_common.h"
47 #define USE_LIBUSB_ASYNCIO
50 #define ENDPOINT_IN 0x80
51 #define ENDPOINT_OUT 0x00
53 #define STLINK_WRITE_TIMEOUT 1000
54 #define STLINK_READ_TIMEOUT 1000
56 #define STLINK_NULL_EP 0
57 #define STLINK_RX_EP (1|ENDPOINT_IN)
58 #define STLINK_TX_EP (2|ENDPOINT_OUT)
59 #define STLINK_TRACE_EP (3|ENDPOINT_IN)
61 #define STLINK_V2_1_TX_EP (1|ENDPOINT_OUT)
62 #define STLINK_V2_1_TRACE_EP (2|ENDPOINT_IN)
64 #define STLINK_SG_SIZE (31)
65 #define STLINK_DATA_SIZE (4096)
66 #define STLINK_CMD_SIZE_V2 (16)
67 #define STLINK_CMD_SIZE_V1 (10)
69 #define STLINK_V1_PID (0x3744)
70 #define STLINK_V2_PID (0x3748)
71 #define STLINK_V2_1_PID (0x374B)
72 #define STLINK_V2_1_NO_MSD_PID (0x3752)
73 #define STLINK_V3_USBLOADER_PID (0x374D)
74 #define STLINK_V3E_PID (0x374E)
75 #define STLINK_V3S_PID (0x374F)
76 #define STLINK_V3_2VCP_PID (0x3753)
79 * ST-Link/V1, ST-Link/V2 and ST-Link/V2.1 are full-speed USB devices and
80 * this limits the bulk packet size and the 8bit read/writes to max 64 bytes.
81 * STLINK-V3 is a high speed USB 2.0 and the limit is 512 bytes.
83 #define STLINK_MAX_RW8 (64)
84 #define STLINKV3_MAX_RW8 (512)
86 /* "WAIT" responses will be retried (with exponential backoff) at
87 * most this many times before failing to caller.
89 #define MAX_WAIT_RETRIES 8
91 enum stlink_jtag_api_version {
92 STLINK_JTAG_API_V1 = 1,
98 struct stlink_usb_version {
105 /** jtag api version supported */
106 enum stlink_jtag_api_version jtag_api;
107 /** one bit for each feature supported. See macros STLINK_F_* */
112 struct stlink_usb_handle_s {
114 struct jtag_libusb_device_handle *fd;
116 struct libusb_transfer *trans;
124 uint8_t cmdbuf[STLINK_SG_SIZE];
130 uint8_t databuf[STLINK_DATA_SIZE];
132 uint32_t max_mem_packet;
134 enum hl_transports transport;
136 struct stlink_usb_version version;
143 /** whether SWO tracing is enabled or not */
145 /** trace module source clock */
148 /** reconnect is needed next time we try to query the
150 bool reconnect_pending;
153 #define STLINK_SWIM_ERR_OK 0x00
154 #define STLINK_SWIM_BUSY 0x01
155 #define STLINK_DEBUG_ERR_OK 0x80
156 #define STLINK_DEBUG_ERR_FAULT 0x81
157 #define STLINK_SWD_AP_WAIT 0x10
158 #define STLINK_SWD_AP_FAULT 0x11
159 #define STLINK_SWD_AP_ERROR 0x12
160 #define STLINK_SWD_AP_PARITY_ERROR 0x13
161 #define STLINK_JTAG_GET_IDCODE_ERROR 0x09
162 #define STLINK_JTAG_WRITE_ERROR 0x0c
163 #define STLINK_JTAG_WRITE_VERIF_ERROR 0x0d
164 #define STLINK_SWD_DP_WAIT 0x14
165 #define STLINK_SWD_DP_FAULT 0x15
166 #define STLINK_SWD_DP_ERROR 0x16
167 #define STLINK_SWD_DP_PARITY_ERROR 0x17
169 #define STLINK_SWD_AP_WDATA_ERROR 0x18
170 #define STLINK_SWD_AP_STICKY_ERROR 0x19
171 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
173 #define STLINK_BAD_AP_ERROR 0x1d
175 #define STLINK_CORE_RUNNING 0x80
176 #define STLINK_CORE_HALTED 0x81
177 #define STLINK_CORE_STAT_UNKNOWN -1
179 #define STLINK_GET_VERSION 0xF1
180 #define STLINK_DEBUG_COMMAND 0xF2
181 #define STLINK_DFU_COMMAND 0xF3
182 #define STLINK_SWIM_COMMAND 0xF4
183 #define STLINK_GET_CURRENT_MODE 0xF5
184 #define STLINK_GET_TARGET_VOLTAGE 0xF7
186 #define STLINK_DEV_DFU_MODE 0x00
187 #define STLINK_DEV_MASS_MODE 0x01
188 #define STLINK_DEV_DEBUG_MODE 0x02
189 #define STLINK_DEV_SWIM_MODE 0x03
190 #define STLINK_DEV_BOOTLOADER_MODE 0x04
191 #define STLINK_DEV_UNKNOWN_MODE -1
193 #define STLINK_DFU_EXIT 0x07
196 STLINK_SWIM_ENTER_SEQ
197 1.3ms low then 750Hz then 1.5kHz
200 STM8 DM pulls reset pin low 50us
203 uint8_t (0=low|1=high)
210 send syncronization seq (16us low, response 64 clocks low)
212 #define STLINK_SWIM_ENTER 0x00
213 #define STLINK_SWIM_EXIT 0x01
214 #define STLINK_SWIM_READ_CAP 0x02
215 #define STLINK_SWIM_SPEED 0x03
216 #define STLINK_SWIM_ENTER_SEQ 0x04
217 #define STLINK_SWIM_GEN_RST 0x05
218 #define STLINK_SWIM_RESET 0x06
219 #define STLINK_SWIM_ASSERT_RESET 0x07
220 #define STLINK_SWIM_DEASSERT_RESET 0x08
221 #define STLINK_SWIM_READSTATUS 0x09
222 #define STLINK_SWIM_WRITEMEM 0x0a
223 #define STLINK_SWIM_READMEM 0x0b
224 #define STLINK_SWIM_READBUF 0x0c
226 #define STLINK_DEBUG_GETSTATUS 0x01
227 #define STLINK_DEBUG_FORCEDEBUG 0x02
228 #define STLINK_DEBUG_APIV1_RESETSYS 0x03
229 #define STLINK_DEBUG_APIV1_READALLREGS 0x04
230 #define STLINK_DEBUG_APIV1_READREG 0x05
231 #define STLINK_DEBUG_APIV1_WRITEREG 0x06
232 #define STLINK_DEBUG_READMEM_32BIT 0x07
233 #define STLINK_DEBUG_WRITEMEM_32BIT 0x08
234 #define STLINK_DEBUG_RUNCORE 0x09
235 #define STLINK_DEBUG_STEPCORE 0x0a
236 #define STLINK_DEBUG_APIV1_SETFP 0x0b
237 #define STLINK_DEBUG_READMEM_8BIT 0x0c
238 #define STLINK_DEBUG_WRITEMEM_8BIT 0x0d
239 #define STLINK_DEBUG_APIV1_CLEARFP 0x0e
240 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG 0x0f
241 #define STLINK_DEBUG_APIV1_SETWATCHPOINT 0x10
243 #define STLINK_DEBUG_ENTER_JTAG_RESET 0x00
244 #define STLINK_DEBUG_ENTER_SWD_NO_RESET 0xa3
245 #define STLINK_DEBUG_ENTER_JTAG_NO_RESET 0xa4
247 #define STLINK_DEBUG_APIV1_ENTER 0x20
248 #define STLINK_DEBUG_EXIT 0x21
249 #define STLINK_DEBUG_READCOREID 0x22
251 #define STLINK_DEBUG_APIV2_ENTER 0x30
252 #define STLINK_DEBUG_APIV2_READ_IDCODES 0x31
253 #define STLINK_DEBUG_APIV2_RESETSYS 0x32
254 #define STLINK_DEBUG_APIV2_READREG 0x33
255 #define STLINK_DEBUG_APIV2_WRITEREG 0x34
256 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG 0x35
257 #define STLINK_DEBUG_APIV2_READDEBUGREG 0x36
259 #define STLINK_DEBUG_APIV2_READALLREGS 0x3A
260 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
261 #define STLINK_DEBUG_APIV2_DRIVE_NRST 0x3C
263 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS2 0x3E
265 #define STLINK_DEBUG_APIV2_START_TRACE_RX 0x40
266 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX 0x41
267 #define STLINK_DEBUG_APIV2_GET_TRACE_NB 0x42
268 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ 0x43
269 #define STLINK_DEBUG_APIV2_JTAG_SET_FREQ 0x44
270 #define STLINK_DEBUG_APIV2_READ_DAP_REG 0x45
271 #define STLINK_DEBUG_APIV2_WRITE_DAP_REG 0x46
272 #define STLINK_DEBUG_APIV2_READMEM_16BIT 0x47
273 #define STLINK_DEBUG_APIV2_WRITEMEM_16BIT 0x48
275 #define STLINK_DEBUG_APIV2_INIT_AP 0x4B
276 #define STLINK_DEBUG_APIV2_CLOSE_AP_DBG 0x4C
278 #define STLINK_APIV3_SET_COM_FREQ 0x61
279 #define STLINK_APIV3_GET_COM_FREQ 0x62
281 #define STLINK_APIV3_GET_VERSION_EX 0xFB
283 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW 0x00
284 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH 0x01
285 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
287 #define STLINK_DEBUG_PORT_ACCESS 0xffff
289 #define STLINK_TRACE_SIZE 4096
290 #define STLINK_TRACE_MAX_HZ 2000000
292 #define STLINK_V3_MAX_FREQ_NB 10
296 STLINK_MODE_UNKNOWN = 0,
299 STLINK_MODE_DEBUG_JTAG,
300 STLINK_MODE_DEBUG_SWD,
301 STLINK_MODE_DEBUG_SWIM
304 #define REQUEST_SENSE 0x03
305 #define REQUEST_SENSE_LENGTH 18
308 * Map the relevant features, quirks and workaround for specific firmware
311 #define STLINK_F_HAS_TRACE BIT(0)
312 #define STLINK_F_HAS_SWD_SET_FREQ BIT(1)
313 #define STLINK_F_HAS_JTAG_SET_FREQ BIT(2)
314 #define STLINK_F_HAS_MEM_16BIT BIT(3)
315 #define STLINK_F_HAS_GETLASTRWSTATUS2 BIT(4)
316 #define STLINK_F_HAS_DAP_REG BIT(5)
317 #define STLINK_F_QUIRK_JTAG_DP_READ BIT(6)
318 #define STLINK_F_HAS_AP_INIT BIT(7)
319 #define STLINK_F_HAS_DPBANKSEL BIT(8)
322 #define STLINK_F_HAS_TARGET_VOLT STLINK_F_HAS_TRACE
329 /* SWD clock speed */
330 static const struct speed_map stlink_khz_to_speed_map_swd[] = {
332 {1800, 1}, /* default */
345 /* JTAG clock speed */
346 static const struct speed_map stlink_khz_to_speed_map_jtag[] = {
351 {1125, 32}, /* default */
357 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
358 static int stlink_swim_status(void *handle);
359 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size);
360 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map);
361 static int stlink_speed(void *handle, int khz, bool query);
364 static unsigned int stlink_usb_block(void *handle)
366 struct stlink_usb_handle_s *h = handle;
368 assert(handle != NULL);
370 if (h->version.stlink == 3)
371 return STLINKV3_MAX_RW8;
373 return STLINK_MAX_RW8;
378 #ifdef USE_LIBUSB_ASYNCIO
380 static LIBUSB_CALL void sync_transfer_cb(struct libusb_transfer *transfer)
382 int *completed = transfer->user_data;
384 /* caller interprets result and frees transfer */
388 static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
390 int r, *completed = transfer->user_data;
392 /* Assuming a single libusb context exists. There no existing interface into this
393 * module to pass a libusb context.
395 struct libusb_context *ctx = NULL;
397 while (!*completed) {
398 r = libusb_handle_events_completed(ctx, completed);
400 if (r == LIBUSB_ERROR_INTERRUPTED)
402 libusb_cancel_transfer(transfer);
409 static int transfer_error_status(const struct libusb_transfer *transfer)
413 switch (transfer->status) {
414 case LIBUSB_TRANSFER_COMPLETED:
417 case LIBUSB_TRANSFER_TIMED_OUT:
418 r = LIBUSB_ERROR_TIMEOUT;
420 case LIBUSB_TRANSFER_STALL:
421 r = LIBUSB_ERROR_PIPE;
423 case LIBUSB_TRANSFER_OVERFLOW:
424 r = LIBUSB_ERROR_OVERFLOW;
426 case LIBUSB_TRANSFER_NO_DEVICE:
427 r = LIBUSB_ERROR_NO_DEVICE;
429 case LIBUSB_TRANSFER_ERROR:
430 case LIBUSB_TRANSFER_CANCELLED:
434 r = LIBUSB_ERROR_OTHER;
448 size_t transfer_size;
449 struct libusb_transfer *transfer;
452 static int jtag_libusb_bulk_transfer_n(
453 jtag_libusb_device_handle * dev_handle,
454 struct jtag_xfer *transfers,
459 int returnval = ERROR_OK;
462 for (size_t i = 0; i < n_transfers; ++i) {
463 transfers[i].retval = 0;
464 transfers[i].completed = 0;
465 transfers[i].transfer_size = 0;
466 transfers[i].transfer = libusb_alloc_transfer(0);
468 if (transfers[i].transfer == NULL) {
469 for (size_t j = 0; j < i; ++j)
470 libusb_free_transfer(transfers[j].transfer);
472 LOG_DEBUG("ERROR, failed to alloc usb transfers");
473 for (size_t k = 0; k < n_transfers; ++k)
474 transfers[k].retval = LIBUSB_ERROR_NO_MEM;
479 for (size_t i = 0; i < n_transfers; ++i) {
480 libusb_fill_bulk_transfer(
481 transfers[i].transfer,
483 transfers[i].ep, transfers[i].buf, transfers[i].size,
484 sync_transfer_cb, &transfers[i].completed, timeout);
485 transfers[i].transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
487 retval = libusb_submit_transfer(transfers[i].transfer);
489 LOG_DEBUG("ERROR, failed to submit transfer %zu, error %d", i, retval);
491 /* Probably no point continuing to submit transfers once a submission fails.
492 * As a result, tag all remaining transfers as errors.
494 for (size_t j = i; j < n_transfers; ++j)
495 transfers[j].retval = retval;
497 returnval = ERROR_FAIL;
502 /* Wait for every submitted USB transfer to complete.
504 for (size_t i = 0; i < n_transfers; ++i) {
505 if (transfers[i].retval == 0) {
506 sync_transfer_wait_for_completion(transfers[i].transfer);
508 retval = transfer_error_status(transfers[i].transfer);
510 returnval = ERROR_FAIL;
511 transfers[i].retval = retval;
512 LOG_DEBUG("ERROR, transfer %zu failed, error %d", i, retval);
514 /* Assuming actual_length is only valid if there is no transfer error.
516 transfers[i].transfer_size = transfers[i].transfer->actual_length;
520 libusb_free_transfer(transfers[i].transfer);
521 transfers[i].transfer = NULL;
531 static int stlink_usb_xfer_v1_get_status(void *handle)
533 struct stlink_usb_handle_s *h = handle;
535 assert(handle != NULL);
538 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
540 if (jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)h->cmdbuf,
541 13, STLINK_READ_TIMEOUT) != 13)
546 t1 = buf_get_u32(h->cmdbuf, 0, 32);
549 if (t1 != 0x53425355)
557 if (h->cmdbuf[12] != 0)
563 #ifdef USE_LIBUSB_ASYNCIO
564 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
566 struct stlink_usb_handle_s *h = handle;
568 assert(handle != NULL);
570 size_t n_transfers = 0;
571 struct jtag_xfer transfers[2];
573 memset(transfers, 0, sizeof(transfers));
575 transfers[0].ep = h->tx_ep;
576 transfers[0].buf = h->cmdbuf;
577 transfers[0].size = cmdsize;
581 if (h->direction == h->tx_ep && size) {
582 transfers[1].ep = h->tx_ep;
583 transfers[1].buf = (uint8_t *)buf;
584 transfers[1].size = size;
587 } else if (h->direction == h->rx_ep && size) {
588 transfers[1].ep = h->rx_ep;
589 transfers[1].buf = (uint8_t *)buf;
590 transfers[1].size = size;
595 return jtag_libusb_bulk_transfer_n(
599 STLINK_WRITE_TIMEOUT);
602 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
604 struct stlink_usb_handle_s *h = handle;
606 assert(handle != NULL);
608 if (jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)h->cmdbuf, cmdsize,
609 STLINK_WRITE_TIMEOUT) != cmdsize) {
613 if (h->direction == h->tx_ep && size) {
614 if (jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)buf,
615 size, STLINK_WRITE_TIMEOUT) != size) {
616 LOG_DEBUG("bulk write failed");
619 } else if (h->direction == h->rx_ep && size) {
620 if (jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)buf,
621 size, STLINK_READ_TIMEOUT) != size) {
622 LOG_DEBUG("bulk read failed");
632 static int stlink_usb_xfer_v1_get_sense(void *handle)
635 struct stlink_usb_handle_s *h = handle;
637 assert(handle != NULL);
639 stlink_usb_init_buffer(handle, h->rx_ep, 16);
641 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE;
642 h->cmdbuf[h->cmdidx++] = 0;
643 h->cmdbuf[h->cmdidx++] = 0;
644 h->cmdbuf[h->cmdidx++] = 0;
645 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE_LENGTH;
647 res = stlink_usb_xfer_rw(handle, REQUEST_SENSE_LENGTH, h->databuf, 16);
652 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK)
659 transfers block in cmdbuf
660 <size> indicates number of bytes in the following
662 Ignore the (eventual) error code in the received packet.
664 static int stlink_usb_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
666 int err, cmdsize = STLINK_CMD_SIZE_V2;
667 struct stlink_usb_handle_s *h = handle;
669 assert(handle != NULL);
671 if (h->version.stlink == 1) {
672 cmdsize = STLINK_SG_SIZE;
673 /* put length in bCBWCBLength */
674 h->cmdbuf[14] = h->cmdidx-15;
677 err = stlink_usb_xfer_rw(handle, cmdsize, buf, size);
682 if (h->version.stlink == 1) {
683 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK) {
684 /* check csw status */
685 if (h->cmdbuf[12] == 1) {
686 LOG_DEBUG("get sense");
687 if (stlink_usb_xfer_v1_get_sense(handle) != ERROR_OK)
698 Converts an STLINK status code held in the first byte of a response
699 to an openocd error, logs any error/wait status as debug output.
701 static int stlink_usb_error_check(void *handle)
703 struct stlink_usb_handle_s *h = handle;
705 assert(handle != NULL);
707 if (h->transport == HL_TRANSPORT_SWIM) {
708 switch (h->databuf[0]) {
709 case STLINK_SWIM_ERR_OK:
711 case STLINK_SWIM_BUSY:
714 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
719 /* TODO: no error checking yet on api V1 */
720 if (h->version.jtag_api == STLINK_JTAG_API_V1)
721 h->databuf[0] = STLINK_DEBUG_ERR_OK;
723 switch (h->databuf[0]) {
724 case STLINK_DEBUG_ERR_OK:
726 case STLINK_DEBUG_ERR_FAULT:
727 LOG_DEBUG("SWD fault response (0x%x)", STLINK_DEBUG_ERR_FAULT);
729 case STLINK_SWD_AP_WAIT:
730 LOG_DEBUG("wait status SWD_AP_WAIT (0x%x)", STLINK_SWD_AP_WAIT);
732 case STLINK_SWD_DP_WAIT:
733 LOG_DEBUG("wait status SWD_DP_WAIT (0x%x)", STLINK_SWD_DP_WAIT);
735 case STLINK_JTAG_GET_IDCODE_ERROR:
736 LOG_DEBUG("STLINK_JTAG_GET_IDCODE_ERROR");
738 case STLINK_JTAG_WRITE_ERROR:
739 LOG_DEBUG("Write error");
741 case STLINK_JTAG_WRITE_VERIF_ERROR:
742 LOG_DEBUG("Write verify error, ignoring");
744 case STLINK_SWD_AP_FAULT:
745 /* git://git.ac6.fr/openocd commit 657e3e885b9ee10
746 * returns ERROR_OK with the comment:
747 * Change in error status when reading outside RAM.
748 * This fix allows CDT plugin to visualize memory.
750 LOG_DEBUG("STLINK_SWD_AP_FAULT");
752 case STLINK_SWD_AP_ERROR:
753 LOG_DEBUG("STLINK_SWD_AP_ERROR");
755 case STLINK_SWD_AP_PARITY_ERROR:
756 LOG_DEBUG("STLINK_SWD_AP_PARITY_ERROR");
758 case STLINK_SWD_DP_FAULT:
759 LOG_DEBUG("STLINK_SWD_DP_FAULT");
761 case STLINK_SWD_DP_ERROR:
762 LOG_DEBUG("STLINK_SWD_DP_ERROR");
764 case STLINK_SWD_DP_PARITY_ERROR:
765 LOG_DEBUG("STLINK_SWD_DP_PARITY_ERROR");
767 case STLINK_SWD_AP_WDATA_ERROR:
768 LOG_DEBUG("STLINK_SWD_AP_WDATA_ERROR");
770 case STLINK_SWD_AP_STICKY_ERROR:
771 LOG_DEBUG("STLINK_SWD_AP_STICKY_ERROR");
773 case STLINK_SWD_AP_STICKYORUN_ERROR:
774 LOG_DEBUG("STLINK_SWD_AP_STICKYORUN_ERROR");
776 case STLINK_BAD_AP_ERROR:
777 LOG_DEBUG("STLINK_BAD_AP_ERROR");
780 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
786 * Wrapper around stlink_usb_xfer_noerrcheck()
787 * to check the error code in the received packet
789 static int stlink_usb_xfer_errcheck(void *handle, const uint8_t *buf, int size)
795 retval = stlink_usb_xfer_noerrcheck(handle, buf, size);
796 if (retval != ERROR_OK)
799 return stlink_usb_error_check(handle);
802 /** Issue an STLINK command via USB transfer, with retries on any wait status responses.
804 Works for commands where the STLINK_DEBUG status is returned in the first
805 byte of the response packet. For SWIM a SWIM_READSTATUS is requested instead.
807 Returns an openocd result code.
809 static int stlink_cmd_allow_retry(void *handle, const uint8_t *buf, int size)
813 struct stlink_usb_handle_s *h = handle;
816 if ((h->transport != HL_TRANSPORT_SWIM) || !retries) {
817 res = stlink_usb_xfer_noerrcheck(handle, buf, size);
822 if (h->transport == HL_TRANSPORT_SWIM) {
823 res = stlink_swim_status(handle);
828 res = stlink_usb_error_check(handle);
829 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
830 useconds_t delay_us = (1<<retries++) * 1000;
831 LOG_DEBUG("stlink_cmd_allow_retry ERROR_WAIT, retry %d, delaying %u microseconds", retries, delay_us);
840 static int stlink_usb_read_trace(void *handle, const uint8_t *buf, int size)
842 struct stlink_usb_handle_s *h = handle;
844 assert(handle != NULL);
846 assert(h->version.flags & STLINK_F_HAS_TRACE);
848 if (jtag_libusb_bulk_read(h->fd, h->trace_ep, (char *)buf,
849 size, STLINK_READ_TIMEOUT) != size) {
850 LOG_ERROR("bulk trace read failed");
858 this function writes transfer length in
859 the right place in the cb
861 static void stlink_usb_set_cbw_transfer_datalength(void *handle, uint32_t size)
863 struct stlink_usb_handle_s *h = handle;
865 buf_set_u32(h->cmdbuf+8, 0, 32, size);
868 static void stlink_usb_xfer_v1_create_cmd(void *handle, uint8_t direction, uint32_t size)
870 struct stlink_usb_handle_s *h = handle;
872 /* fill the send buffer */
873 strcpy((char *)h->cmdbuf, "USBC");
875 /* csw tag not used */
876 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, 0);
878 /* cbw data transfer length (in the following data phase in or out) */
879 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, size);
882 h->cmdbuf[h->cmdidx++] = (direction == h->rx_ep ? ENDPOINT_IN : ENDPOINT_OUT);
883 h->cmdbuf[h->cmdidx++] = 0; /* lun */
884 /* cdb clength (is filled in at xfer) */
885 h->cmdbuf[h->cmdidx++] = 0;
889 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size)
891 struct stlink_usb_handle_s *h = handle;
893 h->direction = direction;
897 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
898 memset(h->databuf, 0, STLINK_DATA_SIZE);
900 if (h->version.stlink == 1)
901 stlink_usb_xfer_v1_create_cmd(handle, direction, size);
905 static int stlink_usb_version(void *handle)
910 uint8_t v, x, y, jtag, swim, msd, bridge = 0;
911 char v_str[5 * (1 + 3) + 1]; /* VvJjMmBbSs */
913 struct stlink_usb_handle_s *h = handle;
915 assert(handle != NULL);
917 stlink_usb_init_buffer(handle, h->rx_ep, 6);
919 h->cmdbuf[h->cmdidx++] = STLINK_GET_VERSION;
921 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 6);
926 version = be_to_h_u16(h->databuf);
927 v = (version >> 12) & 0x0f;
928 x = (version >> 6) & 0x3f;
931 h->vid = le_to_h_u16(h->databuf + 2);
932 h->pid = le_to_h_u16(h->databuf + 4);
935 case STLINK_V2_1_PID:
936 case STLINK_V2_1_NO_MSD_PID:
937 if ((x <= 22 && y == 7) || (x >= 25 && y >= 7 && y <= 12)) {
938 /* MxSy : STM8 V2.1 - SWIM only */
943 /* JxMy : STM32 V2.1 - JTAG/SWD only */
956 /* STLINK-V3 requires a specific command */
957 if (v == 3 && x == 0 && y == 0) {
958 stlink_usb_init_buffer(handle, h->rx_ep, 16);
960 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_VERSION_EX;
962 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 12);
967 swim = h->databuf[1];
968 jtag = h->databuf[2];
970 bridge = h->databuf[4];
971 h->vid = le_to_h_u16(h->databuf + 8);
972 h->pid = le_to_h_u16(h->databuf + 10);
975 h->version.stlink = v;
976 h->version.jtag = jtag;
977 h->version.swim = swim;
980 switch (h->version.stlink) {
982 /* ST-LINK/V1 from J11 switch to api-v2 (and support SWD) */
983 if (h->version.jtag >= 11)
984 h->version.jtag_api = STLINK_JTAG_API_V2;
986 h->version.jtag_api = STLINK_JTAG_API_V1;
990 /* all ST-LINK/V2 and ST-Link/V2.1 use api-v2 */
991 h->version.jtag_api = STLINK_JTAG_API_V2;
993 /* API for trace from J13 */
994 /* API for target voltage from J13 */
995 if (h->version.jtag >= 13)
996 flags |= STLINK_F_HAS_TRACE;
998 /* preferred API to get last R/W status from J15 */
999 if (h->version.jtag >= 15)
1000 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1002 /* API to set SWD frequency from J22 */
1003 if (h->version.jtag >= 22)
1004 flags |= STLINK_F_HAS_SWD_SET_FREQ;
1006 /* API to set JTAG frequency from J24 */
1007 /* API to access DAP registers from J24 */
1008 if (h->version.jtag >= 24) {
1009 flags |= STLINK_F_HAS_JTAG_SET_FREQ;
1010 flags |= STLINK_F_HAS_DAP_REG;
1013 /* Quirk for read DP in JTAG mode (V2 only) from J24, fixed in J32 */
1014 if (h->version.jtag >= 24 && h->version.jtag < 32)
1015 flags |= STLINK_F_QUIRK_JTAG_DP_READ;
1017 /* API to read/write memory at 16 bit from J26 */
1018 if (h->version.jtag >= 26)
1019 flags |= STLINK_F_HAS_MEM_16BIT;
1021 /* API required to init AP before any AP access from J28 */
1022 if (h->version.jtag >= 28)
1023 flags |= STLINK_F_HAS_AP_INIT;
1025 /* Banked regs (DPv1 & DPv2) support from V2J32 */
1026 if (h->version.jtag >= 32)
1027 flags |= STLINK_F_HAS_DPBANKSEL;
1031 /* all STLINK-V3 use api-v3 */
1032 h->version.jtag_api = STLINK_JTAG_API_V3;
1034 /* STLINK-V3 is a superset of ST-LINK/V2 */
1037 /* API for target voltage */
1038 flags |= STLINK_F_HAS_TRACE;
1040 /* preferred API to get last R/W status */
1041 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1043 /* API to access DAP registers */
1044 flags |= STLINK_F_HAS_DAP_REG;
1046 /* API to read/write memory at 16 bit */
1047 flags |= STLINK_F_HAS_MEM_16BIT;
1049 /* API required to init AP before any AP access */
1050 flags |= STLINK_F_HAS_AP_INIT;
1052 /* Banked regs (DPv1 & DPv2) support from V3J2 */
1053 if (h->version.jtag >= 2)
1054 flags |= STLINK_F_HAS_DPBANKSEL;
1060 h->version.flags = flags;
1063 p += sprintf(p, "V%d", v);
1065 p += sprintf(p, "J%d", jtag);
1067 p += sprintf(p, "M%d", msd);
1069 p += sprintf(p, "B%d", bridge);
1071 sprintf(p, "S%d", swim);
1073 LOG_INFO("STLINK %s (API v%d) VID:PID %04X:%04X",
1075 h->version.jtag_api,
1082 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
1084 struct stlink_usb_handle_s *h = handle;
1085 uint32_t adc_results[2];
1087 /* no error message, simply quit with error */
1088 if (!(h->version.flags & STLINK_F_HAS_TARGET_VOLT))
1089 return ERROR_COMMAND_NOTFOUND;
1091 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1093 h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
1095 int result = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1097 if (result != ERROR_OK)
1100 /* convert result */
1101 adc_results[0] = le_to_h_u32(h->databuf);
1102 adc_results[1] = le_to_h_u32(h->databuf + 4);
1104 *target_voltage = 0;
1107 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
1109 LOG_INFO("Target voltage: %f", (double)*target_voltage);
1114 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
1116 struct stlink_usb_handle_s *h = handle;
1118 assert(handle != NULL);
1120 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
1121 return ERROR_COMMAND_NOTFOUND;
1123 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1125 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1126 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
1127 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1130 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1132 if (result != ERROR_OK)
1138 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
1140 struct stlink_usb_handle_s *h = handle;
1142 assert(handle != NULL);
1144 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
1145 return ERROR_COMMAND_NOTFOUND;
1147 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1149 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1150 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
1151 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1154 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1156 if (result != ERROR_OK)
1163 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
1166 struct stlink_usb_handle_s *h = handle;
1168 assert(handle != NULL);
1170 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1172 h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
1174 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1176 if (res != ERROR_OK)
1179 *mode = h->databuf[0];
1185 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
1188 struct stlink_usb_handle_s *h = handle;
1190 assert(handle != NULL);
1192 /* on api V2 we are able the read the latest command
1194 * TODO: we need the test on api V1 too
1196 if (h->version.jtag_api != STLINK_JTAG_API_V1)
1199 stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
1202 case STLINK_MODE_DEBUG_JTAG:
1203 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1204 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1205 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1207 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1208 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG_NO_RESET;
1210 case STLINK_MODE_DEBUG_SWD:
1211 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1212 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1213 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1215 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1216 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD_NO_RESET;
1218 case STLINK_MODE_DEBUG_SWIM:
1219 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1220 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
1221 /* no answer for this function... */
1224 case STLINK_MODE_DFU:
1225 case STLINK_MODE_MASS:
1230 return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
1234 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
1237 struct stlink_usb_handle_s *h = handle;
1239 assert(handle != NULL);
1241 stlink_usb_init_buffer(handle, STLINK_NULL_EP, 0);
1244 case STLINK_MODE_DEBUG_JTAG:
1245 case STLINK_MODE_DEBUG_SWD:
1246 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1247 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
1249 case STLINK_MODE_DEBUG_SWIM:
1250 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1251 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
1253 case STLINK_MODE_DFU:
1254 h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
1255 h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
1257 case STLINK_MODE_MASS:
1262 res = stlink_usb_xfer_noerrcheck(handle, 0, 0);
1264 if (res != ERROR_OK)
1270 static int stlink_usb_assert_srst(void *handle, int srst);
1272 static enum stlink_mode stlink_get_mode(enum hl_transports t)
1275 case HL_TRANSPORT_SWD:
1276 return STLINK_MODE_DEBUG_SWD;
1277 case HL_TRANSPORT_JTAG:
1278 return STLINK_MODE_DEBUG_JTAG;
1279 case HL_TRANSPORT_SWIM:
1280 return STLINK_MODE_DEBUG_SWIM;
1282 return STLINK_MODE_UNKNOWN;
1287 static int stlink_usb_init_mode(void *handle, bool connect_under_reset, int initial_interface_speed)
1291 enum stlink_mode emode;
1292 struct stlink_usb_handle_s *h = handle;
1294 assert(handle != NULL);
1296 res = stlink_usb_current_mode(handle, &mode);
1298 if (res != ERROR_OK)
1301 LOG_DEBUG("MODE: 0x%02X", mode);
1303 /* try to exit current mode */
1305 case STLINK_DEV_DFU_MODE:
1306 emode = STLINK_MODE_DFU;
1308 case STLINK_DEV_DEBUG_MODE:
1309 emode = STLINK_MODE_DEBUG_SWD;
1311 case STLINK_DEV_SWIM_MODE:
1312 emode = STLINK_MODE_DEBUG_SWIM;
1314 case STLINK_DEV_BOOTLOADER_MODE:
1315 case STLINK_DEV_MASS_MODE:
1317 emode = STLINK_MODE_UNKNOWN;
1321 if (emode != STLINK_MODE_UNKNOWN) {
1322 res = stlink_usb_mode_leave(handle, emode);
1324 if (res != ERROR_OK)
1328 res = stlink_usb_current_mode(handle, &mode);
1330 if (res != ERROR_OK)
1333 /* we check the target voltage here as an aid to debugging connection problems.
1334 * the stlink requires the target Vdd to be connected for reliable debugging.
1335 * this cmd is supported in all modes except DFU
1337 if (mode != STLINK_DEV_DFU_MODE) {
1339 float target_voltage;
1341 /* check target voltage (if supported) */
1342 res = stlink_usb_check_voltage(h, &target_voltage);
1344 if (res != ERROR_OK) {
1345 if (res != ERROR_COMMAND_NOTFOUND)
1346 LOG_ERROR("voltage check failed");
1347 /* attempt to continue as it is not a catastrophic failure */
1349 /* check for a sensible target voltage, operating range is 1.65-5.5v
1350 * according to datasheet */
1351 if (target_voltage < 1.5)
1352 LOG_ERROR("target voltage may be too low for reliable debugging");
1356 LOG_DEBUG("MODE: 0x%02X", mode);
1358 /* set selected mode */
1359 emode = stlink_get_mode(h->transport);
1361 if (emode == STLINK_MODE_UNKNOWN) {
1362 LOG_ERROR("selected mode (transport) not supported");
1366 /* set the speed before entering the mode, as the chip discovery phase should be done at this speed too */
1367 if (h->transport == HL_TRANSPORT_JTAG) {
1368 if (h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ) {
1369 stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
1370 stlink_speed(h, initial_interface_speed, false);
1372 } else if (h->transport == HL_TRANSPORT_SWD) {
1373 if (h->version.flags & STLINK_F_HAS_SWD_SET_FREQ) {
1374 stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
1375 stlink_speed(h, initial_interface_speed, false);
1379 if (h->version.jtag_api == STLINK_JTAG_API_V3) {
1380 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
1382 stlink_get_com_freq(h, (h->transport == HL_TRANSPORT_JTAG), map);
1383 stlink_dump_speed_map(map, ARRAY_SIZE(map));
1384 stlink_speed(h, initial_interface_speed, false);
1387 /* preliminary SRST assert:
1388 * We want SRST is asserted before activating debug signals (mode_enter).
1389 * As the required mode has not been set, the adapter may not know what pin to use.
1390 * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
1391 * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
1392 * after power on, SWIM_RST stays unchanged */
1393 if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
1394 stlink_usb_assert_srst(handle, 0);
1395 /* do not check the return status here, we will
1396 proceed and enter the desired mode below
1397 and try asserting srst again. */
1399 res = stlink_usb_mode_enter(handle, emode);
1400 if (res != ERROR_OK)
1403 /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
1404 if (connect_under_reset) {
1405 res = stlink_usb_assert_srst(handle, 0);
1406 if (res != ERROR_OK)
1410 res = stlink_usb_current_mode(handle, &mode);
1412 if (res != ERROR_OK)
1415 LOG_DEBUG("MODE: 0x%02X", mode);
1420 /* request status from last swim request */
1421 static int stlink_swim_status(void *handle)
1423 struct stlink_usb_handle_s *h = handle;
1426 stlink_usb_init_buffer(handle, h->rx_ep, 4);
1427 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1428 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
1429 /* error is checked by the caller */
1430 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1431 if (res != ERROR_OK)
1436 the purpose of this function is unknown...
1437 capabilites? anyway for swim v6 it returns
1440 __attribute__((unused))
1441 static int stlink_swim_cap(void *handle, uint8_t *cap)
1443 struct stlink_usb_handle_s *h = handle;
1446 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1447 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1448 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1449 h->cmdbuf[h->cmdidx++] = 0x01;
1450 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1451 if (res != ERROR_OK)
1453 memcpy(cap, h->databuf, 8);
1457 /* debug dongle assert/deassert sreset line */
1458 static int stlink_swim_assert_reset(void *handle, int reset)
1460 struct stlink_usb_handle_s *h = handle;
1463 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1464 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1466 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1468 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1469 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1470 if (res != ERROR_OK)
1477 1.3ms low then 750Hz then 1.5kHz
1479 static int stlink_swim_enter(void *handle)
1481 struct stlink_usb_handle_s *h = handle;
1484 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1485 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1486 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1487 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1488 if (res != ERROR_OK)
1493 /* switch high/low speed swim */
1494 static int stlink_swim_speed(void *handle, int speed)
1496 struct stlink_usb_handle_s *h = handle;
1499 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1500 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1501 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1503 h->cmdbuf[h->cmdidx++] = 1;
1505 h->cmdbuf[h->cmdidx++] = 0;
1506 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1507 if (res != ERROR_OK)
1513 initiate srst from swim.
1514 nrst is pulled low for 50us.
1516 static int stlink_swim_generate_rst(void *handle)
1518 struct stlink_usb_handle_s *h = handle;
1521 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1522 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1523 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1524 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1525 if (res != ERROR_OK)
1531 send resyncronize sequence
1532 swim is pulled low for 16us
1533 reply is 64 clks low
1535 static int stlink_swim_resync(void *handle)
1537 struct stlink_usb_handle_s *h = handle;
1540 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1541 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1542 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_RESET;
1543 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1544 if (res != ERROR_OK)
1549 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1551 struct stlink_usb_handle_s *h = handle;
1554 unsigned int datalen = 0;
1555 int cmdsize = STLINK_CMD_SIZE_V2;
1557 if (len > STLINK_DATA_SIZE)
1560 if (h->version.stlink == 1)
1561 cmdsize = STLINK_SG_SIZE;
1563 stlink_usb_init_buffer(handle, h->tx_ep, 0);
1564 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1565 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1566 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1568 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1570 for (i = 0; i < len; i++) {
1571 if (h->cmdidx == cmdsize)
1572 h->databuf[datalen++] = *(data++);
1574 h->cmdbuf[h->cmdidx++] = *(data++);
1576 if (h->version.stlink == 1)
1577 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1579 res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1580 if (res != ERROR_OK)
1585 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1587 struct stlink_usb_handle_s *h = handle;
1590 if (len > STLINK_DATA_SIZE)
1593 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1594 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1595 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1596 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1598 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1600 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1601 if (res != ERROR_OK)
1604 stlink_usb_init_buffer(handle, h->rx_ep, len);
1605 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1606 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1607 res = stlink_usb_xfer_noerrcheck(handle, data, len);
1608 if (res != ERROR_OK)
1615 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1618 struct stlink_usb_handle_s *h = handle;
1620 assert(handle != NULL);
1622 /* there is no swim read core id cmd */
1623 if (h->transport == HL_TRANSPORT_SWIM) {
1628 stlink_usb_init_buffer(handle, h->rx_ep, 12);
1630 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1631 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1632 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1634 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1637 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_IDCODES;
1639 res = stlink_usb_xfer_errcheck(handle, h->databuf, 12);
1643 if (res != ERROR_OK)
1646 *idcode = le_to_h_u32(h->databuf + offset);
1648 LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1653 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1655 struct stlink_usb_handle_s *h = handle;
1658 assert(handle != NULL);
1660 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1662 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1663 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1664 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1667 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1668 if (res != ERROR_OK)
1671 *val = le_to_h_u32(h->databuf + 4);
1675 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1677 struct stlink_usb_handle_s *h = handle;
1679 assert(handle != NULL);
1681 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1683 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1684 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1685 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1687 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1688 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1690 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1693 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1697 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1699 struct stlink_usb_handle_s *h = handle;
1701 assert(handle != NULL);
1703 if (h->trace.enabled && (h->version.flags & STLINK_F_HAS_TRACE)) {
1706 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1708 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1709 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1711 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1712 if (res != ERROR_OK)
1715 size_t bytes_avail = le_to_h_u16(h->databuf);
1716 *size = bytes_avail < *size ? bytes_avail : *size - 1;
1719 res = stlink_usb_read_trace(handle, buf, *size);
1720 if (res != ERROR_OK)
1729 static enum target_state stlink_usb_v2_get_status(void *handle)
1734 result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1735 if (result != ERROR_OK)
1736 return TARGET_UNKNOWN;
1738 if (status & S_HALT)
1739 return TARGET_HALTED;
1740 else if (status & S_RESET_ST)
1741 return TARGET_RESET;
1743 return TARGET_RUNNING;
1747 static enum target_state stlink_usb_state(void *handle)
1750 struct stlink_usb_handle_s *h = handle;
1752 assert(handle != NULL);
1754 if (h->transport == HL_TRANSPORT_SWIM) {
1755 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1756 if (res != ERROR_OK)
1757 return TARGET_UNKNOWN;
1759 res = stlink_swim_resync(handle);
1760 if (res != ERROR_OK)
1761 return TARGET_UNKNOWN;
1766 if (h->reconnect_pending) {
1767 LOG_INFO("Previous state query failed, trying to reconnect");
1768 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1770 if (res != ERROR_OK)
1771 return TARGET_UNKNOWN;
1773 h->reconnect_pending = false;
1776 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1777 res = stlink_usb_v2_get_status(handle);
1778 if (res == TARGET_UNKNOWN)
1779 h->reconnect_pending = true;
1783 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1785 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1786 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
1788 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1790 if (res != ERROR_OK)
1791 return TARGET_UNKNOWN;
1793 if (h->databuf[0] == STLINK_CORE_RUNNING)
1794 return TARGET_RUNNING;
1795 if (h->databuf[0] == STLINK_CORE_HALTED)
1796 return TARGET_HALTED;
1798 h->reconnect_pending = true;
1800 return TARGET_UNKNOWN;
1803 static int stlink_usb_assert_srst(void *handle, int srst)
1805 struct stlink_usb_handle_s *h = handle;
1807 assert(handle != NULL);
1809 if (h->transport == HL_TRANSPORT_SWIM)
1810 return stlink_swim_assert_reset(handle, srst);
1812 if (h->version.stlink == 1)
1813 return ERROR_COMMAND_NOTFOUND;
1815 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1817 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1818 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
1819 h->cmdbuf[h->cmdidx++] = srst;
1821 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1825 static void stlink_usb_trace_disable(void *handle)
1828 struct stlink_usb_handle_s *h = handle;
1830 assert(handle != NULL);
1832 assert(h->version.flags & STLINK_F_HAS_TRACE);
1834 LOG_DEBUG("Tracing: disable");
1836 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1837 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1838 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
1839 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1841 if (res == ERROR_OK)
1842 h->trace.enabled = false;
1847 static int stlink_usb_trace_enable(void *handle)
1850 struct stlink_usb_handle_s *h = handle;
1852 assert(handle != NULL);
1854 if (h->version.flags & STLINK_F_HAS_TRACE) {
1855 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1857 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1858 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
1859 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
1861 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
1864 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1866 if (res == ERROR_OK) {
1867 h->trace.enabled = true;
1868 LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
1871 LOG_ERROR("Tracing is not supported by this version.");
1879 static int stlink_usb_reset(void *handle)
1881 struct stlink_usb_handle_s *h = handle;
1884 assert(handle != NULL);
1886 if (h->transport == HL_TRANSPORT_SWIM)
1887 return stlink_swim_generate_rst(handle);
1889 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1891 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1893 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1894 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
1896 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
1898 retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
1899 if (retval != ERROR_OK)
1902 if (h->trace.enabled) {
1903 stlink_usb_trace_disable(h);
1904 return stlink_usb_trace_enable(h);
1911 static int stlink_usb_run(void *handle)
1914 struct stlink_usb_handle_s *h = handle;
1916 assert(handle != NULL);
1918 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1919 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
1924 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1926 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1927 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
1929 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1933 static int stlink_usb_halt(void *handle)
1936 struct stlink_usb_handle_s *h = handle;
1938 assert(handle != NULL);
1940 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1941 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1946 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1948 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1949 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
1951 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1955 static int stlink_usb_step(void *handle)
1957 struct stlink_usb_handle_s *h = handle;
1959 assert(handle != NULL);
1961 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1962 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
1963 * that the Cortex-M3 currently does. */
1964 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
1965 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
1966 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1969 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1971 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1972 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
1974 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1978 static int stlink_usb_read_regs(void *handle)
1981 struct stlink_usb_handle_s *h = handle;
1983 assert(handle != NULL);
1985 stlink_usb_init_buffer(handle, h->rx_ep, 88);
1987 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1988 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1990 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
1991 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 84);
1992 /* regs data from offset 0 */
1994 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
1995 res = stlink_usb_xfer_errcheck(handle, h->databuf, 88);
1996 /* status at offset 0, regs data from offset 4 */
2003 static int stlink_usb_read_reg(void *handle, int num, uint32_t *val)
2006 struct stlink_usb_handle_s *h = handle;
2008 assert(handle != NULL);
2010 stlink_usb_init_buffer(handle, h->rx_ep, h->version.jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
2012 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2013 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2014 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
2016 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
2017 h->cmdbuf[h->cmdidx++] = num;
2019 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2020 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
2021 if (res != ERROR_OK)
2023 *val = le_to_h_u32(h->databuf);
2026 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
2027 if (res != ERROR_OK)
2029 *val = le_to_h_u32(h->databuf + 4);
2035 static int stlink_usb_write_reg(void *handle, int num, uint32_t val)
2037 struct stlink_usb_handle_s *h = handle;
2039 assert(handle != NULL);
2041 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2043 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2044 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2045 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
2047 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
2048 h->cmdbuf[h->cmdidx++] = num;
2049 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
2052 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2055 static int stlink_usb_get_rw_status(void *handle)
2057 struct stlink_usb_handle_s *h = handle;
2059 assert(handle != NULL);
2061 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2064 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2066 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2067 if (h->version.flags & STLINK_F_HAS_GETLASTRWSTATUS2) {
2068 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS2;
2069 return stlink_usb_xfer_errcheck(handle, h->databuf, 12);
2071 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
2072 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2077 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
2081 uint16_t read_len = len;
2082 struct stlink_usb_handle_s *h = handle;
2084 assert(handle != NULL);
2086 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2087 if (len > stlink_usb_block(h)) {
2088 LOG_DEBUG("max buffer (%d) length exceeded", stlink_usb_block(h));
2092 stlink_usb_init_buffer(handle, h->rx_ep, read_len);
2094 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2095 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
2096 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2098 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2101 /* we need to fix read length for single bytes */
2105 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, read_len);
2107 if (res != ERROR_OK)
2110 memcpy(buffer, h->databuf, len);
2112 return stlink_usb_get_rw_status(handle);
2116 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
2117 const uint8_t *buffer)
2120 struct stlink_usb_handle_s *h = handle;
2122 assert(handle != NULL);
2124 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2125 if (len > stlink_usb_block(h)) {
2126 LOG_DEBUG("max buffer length (%d) exceeded", stlink_usb_block(h));
2130 stlink_usb_init_buffer(handle, h->tx_ep, len);
2132 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2133 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
2134 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2136 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2139 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2141 if (res != ERROR_OK)
2144 return stlink_usb_get_rw_status(handle);
2148 static int stlink_usb_read_mem16(void *handle, uint32_t addr, uint16_t len,
2152 struct stlink_usb_handle_s *h = handle;
2154 assert(handle != NULL);
2156 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2157 return ERROR_COMMAND_NOTFOUND;
2159 /* data must be a multiple of 2 and half-word aligned */
2160 if (len % 2 || addr % 2) {
2161 LOG_DEBUG("Invalid data alignment");
2162 return ERROR_TARGET_UNALIGNED_ACCESS;
2165 stlink_usb_init_buffer(handle, h->rx_ep, len);
2167 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2168 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READMEM_16BIT;
2169 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2171 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2174 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2176 if (res != ERROR_OK)
2179 memcpy(buffer, h->databuf, len);
2181 return stlink_usb_get_rw_status(handle);
2185 static int stlink_usb_write_mem16(void *handle, uint32_t addr, uint16_t len,
2186 const uint8_t *buffer)
2189 struct stlink_usb_handle_s *h = handle;
2191 assert(handle != NULL);
2193 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2194 return ERROR_COMMAND_NOTFOUND;
2196 /* data must be a multiple of 2 and half-word aligned */
2197 if (len % 2 || addr % 2) {
2198 LOG_DEBUG("Invalid data alignment");
2199 return ERROR_TARGET_UNALIGNED_ACCESS;
2202 stlink_usb_init_buffer(handle, h->tx_ep, len);
2204 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2205 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEMEM_16BIT;
2206 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2208 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2211 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2213 if (res != ERROR_OK)
2216 return stlink_usb_get_rw_status(handle);
2220 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
2224 struct stlink_usb_handle_s *h = handle;
2226 assert(handle != NULL);
2228 /* data must be a multiple of 4 and word aligned */
2229 if (len % 4 || addr % 4) {
2230 LOG_DEBUG("Invalid data alignment");
2231 return ERROR_TARGET_UNALIGNED_ACCESS;
2234 stlink_usb_init_buffer(handle, h->rx_ep, len);
2236 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2237 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
2238 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2240 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2243 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2245 if (res != ERROR_OK)
2248 memcpy(buffer, h->databuf, len);
2250 return stlink_usb_get_rw_status(handle);
2254 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
2255 const uint8_t *buffer)
2258 struct stlink_usb_handle_s *h = handle;
2260 assert(handle != NULL);
2262 /* data must be a multiple of 4 and word aligned */
2263 if (len % 4 || addr % 4) {
2264 LOG_DEBUG("Invalid data alignment");
2265 return ERROR_TARGET_UNALIGNED_ACCESS;
2268 stlink_usb_init_buffer(handle, h->tx_ep, len);
2270 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2271 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
2272 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2274 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2277 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2279 if (res != ERROR_OK)
2282 return stlink_usb_get_rw_status(handle);
2285 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
2287 uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
2288 if (max_tar_block == 0)
2290 return max_tar_block;
2293 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
2294 uint32_t count, uint8_t *buffer)
2296 int retval = ERROR_OK;
2297 uint32_t bytes_remaining;
2299 struct stlink_usb_handle_s *h = handle;
2301 /* calculate byte count */
2304 /* switch to 8 bit if stlink does not support 16 bit memory read */
2305 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2310 bytes_remaining = (size != 1) ? \
2311 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2313 if (count < bytes_remaining)
2314 bytes_remaining = count;
2316 if (h->transport == HL_TRANSPORT_SWIM) {
2317 retval = stlink_swim_readbytes(handle, addr, bytes_remaining, buffer);
2318 if (retval != ERROR_OK)
2322 * all stlink support 8/32bit memory read/writes and only from
2323 * stlink V2J26 there is support for 16 bit memory read/write.
2324 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2329 /* When in jtag mode the stlink uses the auto-increment functionality.
2330 * However it expects us to pass the data correctly, this includes
2331 * alignment and any page boundaries. We already do this as part of the
2332 * adi_v5 implementation, but the stlink is a hla adapter and so this
2333 * needs implementing manually.
2334 * currently this only affects jtag mode, according to ST they do single
2335 * access in SWD mode - but this may change and so we do it for both modes */
2337 /* we first need to check for any unaligned bytes */
2338 if (addr & (size - 1)) {
2340 uint32_t head_bytes = size - (addr & (size - 1));
2341 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
2342 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2343 usleep((1<<retries++) * 1000);
2346 if (retval != ERROR_OK)
2348 buffer += head_bytes;
2350 count -= head_bytes;
2351 bytes_remaining -= head_bytes;
2354 if (bytes_remaining & (size - 1))
2355 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
2357 retval = stlink_usb_read_mem16(handle, addr, bytes_remaining, buffer);
2359 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
2361 retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
2363 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2364 usleep((1<<retries++) * 1000);
2367 if (retval != ERROR_OK)
2370 buffer += bytes_remaining;
2371 addr += bytes_remaining;
2372 count -= bytes_remaining;
2378 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
2379 uint32_t count, const uint8_t *buffer)
2381 int retval = ERROR_OK;
2382 uint32_t bytes_remaining;
2384 struct stlink_usb_handle_s *h = handle;
2386 /* calculate byte count */
2389 /* switch to 8 bit if stlink does not support 16 bit memory read */
2390 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2395 bytes_remaining = (size != 1) ? \
2396 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2398 if (count < bytes_remaining)
2399 bytes_remaining = count;
2401 if (h->transport == HL_TRANSPORT_SWIM) {
2402 retval = stlink_swim_writebytes(handle, addr, bytes_remaining, buffer);
2403 if (retval != ERROR_OK)
2407 * all stlink support 8/32bit memory read/writes and only from
2408 * stlink V2J26 there is support for 16 bit memory read/write.
2409 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2414 /* When in jtag mode the stlink uses the auto-increment functionality.
2415 * However it expects us to pass the data correctly, this includes
2416 * alignment and any page boundaries. We already do this as part of the
2417 * adi_v5 implementation, but the stlink is a hla adapter and so this
2418 * needs implementing manually.
2419 * currently this only affects jtag mode, according to ST they do single
2420 * access in SWD mode - but this may change and so we do it for both modes */
2422 /* we first need to check for any unaligned bytes */
2423 if (addr & (size - 1)) {
2425 uint32_t head_bytes = size - (addr & (size - 1));
2426 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
2427 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2428 usleep((1<<retries++) * 1000);
2431 if (retval != ERROR_OK)
2433 buffer += head_bytes;
2435 count -= head_bytes;
2436 bytes_remaining -= head_bytes;
2439 if (bytes_remaining & (size - 1))
2440 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
2442 retval = stlink_usb_write_mem16(handle, addr, bytes_remaining, buffer);
2444 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
2447 retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
2448 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2449 usleep((1<<retries++) * 1000);
2452 if (retval != ERROR_OK)
2455 buffer += bytes_remaining;
2456 addr += bytes_remaining;
2457 count -= bytes_remaining;
2464 static int stlink_usb_override_target(const char *targetname)
2466 return !strcmp(targetname, "cortex_m");
2469 static int stlink_speed_swim(void *handle, int khz, bool query)
2472 we dont care what the khz rate is
2473 we only have low and high speed...
2474 before changing speed the SWIM_CSR HS bit
2478 stlink_swim_speed(handle, 0);
2480 stlink_swim_speed(handle, 1);
2484 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
2487 int speed_index = -1;
2488 int speed_diff = INT_MAX;
2489 int last_valid_speed = -1;
2492 for (i = 0; i < map_size; i++) {
2495 last_valid_speed = i;
2496 if (khz == map[i].speed) {
2500 int current_diff = khz - map[i].speed;
2501 /* get abs value for comparison */
2502 current_diff = (current_diff > 0) ? current_diff : -current_diff;
2503 if ((current_diff < speed_diff) && khz >= map[i].speed) {
2504 speed_diff = current_diff;
2510 if (speed_index == -1) {
2511 /* this will only be here if we cannot match the slow speed.
2512 * use the slowest speed we support.*/
2513 speed_index = last_valid_speed;
2515 } else if (i == map_size)
2518 if (!match && query) {
2519 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz", \
2520 khz, map[speed_index].speed);
2526 static int stlink_speed_swd(void *handle, int khz, bool query)
2529 struct stlink_usb_handle_s *h = handle;
2531 /* old firmware cannot change it */
2532 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
2535 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
2536 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
2539 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
2540 if (result != ERROR_OK) {
2541 LOG_ERROR("Unable to set adapter speed");
2546 return stlink_khz_to_speed_map_swd[speed_index].speed;
2549 static int stlink_speed_jtag(void *handle, int khz, bool query)
2552 struct stlink_usb_handle_s *h = handle;
2554 /* old firmware cannot change it */
2555 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
2558 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2559 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2562 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2563 if (result != ERROR_OK) {
2564 LOG_ERROR("Unable to set adapter speed");
2569 return stlink_khz_to_speed_map_jtag[speed_index].speed;
2572 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2576 LOG_DEBUG("Supported clock speeds are:");
2577 for (i = 0; i < map_size; i++)
2579 LOG_DEBUG("%d kHz", map[i].speed);
2582 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map)
2584 struct stlink_usb_handle_s *h = handle;
2587 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2588 LOG_ERROR("Unknown command");
2592 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2594 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2595 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_COM_FREQ;
2596 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2598 int res = stlink_usb_xfer_errcheck(handle, h->databuf, 52);
2600 int size = h->databuf[8];
2602 if (size > STLINK_V3_MAX_FREQ_NB)
2603 size = STLINK_V3_MAX_FREQ_NB;
2605 for (i = 0; i < size; i++) {
2606 map[i].speed = le_to_h_u32(&h->databuf[12 + 4 * i]);
2607 map[i].speed_divisor = i;
2610 /* set to zero all the next entries */
2611 for (i = size; i < STLINK_V3_MAX_FREQ_NB; i++)
2617 static int stlink_set_com_freq(void *handle, bool is_jtag, unsigned int frequency)
2619 struct stlink_usb_handle_s *h = handle;
2621 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2622 LOG_ERROR("Unknown command");
2626 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2628 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2629 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_SET_COM_FREQ;
2630 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2631 h->cmdbuf[h->cmdidx++] = 0;
2633 h_u32_to_le(&h->cmdbuf[4], frequency);
2635 return stlink_usb_xfer_errcheck(handle, h->databuf, 8);
2638 static int stlink_speed_v3(void *handle, bool is_jtag, int khz, bool query)
2640 struct stlink_usb_handle_s *h = handle;
2642 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
2644 stlink_get_com_freq(h, is_jtag, map);
2646 speed_index = stlink_match_speed_map(map, ARRAY_SIZE(map), khz, query);
2649 int result = stlink_set_com_freq(h, is_jtag, map[speed_index].speed);
2650 if (result != ERROR_OK) {
2651 LOG_ERROR("Unable to set adapter speed");
2655 return map[speed_index].speed;
2658 static int stlink_speed(void *handle, int khz, bool query)
2660 struct stlink_usb_handle_s *h = handle;
2665 switch (h->transport) {
2666 case HL_TRANSPORT_SWIM:
2667 return stlink_speed_swim(handle, khz, query);
2669 case HL_TRANSPORT_SWD:
2670 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2671 return stlink_speed_v3(handle, false, khz, query);
2673 return stlink_speed_swd(handle, khz, query);
2675 case HL_TRANSPORT_JTAG:
2676 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2677 return stlink_speed_v3(handle, true, khz, query);
2679 return stlink_speed_jtag(handle, khz, query);
2689 static int stlink_usb_close(void *handle)
2693 enum stlink_mode emode;
2694 struct stlink_usb_handle_s *h = handle;
2697 res = stlink_usb_current_mode(handle, &mode);
2700 /* do not exit if return code != ERROR_OK,
2701 it prevents us from closing jtag_libusb */
2703 if (res == ERROR_OK) {
2704 /* try to exit current mode */
2706 case STLINK_DEV_DFU_MODE:
2707 emode = STLINK_MODE_DFU;
2709 case STLINK_DEV_DEBUG_MODE:
2710 emode = STLINK_MODE_DEBUG_SWD;
2712 case STLINK_DEV_SWIM_MODE:
2713 emode = STLINK_MODE_DEBUG_SWIM;
2715 case STLINK_DEV_BOOTLOADER_MODE:
2716 case STLINK_DEV_MASS_MODE:
2718 emode = STLINK_MODE_UNKNOWN;
2722 if (emode != STLINK_MODE_UNKNOWN)
2723 stlink_usb_mode_leave(handle, emode);
2724 /* do not check return code, it prevent
2725 us from closing jtag_libusb */
2729 jtag_libusb_close(h->fd);
2737 static int stlink_usb_open(struct hl_interface_param_s *param, void **fd)
2739 int err, retry_count = 1;
2740 struct stlink_usb_handle_s *h;
2742 LOG_DEBUG("stlink_usb_open");
2744 h = calloc(1, sizeof(struct stlink_usb_handle_s));
2747 LOG_DEBUG("malloc failed");
2751 h->transport = param->transport;
2753 for (unsigned i = 0; param->vid[i]; i++) {
2754 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
2755 param->transport, param->vid[i], param->pid[i],
2756 param->serial ? param->serial : "");
2760 On certain host USB configurations(e.g. MacBook Air)
2761 STLINKv2 dongle seems to have its FW in a funky state if,
2762 after plugging it in, you try to use openocd with it more
2763 then once (by launching and closing openocd). In cases like
2764 that initial attempt to read the FW info via
2765 stlink_usb_version will fail and the device has to be reset
2766 in order to become operational.
2769 if (jtag_libusb_open(param->vid, param->pid, param->serial, &h->fd) != ERROR_OK) {
2770 LOG_ERROR("open failed");
2774 jtag_libusb_set_configuration(h->fd, 0);
2776 if (jtag_libusb_claim_interface(h->fd, 0) != ERROR_OK) {
2777 LOG_DEBUG("claim interface failed");
2781 /* RX EP is common for all versions */
2782 h->rx_ep = STLINK_RX_EP;
2785 if (jtag_libusb_get_pid(jtag_libusb_get_device(h->fd), &pid) != ERROR_OK) {
2786 LOG_DEBUG("libusb_get_pid failed");
2790 /* wrap version for first read */
2793 h->version.stlink = 1;
2794 h->tx_ep = STLINK_TX_EP;
2796 case STLINK_V3_USBLOADER_PID:
2797 case STLINK_V3E_PID:
2798 case STLINK_V3S_PID:
2799 case STLINK_V3_2VCP_PID:
2800 h->version.stlink = 3;
2801 h->tx_ep = STLINK_V2_1_TX_EP;
2802 h->trace_ep = STLINK_V2_1_TRACE_EP;
2804 case STLINK_V2_1_PID:
2805 case STLINK_V2_1_NO_MSD_PID:
2806 h->version.stlink = 2;
2807 h->tx_ep = STLINK_V2_1_TX_EP;
2808 h->trace_ep = STLINK_V2_1_TRACE_EP;
2811 /* fall through - we assume V2 to be the default version*/
2813 h->version.stlink = 2;
2814 h->tx_ep = STLINK_TX_EP;
2815 h->trace_ep = STLINK_TRACE_EP;
2819 /* get the device version */
2820 err = stlink_usb_version(h);
2822 if (err == ERROR_OK) {
2824 } else if (h->version.stlink == 1 ||
2826 LOG_ERROR("read version failed");
2829 err = jtag_libusb_release_interface(h->fd, 0);
2830 if (err != ERROR_OK) {
2831 LOG_ERROR("release interface failed");
2835 err = jtag_libusb_reset_device(h->fd);
2836 if (err != ERROR_OK) {
2837 LOG_ERROR("reset device failed");
2841 jtag_libusb_close(h->fd);
2843 Give the device one second to settle down and
2846 usleep(1 * 1000 * 1000);
2851 /* check if mode is supported */
2854 switch (h->transport) {
2855 case HL_TRANSPORT_SWD:
2856 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2859 case HL_TRANSPORT_JTAG:
2860 if (h->version.jtag == 0)
2863 case HL_TRANSPORT_SWIM:
2864 if (h->version.swim == 0)
2872 if (err != ERROR_OK) {
2873 LOG_ERROR("mode (transport) not supported by device");
2877 /* initialize the debug hardware */
2878 err = stlink_usb_init_mode(h, param->connect_under_reset, param->initial_interface_speed);
2880 if (err != ERROR_OK) {
2881 LOG_ERROR("init mode failed (unable to connect to the target)");
2885 if (h->transport == HL_TRANSPORT_SWIM) {
2886 err = stlink_swim_enter(h);
2887 if (err != ERROR_OK) {
2888 LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
2892 h->max_mem_packet = STLINK_DATA_SIZE;
2896 /* get cpuid, so we can determine the max page size
2897 * start with a safe default */
2898 h->max_mem_packet = (1 << 10);
2901 err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
2902 if (err == ERROR_OK) {
2903 uint32_t cpuid = le_to_h_u32(buffer);
2904 int i = (cpuid >> 4) & 0xf;
2905 if (i == 4 || i == 3) {
2906 /* Cortex-M3/M4 has 4096 bytes autoincrement range */
2907 h->max_mem_packet = (1 << 12);
2911 LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
2918 stlink_usb_close(h);
2923 int stlink_config_trace(void *handle, bool enabled,
2924 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
2925 unsigned int *trace_freq, unsigned int traceclkin_freq,
2926 uint16_t *prescaler)
2928 struct stlink_usb_handle_s *h = handle;
2931 if (enabled && (!(h->version.flags & STLINK_F_HAS_TRACE) ||
2932 pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART)) {
2933 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
2938 stlink_usb_trace_disable(h);
2942 if (*trace_freq > STLINK_TRACE_MAX_HZ) {
2943 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
2944 STLINK_TRACE_MAX_HZ);
2948 stlink_usb_trace_disable(h);
2951 *trace_freq = STLINK_TRACE_MAX_HZ;
2953 presc = traceclkin_freq / *trace_freq;
2955 if (traceclkin_freq % *trace_freq > 0)
2958 if (presc > TPIU_ACPR_MAX_SWOSCALER) {
2959 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
2965 h->trace.source_hz = *trace_freq;
2967 return stlink_usb_trace_enable(h);
2971 static int stlink_usb_init_access_port(void *handle, unsigned char ap_num)
2973 struct stlink_usb_handle_s *h = handle;
2975 assert(handle != NULL);
2977 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
2978 return ERROR_COMMAND_NOTFOUND;
2980 LOG_DEBUG_IO("init ap_num = %d", ap_num);
2981 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2982 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2983 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_INIT_AP;
2984 h->cmdbuf[h->cmdidx++] = ap_num;
2986 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2990 static int stlink_usb_close_access_port(void *handle, unsigned char ap_num)
2992 struct stlink_usb_handle_s *h = handle;
2994 assert(handle != NULL);
2996 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
2997 return ERROR_COMMAND_NOTFOUND;
2999 LOG_DEBUG_IO("close ap_num = %d", ap_num);
3000 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3001 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3002 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_CLOSE_AP_DBG;
3003 h->cmdbuf[h->cmdidx++] = ap_num;
3005 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3009 static int stlink_read_dap_register(void *handle, unsigned short dap_port,
3010 unsigned short addr, uint32_t *val)
3012 struct stlink_usb_handle_s *h = handle;
3015 assert(handle != NULL);
3017 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3018 return ERROR_COMMAND_NOTFOUND;
3020 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3021 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3022 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_DAP_REG;
3023 h_u16_to_le(&h->cmdbuf[2], dap_port);
3024 h_u16_to_le(&h->cmdbuf[4], addr);
3026 retval = stlink_usb_xfer_errcheck(handle, h->databuf, 8);
3027 *val = le_to_h_u32(h->databuf + 4);
3028 LOG_DEBUG_IO("dap_port_read = %d, addr = 0x%x, value = 0x%x", dap_port, addr, *val);
3033 static int stlink_write_dap_register(void *handle, unsigned short dap_port,
3034 unsigned short addr, uint32_t val)
3036 struct stlink_usb_handle_s *h = handle;
3038 assert(handle != NULL);
3040 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3041 return ERROR_COMMAND_NOTFOUND;
3043 LOG_DEBUG_IO("dap_write port = %d, addr = 0x%x, value = 0x%x", dap_port, addr, val);
3044 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3045 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3046 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITE_DAP_REG;
3047 h_u16_to_le(&h->cmdbuf[2], dap_port);
3048 h_u16_to_le(&h->cmdbuf[4], addr);
3049 h_u32_to_le(&h->cmdbuf[6], val);
3050 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3054 struct hl_layout_api_s stlink_usb_layout_api = {
3056 .open = stlink_usb_open,
3058 .close = stlink_usb_close,
3060 .idcode = stlink_usb_idcode,
3062 .state = stlink_usb_state,
3064 .reset = stlink_usb_reset,
3066 .assert_srst = stlink_usb_assert_srst,
3068 .run = stlink_usb_run,
3070 .halt = stlink_usb_halt,
3072 .step = stlink_usb_step,
3074 .read_regs = stlink_usb_read_regs,
3076 .read_reg = stlink_usb_read_reg,
3078 .write_reg = stlink_usb_write_reg,
3080 .read_mem = stlink_usb_read_mem,
3082 .write_mem = stlink_usb_write_mem,
3084 .write_debug_reg = stlink_usb_write_debug_reg,
3086 .override_target = stlink_usb_override_target,
3088 .speed = stlink_speed,
3090 .config_trace = stlink_config_trace,
3092 .poll_trace = stlink_usb_trace_read,
3095 /*****************************************************************************
3096 * DAP direct interface
3099 static struct stlink_usb_handle_s *stlink_dap_handle;
3100 static struct hl_interface_param_s stlink_dap_param;
3101 static DECLARE_BITMAP(opened_ap, DP_APSEL_MAX + 1);
3102 static int stlink_dap_error = ERROR_OK;
3104 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3108 static int stlink_dap_record_error(int error)
3110 if (stlink_dap_error == ERROR_OK)
3111 stlink_dap_error = error;
3116 static int stlink_dap_get_and_clear_error(void)
3118 int retval = stlink_dap_error;
3119 stlink_dap_error = ERROR_OK;
3124 static int stlink_dap_open_ap(unsigned short apsel)
3128 /* nothing to do on old versions */
3129 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3132 if (apsel > DP_APSEL_MAX)
3135 if (test_bit(apsel, opened_ap))
3138 retval = stlink_usb_init_access_port(stlink_dap_handle, apsel);
3139 if (retval != ERROR_OK)
3142 LOG_DEBUG("AP %d enabled", apsel);
3143 set_bit(apsel, opened_ap);
3148 static int stlink_dap_closeall_ap(void)
3152 /* nothing to do on old versions */
3153 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3156 for (apsel = 0; apsel <= DP_APSEL_MAX; apsel++) {
3157 if (!test_bit(apsel, opened_ap))
3159 retval = stlink_usb_close_access_port(stlink_dap_handle, apsel);
3160 if (retval != ERROR_OK)
3162 clear_bit(apsel, opened_ap);
3168 static int stlink_dap_reinit_interface(void)
3171 enum stlink_mode mode;
3174 * On JTAG only, it should be enough to call stlink_usb_reset(). But on
3175 * some firmware version it does not work as expected, and there is no
3176 * equivalent for SWD.
3177 * At least for now, to reset the interface quit from JTAG/SWD mode then
3178 * select the mode again.
3181 mode = stlink_get_mode(stlink_dap_param.transport);
3182 if (!stlink_dap_handle->reconnect_pending) {
3183 stlink_dap_handle->reconnect_pending = true;
3184 stlink_usb_mode_leave(stlink_dap_handle, mode);
3187 retval = stlink_usb_mode_enter(stlink_dap_handle, mode);
3188 if (retval != ERROR_OK)
3191 stlink_dap_handle->reconnect_pending = false;
3192 /* on new FW, calling mode-leave closes all the opened AP; reopen them! */
3193 if (stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT)
3194 for (int apsel = 0; apsel <= DP_APSEL_MAX; apsel++)
3195 if (test_bit(apsel, opened_ap)) {
3196 clear_bit(apsel, opened_ap);
3197 stlink_dap_open_ap(apsel);
3203 static int stlink_dap_op_connect(struct adiv5_dap *dap)
3208 LOG_INFO("stlink_dap_op_connect(%sconnect)", dap->do_reconnect ? "re" : "");
3210 /* Check if we should reset srst already when connecting, but not if reconnecting. */
3211 if (!dap->do_reconnect) {
3212 enum reset_types jtag_reset_config = jtag_get_reset_config();
3214 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3215 if (jtag_reset_config & RESET_SRST_NO_GATING)
3216 adapter_assert_reset();
3218 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3222 dap->do_reconnect = false;
3223 dap_invalidate_cache(dap);
3225 retval = dap_dp_init(dap);
3226 if (retval != ERROR_OK) {
3227 dap->do_reconnect = true;
3231 retval = stlink_usb_idcode(stlink_dap_handle, &idcode);
3232 if (retval == ERROR_OK)
3233 LOG_INFO("%s %#8.8" PRIx32,
3234 (stlink_dap_handle->transport == HL_TRANSPORT_JTAG) ? "JTAG IDCODE" : "SWD DPIDR",
3237 dap->do_reconnect = true;
3243 static int stlink_dap_check_reconnect(struct adiv5_dap *dap)
3247 if (!dap->do_reconnect)
3250 retval = stlink_dap_reinit_interface();
3251 if (retval != ERROR_OK)
3254 return stlink_dap_op_connect(dap);
3258 static int stlink_dap_op_send_sequence(struct adiv5_dap *dap, enum swd_special_seq seq)
3260 /* Ignore the request */
3265 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3271 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3272 if (reg & 0x000000F0) {
3273 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3274 return ERROR_COMMAND_NOTFOUND;
3277 retval = stlink_dap_check_reconnect(dap);
3278 if (retval != ERROR_OK)
3281 data = data ? : &dummy;
3282 if (stlink_dap_handle->version.flags & STLINK_F_QUIRK_JTAG_DP_READ
3283 && stlink_dap_handle->transport == HL_TRANSPORT_JTAG) {
3284 /* Quirk required in JTAG. Read RDBUFF to get the data */
3285 retval = stlink_read_dap_register(stlink_dap_handle,
3286 STLINK_DEBUG_PORT_ACCESS, reg, &dummy);
3287 if (retval == ERROR_OK)
3288 retval = stlink_read_dap_register(stlink_dap_handle,
3289 STLINK_DEBUG_PORT_ACCESS, DP_RDBUFF, data);
3291 retval = stlink_read_dap_register(stlink_dap_handle,
3292 STLINK_DEBUG_PORT_ACCESS, reg, data);
3295 return stlink_dap_record_error(retval);
3299 static int stlink_dap_op_queue_dp_write(struct adiv5_dap *dap, unsigned reg,
3304 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3305 if (reg & 0x000000F0) {
3306 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3307 return ERROR_COMMAND_NOTFOUND;
3310 if (reg == DP_SELECT && (data & DP_SELECT_DPBANK) != 0) {
3311 /* ignored if STLINK_F_HAS_DPBANKSEL, not properly managed otherwise */
3312 LOG_DEBUG("Ignoring DPBANKSEL while write SELECT");
3313 data &= ~DP_SELECT_DPBANK;
3316 retval = stlink_dap_check_reconnect(dap);
3317 if (retval != ERROR_OK)
3320 /* ST-Link does not like that we set CORUNDETECT */
3321 if (reg == DP_CTRL_STAT)
3322 data &= ~CORUNDETECT;
3324 retval = stlink_write_dap_register(stlink_dap_handle,
3325 STLINK_DEBUG_PORT_ACCESS, reg, data);
3326 return stlink_dap_record_error(retval);
3330 static int stlink_dap_op_queue_ap_read(struct adiv5_ap *ap, unsigned reg,
3333 struct adiv5_dap *dap = ap->dap;
3337 retval = stlink_dap_check_reconnect(dap);
3338 if (retval != ERROR_OK)
3341 if (reg != AP_REG_IDR) {
3342 retval = stlink_dap_open_ap(ap->ap_num);
3343 if (retval != ERROR_OK)
3346 data = data ? : &dummy;
3347 retval = stlink_read_dap_register(stlink_dap_handle, ap->ap_num, reg,
3349 dap->stlink_flush_ap_write = false;
3350 return stlink_dap_record_error(retval);
3354 static int stlink_dap_op_queue_ap_write(struct adiv5_ap *ap, unsigned reg,
3357 struct adiv5_dap *dap = ap->dap;
3360 retval = stlink_dap_check_reconnect(dap);
3361 if (retval != ERROR_OK)
3364 retval = stlink_dap_open_ap(ap->ap_num);
3365 if (retval != ERROR_OK)
3368 retval = stlink_write_dap_register(stlink_dap_handle, ap->ap_num, reg,
3370 dap->stlink_flush_ap_write = true;
3371 return stlink_dap_record_error(retval);
3375 static int stlink_dap_op_queue_ap_abort(struct adiv5_dap *dap, uint8_t *ack)
3377 LOG_WARNING("stlink_dap_op_queue_ap_abort()");
3382 static int stlink_dap_op_run(struct adiv5_dap *dap)
3384 uint32_t ctrlstat, pwrmask;
3385 int retval, saved_retval;
3387 /* Here no LOG_DEBUG. This is called continuously! */
3390 * ST-Link returns immediately after a DAP write, without waiting for it
3392 * Run a dummy read to DP_RDBUFF, as suggested in
3393 * http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka16363.html
3395 if (dap->stlink_flush_ap_write) {
3396 dap->stlink_flush_ap_write = false;
3397 retval = stlink_dap_op_queue_dp_read(dap, DP_RDBUFF, NULL);
3398 if (retval != ERROR_OK) {
3399 dap->do_reconnect = true;
3404 saved_retval = stlink_dap_get_and_clear_error();
3406 retval = stlink_dap_op_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
3407 if (retval != ERROR_OK) {
3408 dap->do_reconnect = true;
3411 retval = stlink_dap_get_and_clear_error();
3412 if (retval != ERROR_OK) {
3413 LOG_ERROR("Fail reading CTRL/STAT register. Force reconnect");
3414 dap->do_reconnect = true;
3418 if (ctrlstat & SSTICKYERR) {
3419 if (stlink_dap_param.transport == HL_TRANSPORT_JTAG)
3420 retval = stlink_dap_op_queue_dp_write(dap, DP_CTRL_STAT,
3421 ctrlstat & (dap->dp_ctrl_stat | SSTICKYERR));
3423 retval = stlink_dap_op_queue_dp_write(dap, DP_ABORT, STKERRCLR);
3424 if (retval != ERROR_OK) {
3425 dap->do_reconnect = true;
3428 retval = stlink_dap_get_and_clear_error();
3429 if (retval != ERROR_OK) {
3430 dap->do_reconnect = true;
3435 /* check for power lost */
3436 pwrmask = dap->dp_ctrl_stat & (CDBGPWRUPREQ | CSYSPWRUPREQ);
3437 if ((ctrlstat & pwrmask) != pwrmask)
3438 dap->do_reconnect = true;
3440 return saved_retval;
3444 static void stlink_dap_op_quit(struct adiv5_dap *dap)
3448 retval = stlink_dap_closeall_ap();
3449 if (retval != ERROR_OK)
3450 LOG_ERROR("Error closing APs");
3454 COMMAND_HANDLER(stlink_dap_serial_command)
3456 LOG_DEBUG("stlink_dap_serial_command");
3458 if (CMD_ARGC != 1) {
3459 LOG_ERROR("Expected exactly one argument for \"st-link serial <serial-number>\".");
3460 return ERROR_COMMAND_SYNTAX_ERROR;
3463 if (stlink_dap_param.serial) {
3464 LOG_WARNING("Command \"st-link serial\" already used. Replacing previous value");
3465 free((void *)stlink_dap_param.serial);
3468 stlink_dap_param.serial = strdup(CMD_ARGV[0]);
3473 COMMAND_HANDLER(stlink_dap_vid_pid)
3475 unsigned int i, max_usb_ids = HLA_MAX_USB_IDS;
3477 if (CMD_ARGC > max_usb_ids * 2) {
3478 LOG_WARNING("ignoring extra IDs in vid_pid "
3479 "(maximum is %d pairs)", max_usb_ids);
3480 CMD_ARGC = max_usb_ids * 2;
3482 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
3483 LOG_WARNING("incomplete vid_pid configuration directive");
3484 return ERROR_COMMAND_SYNTAX_ERROR;
3486 for (i = 0; i < CMD_ARGC; i += 2) {
3487 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], stlink_dap_param.vid[i / 2]);
3488 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], stlink_dap_param.pid[i / 2]);
3491 /* null termination */
3492 stlink_dap_param.vid[i / 2] = stlink_dap_param.pid[i / 2] = 0;
3498 static const struct command_registration stlink_dap_subcommand_handlers[] = {
3501 .handler = stlink_dap_serial_command,
3502 .mode = COMMAND_CONFIG,
3503 .help = "set the serial number of the adapter",
3504 .usage = "<serial_number>",
3508 .handler = stlink_dap_vid_pid,
3509 .mode = COMMAND_CONFIG,
3510 .help = "USB VID and PID of the adapter",
3511 .usage = "(vid pid)+",
3513 COMMAND_REGISTRATION_DONE
3517 static const struct command_registration stlink_dap_command_handlers[] = {
3520 .mode = COMMAND_ANY,
3521 .help = "perform st-link management",
3522 .chain = stlink_dap_subcommand_handlers,
3525 COMMAND_REGISTRATION_DONE
3529 static int stlink_dap_init(void)
3531 enum reset_types jtag_reset_config = jtag_get_reset_config();
3534 LOG_DEBUG("stlink_dap_init()");
3536 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3537 if (jtag_reset_config & RESET_SRST_NO_GATING)
3538 stlink_dap_param.connect_under_reset = true;
3540 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3543 if (transport_is_dapdirect_swd())
3544 stlink_dap_param.transport = HL_TRANSPORT_SWD;
3545 else if (transport_is_dapdirect_jtag())
3546 stlink_dap_param.transport = HL_TRANSPORT_JTAG;
3548 LOG_ERROR("Unsupported transport");
3552 retval = stlink_usb_open(&stlink_dap_param, (void **)&stlink_dap_handle);
3553 if (retval != ERROR_OK)
3556 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DAP_REG)) {
3557 LOG_ERROR("ST-Link version does not support DAP direct transport");
3564 static int stlink_dap_quit(void)
3566 LOG_DEBUG("stlink_dap_quit()");
3568 free((void *)stlink_dap_param.serial);
3569 stlink_dap_param.serial = NULL;
3571 return stlink_usb_close(stlink_dap_handle);
3575 static int stlink_dap_reset(int req_trst, int req_srst)
3577 LOG_DEBUG("stlink_dap_reset(%d)", req_srst);
3578 return stlink_usb_assert_srst(stlink_dap_handle,
3579 req_srst ? STLINK_DEBUG_APIV2_DRIVE_NRST_LOW
3580 : STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH);
3584 static int stlink_dap_speed(int speed)
3587 LOG_ERROR("RTCK not supported. Set nonzero adapter_khz.");
3588 return ERROR_JTAG_NOT_IMPLEMENTED;
3591 stlink_dap_param.initial_interface_speed = speed;
3592 stlink_speed(stlink_dap_handle, speed, false);
3597 static int stlink_dap_khz(int khz, int *jtag_speed)
3604 static int stlink_dap_speed_div(int speed, int *khz)
3610 static const struct dap_ops stlink_dap_ops = {
3611 .connect = stlink_dap_op_connect,
3612 .send_sequence = stlink_dap_op_send_sequence,
3613 .queue_dp_read = stlink_dap_op_queue_dp_read,
3614 .queue_dp_write = stlink_dap_op_queue_dp_write,
3615 .queue_ap_read = stlink_dap_op_queue_ap_read,
3616 .queue_ap_write = stlink_dap_op_queue_ap_write,
3617 .queue_ap_abort = stlink_dap_op_queue_ap_abort,
3618 .run = stlink_dap_op_run,
3619 .sync = NULL, /* optional */
3620 .quit = stlink_dap_op_quit, /* optional */
3623 static const char *const stlink_dap_transport[] = { "dapdirect_jtag", "dapdirect_swd", NULL };
3625 struct adapter_driver stlink_dap_adapter_driver = {
3627 .transports = stlink_dap_transport,
3628 .commands = stlink_dap_command_handlers,
3630 .init = stlink_dap_init,
3631 .quit = stlink_dap_quit,
3632 .reset = stlink_dap_reset,
3633 .speed = stlink_dap_speed,
3634 .khz = stlink_dap_khz,
3635 .speed_div = stlink_dap_speed_div,
3637 .dap_jtag_ops = &stlink_dap_ops,
3638 .dap_swd_ops = &stlink_dap_ops,