1 /***************************************************************************
2 * Copyright (C) 2020 by Tarek Bochkati *
3 * Tarek Bochkati <tarek.bouchkati@gmail.com> *
5 * SWIM contributions by Ake Rehnman *
6 * Copyright (C) 2017 Ake Rehnman *
7 * ake.rehnman(at)gmail.com *
9 * Copyright (C) 2011-2012 by Mathias Kuester *
10 * Mathias Kuester <kesmtp@freenet.de> *
12 * Copyright (C) 2012 by Spencer Oliver *
13 * spen@spen-soft.co.uk *
15 * This code is based on https://github.com/texane/stlink *
17 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
29 ***************************************************************************/
35 /* project specific includes */
36 #include <helper/binarybuffer.h>
37 #include <helper/bits.h>
38 #include <helper/system.h>
39 #include <jtag/interface.h>
40 #include <jtag/hla/hla_layout.h>
41 #include <jtag/hla/hla_transport.h>
42 #include <jtag/hla/hla_interface.h>
43 #include <jtag/swim.h>
44 #include <target/arm_adi_v5.h>
45 #include <target/target.h>
46 #include <transport/transport.h>
48 #include <target/cortex_m.h>
50 #include <helper/system.h>
52 #ifdef HAVE_ARPA_INET_H
53 #include <arpa/inet.h>
56 #ifdef HAVE_NETINET_TCP_H
57 #include <netinet/tcp.h>
60 #include "libusb_helper.h"
63 #define USE_LIBUSB_ASYNCIO
66 #define STLINK_SERIAL_LEN 24
68 #define ENDPOINT_IN 0x80
69 #define ENDPOINT_OUT 0x00
71 #define STLINK_WRITE_TIMEOUT 1000
72 #define STLINK_READ_TIMEOUT 1000
74 #define STLINK_RX_EP (1|ENDPOINT_IN)
75 #define STLINK_TX_EP (2|ENDPOINT_OUT)
76 #define STLINK_TRACE_EP (3|ENDPOINT_IN)
78 #define STLINK_V2_1_TX_EP (1|ENDPOINT_OUT)
79 #define STLINK_V2_1_TRACE_EP (2|ENDPOINT_IN)
81 #define STLINK_SG_SIZE (31)
82 #define STLINK_DATA_SIZE (4096)
83 #define STLINK_CMD_SIZE_V2 (16)
84 #define STLINK_CMD_SIZE_V1 (10)
86 #define STLINK_V1_PID (0x3744)
87 #define STLINK_V2_PID (0x3748)
88 #define STLINK_V2_1_PID (0x374B)
89 #define STLINK_V2_1_NO_MSD_PID (0x3752)
90 #define STLINK_V3_USBLOADER_PID (0x374D)
91 #define STLINK_V3E_PID (0x374E)
92 #define STLINK_V3S_PID (0x374F)
93 #define STLINK_V3_2VCP_PID (0x3753)
94 #define STLINK_V3E_NO_MSD_PID (0x3754)
97 * ST-Link/V1, ST-Link/V2 and ST-Link/V2.1 are full-speed USB devices and
98 * this limits the bulk packet size and the 8bit read/writes to max 64 bytes.
99 * STLINK-V3 is a high speed USB 2.0 and the limit is 512 bytes from FW V3J6.
101 #define STLINK_MAX_RW8 (64)
102 #define STLINKV3_MAX_RW8 (512)
104 /* "WAIT" responses will be retried (with exponential backoff) at
105 * most this many times before failing to caller.
107 #define MAX_WAIT_RETRIES 8
109 enum stlink_jtag_api_version {
110 STLINK_JTAG_API_V1 = 1,
116 STLINK_MODE_UNKNOWN = 0,
119 STLINK_MODE_DEBUG_JTAG,
120 STLINK_MODE_DEBUG_SWD,
121 STLINK_MODE_DEBUG_SWIM
125 struct stlink_usb_version {
132 /** jtag api version supported */
133 enum stlink_jtag_api_version jtag_api;
134 /** one bit for each feature supported. See macros STLINK_F_* */
138 struct stlink_usb_priv_s {
140 struct libusb_device_handle *fd;
142 struct libusb_transfer *trans;
145 struct stlink_tcp_priv_s {
160 struct stlink_backend_s {
162 int (*open)(void *handle, struct hl_interface_param_s *param);
164 int (*close)(void *handle);
166 int (*xfer_noerrcheck)(void *handle, const uint8_t *buf, int size);
168 int (*read_trace)(void *handle, const uint8_t *buf, int size);
172 struct stlink_usb_handle_s {
174 struct stlink_backend_s *backend;
177 struct stlink_usb_priv_s usb_backend_priv;
178 struct stlink_tcp_priv_s tcp_backend_priv;
195 uint32_t max_mem_packet;
197 enum stlink_mode st_mode;
199 struct stlink_usb_version version;
206 /** whether SWO tracing is enabled or not */
208 /** trace module source clock */
211 /** reconnect is needed next time we try to query the
213 bool reconnect_pending;
217 static inline int stlink_usb_open(void *handle, struct hl_interface_param_s *param)
219 struct stlink_usb_handle_s *h = handle;
220 return h->backend->open(handle, param);
224 static inline int stlink_usb_close(void *handle)
226 struct stlink_usb_handle_s *h = handle;
227 return h->backend->close(handle);
230 static inline int stlink_usb_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
232 struct stlink_usb_handle_s *h = handle;
233 return h->backend->xfer_noerrcheck(handle, buf, size);
236 #define STLINK_SWIM_ERR_OK 0x00
237 #define STLINK_SWIM_BUSY 0x01
238 #define STLINK_DEBUG_ERR_OK 0x80
239 #define STLINK_DEBUG_ERR_FAULT 0x81
240 #define STLINK_SWD_AP_WAIT 0x10
241 #define STLINK_SWD_AP_FAULT 0x11
242 #define STLINK_SWD_AP_ERROR 0x12
243 #define STLINK_SWD_AP_PARITY_ERROR 0x13
244 #define STLINK_JTAG_GET_IDCODE_ERROR 0x09
245 #define STLINK_JTAG_WRITE_ERROR 0x0c
246 #define STLINK_JTAG_WRITE_VERIF_ERROR 0x0d
247 #define STLINK_SWD_DP_WAIT 0x14
248 #define STLINK_SWD_DP_FAULT 0x15
249 #define STLINK_SWD_DP_ERROR 0x16
250 #define STLINK_SWD_DP_PARITY_ERROR 0x17
252 #define STLINK_SWD_AP_WDATA_ERROR 0x18
253 #define STLINK_SWD_AP_STICKY_ERROR 0x19
254 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
256 #define STLINK_BAD_AP_ERROR 0x1d
258 #define STLINK_CORE_RUNNING 0x80
259 #define STLINK_CORE_HALTED 0x81
260 #define STLINK_CORE_STAT_UNKNOWN -1
262 #define STLINK_GET_VERSION 0xF1
263 #define STLINK_DEBUG_COMMAND 0xF2
264 #define STLINK_DFU_COMMAND 0xF3
265 #define STLINK_SWIM_COMMAND 0xF4
266 #define STLINK_GET_CURRENT_MODE 0xF5
267 #define STLINK_GET_TARGET_VOLTAGE 0xF7
269 #define STLINK_DEV_DFU_MODE 0x00
270 #define STLINK_DEV_MASS_MODE 0x01
271 #define STLINK_DEV_DEBUG_MODE 0x02
272 #define STLINK_DEV_SWIM_MODE 0x03
273 #define STLINK_DEV_BOOTLOADER_MODE 0x04
274 #define STLINK_DEV_UNKNOWN_MODE -1
276 #define STLINK_DFU_EXIT 0x07
279 STLINK_SWIM_ENTER_SEQ
280 1.3ms low then 750Hz then 1.5kHz
283 STM8 DM pulls reset pin low 50us
286 uint8_t (0=low|1=high)
293 send synchronization seq (16us low, response 64 clocks low)
295 #define STLINK_SWIM_ENTER 0x00
296 #define STLINK_SWIM_EXIT 0x01
297 #define STLINK_SWIM_READ_CAP 0x02
298 #define STLINK_SWIM_SPEED 0x03
299 #define STLINK_SWIM_ENTER_SEQ 0x04
300 #define STLINK_SWIM_GEN_RST 0x05
301 #define STLINK_SWIM_RESET 0x06
302 #define STLINK_SWIM_ASSERT_RESET 0x07
303 #define STLINK_SWIM_DEASSERT_RESET 0x08
304 #define STLINK_SWIM_READSTATUS 0x09
305 #define STLINK_SWIM_WRITEMEM 0x0a
306 #define STLINK_SWIM_READMEM 0x0b
307 #define STLINK_SWIM_READBUF 0x0c
309 #define STLINK_DEBUG_GETSTATUS 0x01
310 #define STLINK_DEBUG_FORCEDEBUG 0x02
311 #define STLINK_DEBUG_APIV1_RESETSYS 0x03
312 #define STLINK_DEBUG_APIV1_READALLREGS 0x04
313 #define STLINK_DEBUG_APIV1_READREG 0x05
314 #define STLINK_DEBUG_APIV1_WRITEREG 0x06
315 #define STLINK_DEBUG_READMEM_32BIT 0x07
316 #define STLINK_DEBUG_WRITEMEM_32BIT 0x08
317 #define STLINK_DEBUG_RUNCORE 0x09
318 #define STLINK_DEBUG_STEPCORE 0x0a
319 #define STLINK_DEBUG_APIV1_SETFP 0x0b
320 #define STLINK_DEBUG_READMEM_8BIT 0x0c
321 #define STLINK_DEBUG_WRITEMEM_8BIT 0x0d
322 #define STLINK_DEBUG_APIV1_CLEARFP 0x0e
323 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG 0x0f
324 #define STLINK_DEBUG_APIV1_SETWATCHPOINT 0x10
326 #define STLINK_DEBUG_ENTER_JTAG_RESET 0x00
327 #define STLINK_DEBUG_ENTER_SWD_NO_RESET 0xa3
328 #define STLINK_DEBUG_ENTER_JTAG_NO_RESET 0xa4
330 #define STLINK_DEBUG_APIV1_ENTER 0x20
331 #define STLINK_DEBUG_EXIT 0x21
332 #define STLINK_DEBUG_READCOREID 0x22
334 #define STLINK_DEBUG_APIV2_ENTER 0x30
335 #define STLINK_DEBUG_APIV2_READ_IDCODES 0x31
336 #define STLINK_DEBUG_APIV2_RESETSYS 0x32
337 #define STLINK_DEBUG_APIV2_READREG 0x33
338 #define STLINK_DEBUG_APIV2_WRITEREG 0x34
339 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG 0x35
340 #define STLINK_DEBUG_APIV2_READDEBUGREG 0x36
342 #define STLINK_DEBUG_APIV2_READALLREGS 0x3A
343 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
344 #define STLINK_DEBUG_APIV2_DRIVE_NRST 0x3C
346 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS2 0x3E
348 #define STLINK_DEBUG_APIV2_START_TRACE_RX 0x40
349 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX 0x41
350 #define STLINK_DEBUG_APIV2_GET_TRACE_NB 0x42
351 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ 0x43
352 #define STLINK_DEBUG_APIV2_JTAG_SET_FREQ 0x44
353 #define STLINK_DEBUG_APIV2_READ_DAP_REG 0x45
354 #define STLINK_DEBUG_APIV2_WRITE_DAP_REG 0x46
355 #define STLINK_DEBUG_APIV2_READMEM_16BIT 0x47
356 #define STLINK_DEBUG_APIV2_WRITEMEM_16BIT 0x48
358 #define STLINK_DEBUG_APIV2_INIT_AP 0x4B
359 #define STLINK_DEBUG_APIV2_CLOSE_AP_DBG 0x4C
361 #define STLINK_APIV3_SET_COM_FREQ 0x61
362 #define STLINK_APIV3_GET_COM_FREQ 0x62
364 #define STLINK_APIV3_GET_VERSION_EX 0xFB
366 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW 0x00
367 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH 0x01
368 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
370 #define STLINK_DEBUG_PORT_ACCESS 0xffff
372 #define STLINK_TRACE_SIZE 4096
373 #define STLINK_TRACE_MAX_HZ 2000000
374 #define STLINK_V3_TRACE_MAX_HZ 24000000
376 #define STLINK_V3_MAX_FREQ_NB 10
378 #define REQUEST_SENSE 0x03
379 #define REQUEST_SENSE_LENGTH 18
381 /* STLINK TCP commands */
382 #define STLINK_TCP_CMD_REFRESH_DEVICE_LIST 0x00
383 #define STLINK_TCP_CMD_GET_NB_DEV 0x01
384 #define STLINK_TCP_CMD_GET_DEV_INFO 0x02
385 #define STLINK_TCP_CMD_OPEN_DEV 0x03
386 #define STLINK_TCP_CMD_CLOSE_DEV 0x04
387 #define STLINK_TCP_CMD_SEND_USB_CMD 0x05
388 #define STLINK_TCP_CMD_GET_SERVER_VERSION 0x06
389 #define STLINK_TCP_CMD_GET_NB_OF_DEV_CLIENTS 0x07
391 /* STLINK TCP constants */
392 #define OPENOCD_STLINK_TCP_API_VERSION 1
393 #define STLINK_TCP_REQUEST_WRITE 0
394 #define STLINK_TCP_REQUEST_READ 1
395 #define STLINK_TCP_REQUEST_READ_SWO 3
396 #define STLINK_TCP_SS_SIZE 4
397 #define STLINK_TCP_USB_CMD_SIZE 32
398 #define STLINK_TCP_SERIAL_SIZE 32
399 #define STLINK_TCP_SEND_BUFFER_SIZE 10240
400 #define STLINK_TCP_RECV_BUFFER_SIZE 10240
402 /* STLINK TCP command status */
403 #define STLINK_TCP_SS_OK 0x00000001
404 #define STLINK_TCP_SS_MEMORY_PROBLEM 0x00001000
405 #define STLINK_TCP_SS_TIMEOUT 0x00001001
406 #define STLINK_TCP_SS_BAD_PARAMETER 0x00001002
407 #define STLINK_TCP_SS_OPEN_ERR 0x00001003
408 #define STLINK_TCP_SS_TRUNCATED_DATA 0x00001052
409 #define STLINK_TCP_SS_CMD_NOT_AVAILABLE 0x00001053
410 #define STLINK_TCP_SS_TCP_ERROR 0x00002001
411 #define STLINK_TCP_SS_TCP_CANT_CONNECT 0x00002002
412 #define STLINK_TCP_SS_WIN32_ERROR 0x00010000
415 * Map the relevant features, quirks and workaround for specific firmware
418 #define STLINK_F_HAS_TRACE BIT(0) /* v2>=j13 || v3 */
419 #define STLINK_F_HAS_GETLASTRWSTATUS2 BIT(1) /* v2>=j15 || v3 */
420 #define STLINK_F_HAS_SWD_SET_FREQ BIT(2) /* v2>=j22 */
421 #define STLINK_F_HAS_JTAG_SET_FREQ BIT(3) /* v2>=j24 */
422 #define STLINK_F_QUIRK_JTAG_DP_READ BIT(4) /* v2>=j24 && v2<j32 */
423 #define STLINK_F_HAS_DAP_REG BIT(5) /* v2>=j24 || v3 */
424 #define STLINK_F_HAS_MEM_16BIT BIT(6) /* v2>=j26 || v3 */
425 #define STLINK_F_HAS_AP_INIT BIT(7) /* v2>=j28 || v3 */
426 #define STLINK_F_FIX_CLOSE_AP BIT(8) /* v2>=j29 || v3 */
427 #define STLINK_F_HAS_DPBANKSEL BIT(9) /* v2>=j32 || v3>=j2 */
428 #define STLINK_F_HAS_RW8_512BYTES BIT(10) /* v3>=j6 */
431 #define STLINK_F_HAS_TARGET_VOLT STLINK_F_HAS_TRACE
432 #define STLINK_F_HAS_FPU_REG STLINK_F_HAS_GETLASTRWSTATUS2
434 #define STLINK_REGSEL_IS_FPU(x) ((x) > 0x1F)
441 /* SWD clock speed */
442 static const struct speed_map stlink_khz_to_speed_map_swd[] = {
444 {1800, 1}, /* default */
457 /* JTAG clock speed */
458 static const struct speed_map stlink_khz_to_speed_map_jtag[] = {
462 {1125, 32}, /* default */
468 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
469 static int stlink_swim_status(void *handle);
470 static void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size);
471 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map);
472 static int stlink_speed(void *handle, int khz, bool query);
473 static int stlink_usb_open_ap(void *handle, unsigned short apsel);
476 static unsigned int stlink_usb_block(void *handle)
478 struct stlink_usb_handle_s *h = handle;
482 if (h->version.flags & STLINK_F_HAS_RW8_512BYTES)
483 return STLINKV3_MAX_RW8;
485 return STLINK_MAX_RW8;
488 #ifdef USE_LIBUSB_ASYNCIO
490 static LIBUSB_CALL void sync_transfer_cb(struct libusb_transfer *transfer)
492 int *completed = transfer->user_data;
494 /* caller interprets result and frees transfer */
498 static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
500 int r, *completed = transfer->user_data;
502 while (!*completed) {
503 r = jtag_libusb_handle_events_completed(completed);
505 if (r == LIBUSB_ERROR_INTERRUPTED)
507 libusb_cancel_transfer(transfer);
514 static int transfer_error_status(const struct libusb_transfer *transfer)
518 switch (transfer->status) {
519 case LIBUSB_TRANSFER_COMPLETED:
522 case LIBUSB_TRANSFER_TIMED_OUT:
523 r = LIBUSB_ERROR_TIMEOUT;
525 case LIBUSB_TRANSFER_STALL:
526 r = LIBUSB_ERROR_PIPE;
528 case LIBUSB_TRANSFER_OVERFLOW:
529 r = LIBUSB_ERROR_OVERFLOW;
531 case LIBUSB_TRANSFER_NO_DEVICE:
532 r = LIBUSB_ERROR_NO_DEVICE;
534 case LIBUSB_TRANSFER_ERROR:
535 case LIBUSB_TRANSFER_CANCELLED:
539 r = LIBUSB_ERROR_OTHER;
553 size_t transfer_size;
554 struct libusb_transfer *transfer;
557 static int jtag_libusb_bulk_transfer_n(
558 struct libusb_device_handle *dev_handle,
559 struct jtag_xfer *transfers,
564 int returnval = ERROR_OK;
567 for (size_t i = 0; i < n_transfers; ++i) {
568 transfers[i].retval = 0;
569 transfers[i].completed = 0;
570 transfers[i].transfer_size = 0;
571 transfers[i].transfer = libusb_alloc_transfer(0);
573 if (!transfers[i].transfer) {
574 for (size_t j = 0; j < i; ++j)
575 libusb_free_transfer(transfers[j].transfer);
577 LOG_DEBUG("ERROR, failed to alloc usb transfers");
578 for (size_t k = 0; k < n_transfers; ++k)
579 transfers[k].retval = LIBUSB_ERROR_NO_MEM;
584 for (size_t i = 0; i < n_transfers; ++i) {
585 libusb_fill_bulk_transfer(
586 transfers[i].transfer,
588 transfers[i].ep, transfers[i].buf, transfers[i].size,
589 sync_transfer_cb, &transfers[i].completed, timeout);
590 transfers[i].transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
592 retval = libusb_submit_transfer(transfers[i].transfer);
594 LOG_DEBUG("ERROR, failed to submit transfer %zu, error %d", i, retval);
596 /* Probably no point continuing to submit transfers once a submission fails.
597 * As a result, tag all remaining transfers as errors.
599 for (size_t j = i; j < n_transfers; ++j)
600 transfers[j].retval = retval;
602 returnval = ERROR_FAIL;
607 /* Wait for every submitted USB transfer to complete.
609 for (size_t i = 0; i < n_transfers; ++i) {
610 if (transfers[i].retval == 0) {
611 sync_transfer_wait_for_completion(transfers[i].transfer);
613 retval = transfer_error_status(transfers[i].transfer);
615 returnval = ERROR_FAIL;
616 transfers[i].retval = retval;
617 LOG_DEBUG("ERROR, transfer %zu failed, error %d", i, retval);
619 /* Assuming actual_length is only valid if there is no transfer error.
621 transfers[i].transfer_size = transfers[i].transfer->actual_length;
625 libusb_free_transfer(transfers[i].transfer);
626 transfers[i].transfer = NULL;
636 static int stlink_usb_xfer_v1_get_status(void *handle)
638 struct stlink_usb_handle_s *h = handle;
644 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
646 ret = jtag_libusb_bulk_read(h->usb_backend_priv.fd, h->rx_ep, (char *)h->cmdbuf, 13,
647 STLINK_READ_TIMEOUT, &tr);
653 t1 = buf_get_u32(h->cmdbuf, 0, 32);
656 if (t1 != 0x53425355)
664 if (h->cmdbuf[12] != 0)
670 #ifdef USE_LIBUSB_ASYNCIO
671 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
673 struct stlink_usb_handle_s *h = handle;
677 size_t n_transfers = 0;
678 struct jtag_xfer transfers[2];
680 memset(transfers, 0, sizeof(transfers));
682 transfers[0].ep = h->tx_ep;
683 transfers[0].buf = h->cmdbuf;
684 transfers[0].size = cmdsize;
688 if (h->direction == h->tx_ep && size) {
689 transfers[1].ep = h->tx_ep;
690 transfers[1].buf = (uint8_t *)buf;
691 transfers[1].size = size;
694 } else if (h->direction == h->rx_ep && size) {
695 transfers[1].ep = h->rx_ep;
696 transfers[1].buf = (uint8_t *)buf;
697 transfers[1].size = size;
702 return jtag_libusb_bulk_transfer_n(
703 h->usb_backend_priv.fd,
706 STLINK_WRITE_TIMEOUT);
709 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
711 struct stlink_usb_handle_s *h = handle;
716 ret = jtag_libusb_bulk_write(h->usb_backend_priv.fd, h->tx_ep, (char *)h->cmdbuf,
717 cmdsize, STLINK_WRITE_TIMEOUT, &tr);
718 if (ret || tr != cmdsize)
721 if (h->direction == h->tx_ep && size) {
722 ret = jtag_libusb_bulk_write(h->usb_backend_priv.fd, h->tx_ep, (char *)buf,
723 size, STLINK_WRITE_TIMEOUT, &tr);
724 if (ret || tr != size) {
725 LOG_DEBUG("bulk write failed");
728 } else if (h->direction == h->rx_ep && size) {
729 ret = jtag_libusb_bulk_read(h->usb_backend_priv.fd, h->rx_ep, (char *)buf,
730 size, STLINK_READ_TIMEOUT, &tr);
731 if (ret || tr != size) {
732 LOG_DEBUG("bulk read failed");
742 static int stlink_usb_xfer_v1_get_sense(void *handle)
745 struct stlink_usb_handle_s *h = handle;
749 stlink_usb_init_buffer(handle, h->rx_ep, 16);
751 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE;
752 h->cmdbuf[h->cmdidx++] = 0;
753 h->cmdbuf[h->cmdidx++] = 0;
754 h->cmdbuf[h->cmdidx++] = 0;
755 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE_LENGTH;
757 res = stlink_usb_xfer_rw(handle, REQUEST_SENSE_LENGTH, h->databuf, 16);
762 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK)
769 static int stlink_usb_usb_read_trace(void *handle, const uint8_t *buf, int size)
771 struct stlink_usb_handle_s *h = handle;
774 ret = jtag_libusb_bulk_read(h->usb_backend_priv.fd, h->trace_ep, (char *)buf, size,
775 STLINK_READ_TIMEOUT, &tr);
776 if (ret || tr != size) {
777 LOG_ERROR("bulk trace read failed");
785 transfers block in cmdbuf
786 <size> indicates number of bytes in the following
788 Ignore the (eventual) error code in the received packet.
790 static int stlink_usb_usb_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
792 int err, cmdsize = STLINK_CMD_SIZE_V2;
793 struct stlink_usb_handle_s *h = handle;
797 if (h->version.stlink == 1) {
798 cmdsize = STLINK_SG_SIZE;
799 /* put length in bCBWCBLength */
800 h->cmdbuf[14] = h->cmdidx-15;
803 err = stlink_usb_xfer_rw(handle, cmdsize, buf, size);
808 if (h->version.stlink == 1) {
809 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK) {
810 /* check csw status */
811 if (h->cmdbuf[12] == 1) {
812 LOG_DEBUG("get sense");
813 if (stlink_usb_xfer_v1_get_sense(handle) != ERROR_OK)
824 static int stlink_tcp_send_cmd(void *handle, int send_size, int recv_size, bool check_tcp_status)
826 struct stlink_usb_handle_s *h = handle;
830 /* send the TCP command */
831 int sent_size = send(h->tcp_backend_priv.fd, (void *)h->tcp_backend_priv.send_buf, send_size, 0);
832 if (sent_size != send_size) {
833 LOG_ERROR("failed to send USB CMD");
835 LOG_DEBUG("socket send error: %s (errno %d)", strerror(errno), errno);
837 LOG_DEBUG("sent size %d (expected %d)", sent_size, send_size);
843 /* read the TCP response */
844 int received_size = recv(h->tcp_backend_priv.fd, (void *)h->tcp_backend_priv.recv_buf, recv_size, 0);
845 if (received_size != recv_size) {
846 LOG_ERROR("failed to receive USB CMD response");
847 if (received_size == -1)
848 LOG_DEBUG("socket recv error: %s (errno %d)", strerror(errno), errno);
850 LOG_DEBUG("received size %d (expected %d)", received_size, recv_size);
854 if (check_tcp_status) {
855 uint32_t tcp_ss = le_to_h_u32(h->tcp_backend_priv.recv_buf);
856 if (tcp_ss != STLINK_TCP_SS_OK) {
857 LOG_ERROR("TCP error status 0x%X", tcp_ss);
866 static int stlink_tcp_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
868 struct stlink_usb_handle_s *h = handle;
870 int send_size = STLINK_TCP_USB_CMD_SIZE;
871 int recv_size = STLINK_TCP_SS_SIZE;
875 /* prepare the TCP command */
876 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_SEND_USB_CMD;
877 memset(&h->tcp_backend_priv.send_buf[1], 0, 3); /* reserved for alignment and future use, must be zero */
878 h_u32_to_le(&h->tcp_backend_priv.send_buf[4], h->tcp_backend_priv.connect_id);
879 /* tcp_backend_priv.send_buf[8..23] already contains the constructed stlink command */
880 h->tcp_backend_priv.send_buf[24] = h->direction;
881 memset(&h->tcp_backend_priv.send_buf[25], 0, 3); /* reserved for alignment and future use, must be zero */
883 h_u32_to_le(&h->tcp_backend_priv.send_buf[28], size);
886 * if the xfer is a write request (tx_ep)
887 * > then buf content will be copied
889 * else : the xfer is a read or trace read request (rx_ep or trace_ep)
890 * > the buf content will be filled from &databuf[4].
892 * note : if h->direction is trace_ep, h->cmdbuf is zeros.
895 if (h->direction == h->tx_ep) { /* STLINK_TCP_REQUEST_WRITE */
897 if (send_size > STLINK_TCP_SEND_BUFFER_SIZE) {
898 LOG_ERROR("STLINK_TCP command buffer overflow");
901 memcpy(&h->tcp_backend_priv.send_buf[32], buf, size);
902 } else { /* STLINK_TCP_REQUEST_READ or STLINK_TCP_REQUEST_READ_SWO */
904 if (recv_size > STLINK_TCP_RECV_BUFFER_SIZE) {
905 LOG_ERROR("STLINK_TCP data buffer overflow");
910 int ret = stlink_tcp_send_cmd(h, send_size, recv_size, true);
914 if (h->direction != h->tx_ep) {
915 /* the read data is located in tcp_backend_priv.recv_buf[4] */
916 /* most of the case it will be copying the data from tcp_backend_priv.recv_buf[4]
917 * to handle->cmd_buff which are the same, so let's avoid unnecessary copying */
918 if (buf != &h->tcp_backend_priv.recv_buf[4])
919 memcpy((uint8_t *)buf, &h->tcp_backend_priv.recv_buf[4], size);
926 static int stlink_tcp_read_trace(void *handle, const uint8_t *buf, int size)
928 struct stlink_usb_handle_s *h = handle;
930 stlink_usb_init_buffer(h, h->trace_ep, 0);
931 return stlink_tcp_xfer_noerrcheck(handle, buf, size);
935 Converts an STLINK status code held in the first byte of a response
936 to an openocd error, logs any error/wait status as debug output.
938 static int stlink_usb_error_check(void *handle)
940 struct stlink_usb_handle_s *h = handle;
944 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
945 switch (h->databuf[0]) {
946 case STLINK_SWIM_ERR_OK:
948 case STLINK_SWIM_BUSY:
951 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
956 /* TODO: no error checking yet on api V1 */
957 if (h->version.jtag_api == STLINK_JTAG_API_V1)
958 h->databuf[0] = STLINK_DEBUG_ERR_OK;
960 switch (h->databuf[0]) {
961 case STLINK_DEBUG_ERR_OK:
963 case STLINK_DEBUG_ERR_FAULT:
964 LOG_DEBUG("SWD fault response (0x%x)", STLINK_DEBUG_ERR_FAULT);
966 case STLINK_SWD_AP_WAIT:
967 LOG_DEBUG("wait status SWD_AP_WAIT (0x%x)", STLINK_SWD_AP_WAIT);
969 case STLINK_SWD_DP_WAIT:
970 LOG_DEBUG("wait status SWD_DP_WAIT (0x%x)", STLINK_SWD_DP_WAIT);
972 case STLINK_JTAG_GET_IDCODE_ERROR:
973 LOG_DEBUG("STLINK_JTAG_GET_IDCODE_ERROR");
975 case STLINK_JTAG_WRITE_ERROR:
976 LOG_DEBUG("Write error");
978 case STLINK_JTAG_WRITE_VERIF_ERROR:
979 LOG_DEBUG("Write verify error, ignoring");
981 case STLINK_SWD_AP_FAULT:
982 /* git://git.ac6.fr/openocd commit 657e3e885b9ee10
983 * returns ERROR_OK with the comment:
984 * Change in error status when reading outside RAM.
985 * This fix allows CDT plugin to visualize memory.
987 LOG_DEBUG("STLINK_SWD_AP_FAULT");
989 case STLINK_SWD_AP_ERROR:
990 LOG_DEBUG("STLINK_SWD_AP_ERROR");
992 case STLINK_SWD_AP_PARITY_ERROR:
993 LOG_DEBUG("STLINK_SWD_AP_PARITY_ERROR");
995 case STLINK_SWD_DP_FAULT:
996 LOG_DEBUG("STLINK_SWD_DP_FAULT");
998 case STLINK_SWD_DP_ERROR:
999 LOG_DEBUG("STLINK_SWD_DP_ERROR");
1001 case STLINK_SWD_DP_PARITY_ERROR:
1002 LOG_DEBUG("STLINK_SWD_DP_PARITY_ERROR");
1004 case STLINK_SWD_AP_WDATA_ERROR:
1005 LOG_DEBUG("STLINK_SWD_AP_WDATA_ERROR");
1007 case STLINK_SWD_AP_STICKY_ERROR:
1008 LOG_DEBUG("STLINK_SWD_AP_STICKY_ERROR");
1010 case STLINK_SWD_AP_STICKYORUN_ERROR:
1011 LOG_DEBUG("STLINK_SWD_AP_STICKYORUN_ERROR");
1013 case STLINK_BAD_AP_ERROR:
1014 LOG_DEBUG("STLINK_BAD_AP_ERROR");
1017 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
1023 * Wrapper around stlink_usb_xfer_noerrcheck()
1024 * to check the error code in the received packet
1026 static int stlink_usb_xfer_errcheck(void *handle, const uint8_t *buf, int size)
1032 retval = stlink_usb_xfer_noerrcheck(handle, buf, size);
1033 if (retval != ERROR_OK)
1036 return stlink_usb_error_check(handle);
1039 /** Issue an STLINK command via USB transfer, with retries on any wait status responses.
1041 Works for commands where the STLINK_DEBUG status is returned in the first
1042 byte of the response packet. For SWIM a SWIM_READSTATUS is requested instead.
1044 Returns an openocd result code.
1046 static int stlink_cmd_allow_retry(void *handle, const uint8_t *buf, int size)
1050 struct stlink_usb_handle_s *h = handle;
1053 if ((h->st_mode != STLINK_MODE_DEBUG_SWIM) || !retries) {
1054 res = stlink_usb_xfer_noerrcheck(handle, buf, size);
1055 if (res != ERROR_OK)
1059 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
1060 res = stlink_swim_status(handle);
1061 if (res != ERROR_OK)
1065 res = stlink_usb_error_check(handle);
1066 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1067 unsigned int delay_us = (1<<retries++) * 1000;
1068 LOG_DEBUG("stlink_cmd_allow_retry ERROR_WAIT, retry %d, delaying %u microseconds", retries, delay_us);
1077 static int stlink_usb_read_trace(void *handle, const uint8_t *buf, int size)
1079 struct stlink_usb_handle_s *h = handle;
1083 assert(h->version.flags & STLINK_F_HAS_TRACE);
1085 return h->backend->read_trace(handle, buf, size);
1089 this function writes transfer length in
1090 the right place in the cb
1092 static void stlink_usb_set_cbw_transfer_datalength(void *handle, uint32_t size)
1094 struct stlink_usb_handle_s *h = handle;
1096 buf_set_u32(h->cmdbuf+8, 0, 32, size);
1099 static void stlink_usb_xfer_v1_create_cmd(void *handle, uint8_t direction, uint32_t size)
1101 struct stlink_usb_handle_s *h = handle;
1103 /* fill the send buffer */
1104 strcpy((char *)h->cmdbuf, "USBC");
1106 /* csw tag not used */
1107 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, 0);
1109 /* cbw data transfer length (in the following data phase in or out) */
1110 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, size);
1113 h->cmdbuf[h->cmdidx++] = (direction == h->rx_ep ? ENDPOINT_IN : ENDPOINT_OUT);
1114 h->cmdbuf[h->cmdidx++] = 0; /* lun */
1115 /* cdb clength (is filled in at xfer) */
1116 h->cmdbuf[h->cmdidx++] = 0;
1120 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size)
1122 struct stlink_usb_handle_s *h = handle;
1124 h->direction = direction;
1128 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
1129 memset(h->databuf, 0, STLINK_DATA_SIZE);
1131 if (h->version.stlink == 1)
1132 stlink_usb_xfer_v1_create_cmd(handle, direction, size);
1136 static int stlink_usb_version(void *handle)
1141 uint8_t v, x, y, jtag, swim, msd, bridge = 0;
1142 char v_str[5 * (1 + 3) + 1]; /* VvJjMmBbSs */
1144 struct stlink_usb_handle_s *h = handle;
1148 stlink_usb_init_buffer(handle, h->rx_ep, 6);
1150 h->cmdbuf[h->cmdidx++] = STLINK_GET_VERSION;
1152 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 6);
1154 if (res != ERROR_OK)
1157 version = be_to_h_u16(h->databuf);
1158 v = (version >> 12) & 0x0f;
1159 x = (version >> 6) & 0x3f;
1162 h->vid = le_to_h_u16(h->databuf + 2);
1163 h->pid = le_to_h_u16(h->databuf + 4);
1166 case STLINK_V2_1_PID:
1167 case STLINK_V2_1_NO_MSD_PID:
1168 if ((x <= 22 && y == 7) || (x >= 25 && y >= 7 && y <= 12)) {
1169 /* MxSy : STM8 V2.1 - SWIM only */
1174 /* JxMy : STM32 V2.1 - JTAG/SWD only */
1187 /* STLINK-V3 requires a specific command */
1188 if (v == 3 && x == 0 && y == 0) {
1189 stlink_usb_init_buffer(handle, h->rx_ep, 16);
1191 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_VERSION_EX;
1193 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 12);
1194 if (res != ERROR_OK)
1198 swim = h->databuf[1];
1199 jtag = h->databuf[2];
1200 msd = h->databuf[3];
1201 bridge = h->databuf[4];
1202 h->vid = le_to_h_u16(h->databuf + 8);
1203 h->pid = le_to_h_u16(h->databuf + 10);
1206 h->version.stlink = v;
1207 h->version.jtag = jtag;
1208 h->version.swim = swim;
1211 switch (h->version.stlink) {
1213 /* ST-LINK/V1 from J11 switch to api-v2 (and support SWD) */
1214 if (h->version.jtag >= 11)
1215 h->version.jtag_api = STLINK_JTAG_API_V2;
1217 h->version.jtag_api = STLINK_JTAG_API_V1;
1221 /* all ST-LINK/V2 and ST-Link/V2.1 use api-v2 */
1222 h->version.jtag_api = STLINK_JTAG_API_V2;
1224 /* API for trace from J13 */
1225 /* API for target voltage from J13 */
1226 if (h->version.jtag >= 13)
1227 flags |= STLINK_F_HAS_TRACE;
1229 /* preferred API to get last R/W status from J15 */
1230 if (h->version.jtag >= 15)
1231 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1233 /* API to set SWD frequency from J22 */
1234 if (h->version.jtag >= 22)
1235 flags |= STLINK_F_HAS_SWD_SET_FREQ;
1237 /* API to set JTAG frequency from J24 */
1238 /* API to access DAP registers from J24 */
1239 if (h->version.jtag >= 24) {
1240 flags |= STLINK_F_HAS_JTAG_SET_FREQ;
1241 flags |= STLINK_F_HAS_DAP_REG;
1244 /* Quirk for read DP in JTAG mode (V2 only) from J24, fixed in J32 */
1245 if (h->version.jtag >= 24 && h->version.jtag < 32)
1246 flags |= STLINK_F_QUIRK_JTAG_DP_READ;
1248 /* API to read/write memory at 16 bit from J26 */
1249 if (h->version.jtag >= 26)
1250 flags |= STLINK_F_HAS_MEM_16BIT;
1252 /* API required to init AP before any AP access from J28 */
1253 if (h->version.jtag >= 28)
1254 flags |= STLINK_F_HAS_AP_INIT;
1256 /* API required to return proper error code on close AP from J29 */
1257 if (h->version.jtag >= 29)
1258 flags |= STLINK_F_FIX_CLOSE_AP;
1260 /* Banked regs (DPv1 & DPv2) support from V2J32 */
1261 if (h->version.jtag >= 32)
1262 flags |= STLINK_F_HAS_DPBANKSEL;
1266 /* all STLINK-V3 use api-v3 */
1267 h->version.jtag_api = STLINK_JTAG_API_V3;
1269 /* STLINK-V3 is a superset of ST-LINK/V2 */
1272 /* API for target voltage */
1273 flags |= STLINK_F_HAS_TRACE;
1275 /* preferred API to get last R/W status */
1276 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1278 /* API to access DAP registers */
1279 flags |= STLINK_F_HAS_DAP_REG;
1281 /* API to read/write memory at 16 bit */
1282 flags |= STLINK_F_HAS_MEM_16BIT;
1284 /* API required to init AP before any AP access */
1285 flags |= STLINK_F_HAS_AP_INIT;
1287 /* API required to return proper error code on close AP */
1288 flags |= STLINK_F_FIX_CLOSE_AP;
1290 /* Banked regs (DPv1 & DPv2) support from V3J2 */
1291 if (h->version.jtag >= 2)
1292 flags |= STLINK_F_HAS_DPBANKSEL;
1294 /* 8bit read/write max packet size 512 bytes from V3J6 */
1295 if (h->version.jtag >= 6)
1296 flags |= STLINK_F_HAS_RW8_512BYTES;
1302 h->version.flags = flags;
1305 p += sprintf(p, "V%d", v);
1307 p += sprintf(p, "J%d", jtag);
1309 p += sprintf(p, "M%d", msd);
1311 p += sprintf(p, "B%d", bridge);
1313 sprintf(p, "S%d", swim);
1315 LOG_INFO("STLINK %s (API v%d) VID:PID %04X:%04X",
1317 h->version.jtag_api,
1324 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
1326 struct stlink_usb_handle_s *h = handle;
1327 uint32_t adc_results[2];
1329 /* no error message, simply quit with error */
1330 if (!(h->version.flags & STLINK_F_HAS_TARGET_VOLT))
1331 return ERROR_COMMAND_NOTFOUND;
1333 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1335 h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
1337 int result = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1339 if (result != ERROR_OK)
1342 /* convert result */
1343 adc_results[0] = le_to_h_u32(h->databuf);
1344 adc_results[1] = le_to_h_u32(h->databuf + 4);
1346 *target_voltage = 0;
1349 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
1351 LOG_INFO("Target voltage: %f", (double)*target_voltage);
1356 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
1358 struct stlink_usb_handle_s *h = handle;
1362 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
1363 return ERROR_COMMAND_NOTFOUND;
1365 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1367 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1368 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
1369 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1372 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1374 if (result != ERROR_OK)
1380 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
1382 struct stlink_usb_handle_s *h = handle;
1386 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
1387 return ERROR_COMMAND_NOTFOUND;
1389 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1391 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1392 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
1393 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1396 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1398 if (result != ERROR_OK)
1405 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
1408 struct stlink_usb_handle_s *h = handle;
1412 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1414 h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
1416 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1418 if (res != ERROR_OK)
1421 *mode = h->databuf[0];
1427 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
1430 struct stlink_usb_handle_s *h = handle;
1434 /* on api V2 we are able the read the latest command
1436 * TODO: we need the test on api V1 too
1438 if (h->version.jtag_api != STLINK_JTAG_API_V1)
1441 stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
1444 case STLINK_MODE_DEBUG_JTAG:
1445 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1446 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1447 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1449 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1450 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG_NO_RESET;
1452 case STLINK_MODE_DEBUG_SWD:
1453 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1454 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1455 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1457 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1458 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD_NO_RESET;
1460 case STLINK_MODE_DEBUG_SWIM:
1461 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1462 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
1463 /* swim enter does not return any response or status */
1464 return stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1465 case STLINK_MODE_DFU:
1466 case STLINK_MODE_MASS:
1471 return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
1475 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
1478 struct stlink_usb_handle_s *h = handle;
1482 /* command with no reply, use a valid endpoint but zero size */
1483 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1486 case STLINK_MODE_DEBUG_JTAG:
1487 case STLINK_MODE_DEBUG_SWD:
1488 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1489 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
1491 case STLINK_MODE_DEBUG_SWIM:
1492 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1493 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
1495 case STLINK_MODE_DFU:
1496 h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
1497 h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
1499 case STLINK_MODE_MASS:
1504 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1506 if (res != ERROR_OK)
1512 static int stlink_usb_assert_srst(void *handle, int srst);
1514 static enum stlink_mode stlink_get_mode(enum hl_transports t)
1517 case HL_TRANSPORT_SWD:
1518 return STLINK_MODE_DEBUG_SWD;
1519 case HL_TRANSPORT_JTAG:
1520 return STLINK_MODE_DEBUG_JTAG;
1522 return STLINK_MODE_UNKNOWN;
1527 static int stlink_usb_exit_mode(void *handle)
1531 enum stlink_mode emode;
1535 res = stlink_usb_current_mode(handle, &mode);
1537 if (res != ERROR_OK)
1540 LOG_DEBUG("MODE: 0x%02X", mode);
1542 /* try to exit current mode */
1544 case STLINK_DEV_DFU_MODE:
1545 emode = STLINK_MODE_DFU;
1547 case STLINK_DEV_DEBUG_MODE:
1548 emode = STLINK_MODE_DEBUG_SWD;
1550 case STLINK_DEV_SWIM_MODE:
1551 emode = STLINK_MODE_DEBUG_SWIM;
1553 case STLINK_DEV_BOOTLOADER_MODE:
1554 case STLINK_DEV_MASS_MODE:
1556 emode = STLINK_MODE_UNKNOWN;
1560 if (emode != STLINK_MODE_UNKNOWN)
1561 return stlink_usb_mode_leave(handle, emode);
1567 static int stlink_usb_init_mode(void *handle, bool connect_under_reset, int initial_interface_speed)
1571 enum stlink_mode emode;
1572 struct stlink_usb_handle_s *h = handle;
1576 res = stlink_usb_exit_mode(handle);
1577 if (res != ERROR_OK)
1580 res = stlink_usb_current_mode(handle, &mode);
1582 if (res != ERROR_OK)
1585 /* we check the target voltage here as an aid to debugging connection problems.
1586 * the stlink requires the target Vdd to be connected for reliable debugging.
1587 * this cmd is supported in all modes except DFU
1589 if (mode != STLINK_DEV_DFU_MODE) {
1591 float target_voltage;
1593 /* check target voltage (if supported) */
1594 res = stlink_usb_check_voltage(h, &target_voltage);
1596 if (res != ERROR_OK) {
1597 if (res != ERROR_COMMAND_NOTFOUND)
1598 LOG_ERROR("voltage check failed");
1599 /* attempt to continue as it is not a catastrophic failure */
1601 /* check for a sensible target voltage, operating range is 1.65-5.5v
1602 * according to datasheet */
1603 if (target_voltage < 1.5)
1604 LOG_ERROR("target voltage may be too low for reliable debugging");
1608 LOG_DEBUG("MODE: 0x%02X", mode);
1610 /* set selected mode */
1613 if (emode == STLINK_MODE_UNKNOWN) {
1614 LOG_ERROR("selected mode (transport) not supported");
1618 /* set the speed before entering the mode, as the chip discovery phase should be done at this speed too */
1619 if (emode == STLINK_MODE_DEBUG_JTAG) {
1620 if (h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ) {
1621 stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
1622 stlink_speed(h, initial_interface_speed, false);
1624 } else if (emode == STLINK_MODE_DEBUG_SWD) {
1625 if (h->version.flags & STLINK_F_HAS_SWD_SET_FREQ) {
1626 stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
1627 stlink_speed(h, initial_interface_speed, false);
1631 if (h->version.jtag_api == STLINK_JTAG_API_V3 &&
1632 (emode == STLINK_MODE_DEBUG_JTAG || emode == STLINK_MODE_DEBUG_SWD)) {
1633 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
1635 stlink_get_com_freq(h, (emode == STLINK_MODE_DEBUG_JTAG), map);
1636 stlink_dump_speed_map(map, ARRAY_SIZE(map));
1637 stlink_speed(h, initial_interface_speed, false);
1640 /* preliminary SRST assert:
1641 * We want SRST is asserted before activating debug signals (mode_enter).
1642 * As the required mode has not been set, the adapter may not know what pin to use.
1643 * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
1644 * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
1645 * after power on, SWIM_RST stays unchanged */
1646 if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
1647 stlink_usb_assert_srst(handle, 0);
1648 /* do not check the return status here, we will
1649 proceed and enter the desired mode below
1650 and try asserting srst again. */
1652 res = stlink_usb_mode_enter(handle, emode);
1653 if (res != ERROR_OK)
1656 /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
1657 if (connect_under_reset) {
1658 res = stlink_usb_assert_srst(handle, 0);
1659 if (res != ERROR_OK)
1663 res = stlink_usb_current_mode(handle, &mode);
1665 if (res != ERROR_OK)
1668 LOG_DEBUG("MODE: 0x%02X", mode);
1673 /* request status from last swim request */
1674 static int stlink_swim_status(void *handle)
1676 struct stlink_usb_handle_s *h = handle;
1679 stlink_usb_init_buffer(handle, h->rx_ep, 4);
1680 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1681 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
1682 /* error is checked by the caller */
1683 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1684 if (res != ERROR_OK)
1689 the purpose of this function is unknown...
1690 capabilities? anyway for swim v6 it returns
1693 __attribute__((unused))
1694 static int stlink_swim_cap(void *handle, uint8_t *cap)
1696 struct stlink_usb_handle_s *h = handle;
1699 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1700 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1701 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1702 h->cmdbuf[h->cmdidx++] = 0x01;
1703 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1704 if (res != ERROR_OK)
1706 memcpy(cap, h->databuf, 8);
1710 /* debug dongle assert/deassert sreset line */
1711 static int stlink_swim_assert_reset(void *handle, int reset)
1713 struct stlink_usb_handle_s *h = handle;
1716 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1717 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1719 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1721 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1722 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1723 if (res != ERROR_OK)
1730 1.3ms low then 750Hz then 1.5kHz
1732 static int stlink_swim_enter(void *handle)
1734 struct stlink_usb_handle_s *h = handle;
1737 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1738 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1739 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1740 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1741 if (res != ERROR_OK)
1746 /* switch high/low speed swim */
1747 static int stlink_swim_speed(void *handle, int speed)
1749 struct stlink_usb_handle_s *h = handle;
1752 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1753 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1754 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1756 h->cmdbuf[h->cmdidx++] = 1;
1758 h->cmdbuf[h->cmdidx++] = 0;
1759 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1760 if (res != ERROR_OK)
1766 initiate srst from swim.
1767 nrst is pulled low for 50us.
1769 static int stlink_swim_generate_rst(void *handle)
1771 struct stlink_usb_handle_s *h = handle;
1774 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1775 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1776 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1777 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1778 if (res != ERROR_OK)
1784 send resynchronize sequence
1785 swim is pulled low for 16us
1786 reply is 64 clks low
1788 static int stlink_swim_resync(void *handle)
1790 struct stlink_usb_handle_s *h = handle;
1793 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1794 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1795 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_RESET;
1796 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1797 if (res != ERROR_OK)
1802 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1804 struct stlink_usb_handle_s *h = handle;
1807 unsigned int datalen = 0;
1808 int cmdsize = STLINK_CMD_SIZE_V2;
1810 if (len > STLINK_DATA_SIZE)
1813 if (h->version.stlink == 1)
1814 cmdsize = STLINK_SG_SIZE;
1816 stlink_usb_init_buffer(handle, h->tx_ep, 0);
1817 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1818 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1819 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1821 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1823 for (i = 0; i < len; i++) {
1824 if (h->cmdidx == cmdsize)
1825 h->databuf[datalen++] = *(data++);
1827 h->cmdbuf[h->cmdidx++] = *(data++);
1829 if (h->version.stlink == 1)
1830 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1832 res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1833 if (res != ERROR_OK)
1838 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1840 struct stlink_usb_handle_s *h = handle;
1843 if (len > STLINK_DATA_SIZE)
1846 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1847 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1848 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1849 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1851 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1853 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1854 if (res != ERROR_OK)
1857 stlink_usb_init_buffer(handle, h->rx_ep, len);
1858 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1859 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1860 res = stlink_usb_xfer_noerrcheck(handle, data, len);
1861 if (res != ERROR_OK)
1868 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1871 struct stlink_usb_handle_s *h = handle;
1875 /* there is no swim read core id cmd */
1876 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
1881 stlink_usb_init_buffer(handle, h->rx_ep, 12);
1883 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1884 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1885 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1887 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1890 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_IDCODES;
1892 res = stlink_usb_xfer_errcheck(handle, h->databuf, 12);
1896 if (res != ERROR_OK)
1899 *idcode = le_to_h_u32(h->databuf + offset);
1901 LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1906 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1908 struct stlink_usb_handle_s *h = handle;
1913 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1915 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1916 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1917 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1920 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1921 if (res != ERROR_OK)
1924 *val = le_to_h_u32(h->databuf + 4);
1928 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1930 struct stlink_usb_handle_s *h = handle;
1934 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1936 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1937 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1938 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1940 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1941 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1943 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1946 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1950 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1952 struct stlink_usb_handle_s *h = handle;
1956 if (h->trace.enabled && (h->version.flags & STLINK_F_HAS_TRACE)) {
1959 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1961 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1962 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1964 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1965 if (res != ERROR_OK)
1968 size_t bytes_avail = le_to_h_u16(h->databuf);
1969 *size = bytes_avail < *size ? bytes_avail : *size;
1972 res = stlink_usb_read_trace(handle, buf, *size);
1973 if (res != ERROR_OK)
1982 static enum target_state stlink_usb_v2_get_status(void *handle)
1987 result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1988 if (result != ERROR_OK)
1989 return TARGET_UNKNOWN;
1991 if (status & S_HALT)
1992 return TARGET_HALTED;
1993 else if (status & S_RESET_ST)
1994 return TARGET_RESET;
1996 return TARGET_RUNNING;
2000 static enum target_state stlink_usb_state(void *handle)
2003 struct stlink_usb_handle_s *h = handle;
2007 if (h->reconnect_pending) {
2008 LOG_INFO("Previous state query failed, trying to reconnect");
2009 res = stlink_usb_mode_enter(handle, h->st_mode);
2010 if (res != ERROR_OK)
2011 return TARGET_UNKNOWN;
2013 h->reconnect_pending = false;
2016 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
2017 res = stlink_usb_v2_get_status(handle);
2018 if (res == TARGET_UNKNOWN)
2019 h->reconnect_pending = true;
2023 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2025 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2026 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
2028 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
2030 if (res != ERROR_OK)
2031 return TARGET_UNKNOWN;
2033 if (h->databuf[0] == STLINK_CORE_RUNNING)
2034 return TARGET_RUNNING;
2035 if (h->databuf[0] == STLINK_CORE_HALTED)
2036 return TARGET_HALTED;
2038 h->reconnect_pending = true;
2040 return TARGET_UNKNOWN;
2043 static int stlink_usb_assert_srst(void *handle, int srst)
2045 struct stlink_usb_handle_s *h = handle;
2049 if (h->st_mode == STLINK_MODE_DEBUG_SWIM)
2050 return stlink_swim_assert_reset(handle, srst);
2052 if (h->version.stlink == 1)
2053 return ERROR_COMMAND_NOTFOUND;
2055 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2057 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2058 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
2059 h->cmdbuf[h->cmdidx++] = srst;
2061 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2065 static void stlink_usb_trace_disable(void *handle)
2068 struct stlink_usb_handle_s *h = handle;
2072 assert(h->version.flags & STLINK_F_HAS_TRACE);
2074 LOG_DEBUG("Tracing: disable");
2076 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2077 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2078 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
2079 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2081 if (res == ERROR_OK)
2082 h->trace.enabled = false;
2087 static int stlink_usb_trace_enable(void *handle)
2090 struct stlink_usb_handle_s *h = handle;
2094 if (h->version.flags & STLINK_F_HAS_TRACE) {
2095 stlink_usb_init_buffer(handle, h->rx_ep, 10);
2097 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2098 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
2099 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
2101 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
2104 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2106 if (res == ERROR_OK) {
2107 h->trace.enabled = true;
2108 LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
2111 LOG_ERROR("Tracing is not supported by this version.");
2119 static int stlink_usb_reset(void *handle)
2121 struct stlink_usb_handle_s *h = handle;
2126 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2128 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2130 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2131 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
2133 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
2135 retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
2136 if (retval != ERROR_OK)
2139 if (h->trace.enabled) {
2140 stlink_usb_trace_disable(h);
2141 return stlink_usb_trace_enable(h);
2148 static int stlink_usb_run(void *handle)
2151 struct stlink_usb_handle_s *h = handle;
2155 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
2156 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
2161 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2163 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2164 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
2166 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2170 static int stlink_usb_halt(void *handle)
2173 struct stlink_usb_handle_s *h = handle;
2177 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
2178 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
2183 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2185 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2186 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
2188 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2192 static int stlink_usb_step(void *handle)
2194 struct stlink_usb_handle_s *h = handle;
2198 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
2199 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
2200 * that the Cortex-M3 currently does. */
2201 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
2202 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
2203 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
2206 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2208 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2209 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
2211 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2215 static int stlink_usb_read_regs(void *handle)
2218 struct stlink_usb_handle_s *h = handle;
2222 stlink_usb_init_buffer(handle, h->rx_ep, 88);
2224 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2225 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2227 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
2228 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 84);
2229 /* regs data from offset 0 */
2231 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
2232 res = stlink_usb_xfer_errcheck(handle, h->databuf, 88);
2233 /* status at offset 0, regs data from offset 4 */
2240 static int stlink_usb_read_reg(void *handle, unsigned int regsel, uint32_t *val)
2243 struct stlink_usb_handle_s *h = handle;
2247 if (STLINK_REGSEL_IS_FPU(regsel) && !(h->version.flags & STLINK_F_HAS_FPU_REG)) {
2248 res = stlink_usb_write_debug_reg(h, DCB_DCRSR, regsel & 0x7f);
2249 if (res != ERROR_OK)
2252 /* FIXME: poll DHCSR.S_REGRDY before read DCRDR */
2253 return stlink_usb_v2_read_debug_reg(h, DCB_DCRDR, val);
2256 stlink_usb_init_buffer(handle, h->rx_ep, h->version.jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
2258 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2259 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2260 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
2262 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
2263 h->cmdbuf[h->cmdidx++] = regsel;
2265 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2266 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
2267 if (res != ERROR_OK)
2269 *val = le_to_h_u32(h->databuf);
2272 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
2273 if (res != ERROR_OK)
2275 *val = le_to_h_u32(h->databuf + 4);
2281 static int stlink_usb_write_reg(void *handle, unsigned int regsel, uint32_t val)
2283 struct stlink_usb_handle_s *h = handle;
2287 if (STLINK_REGSEL_IS_FPU(regsel) && !(h->version.flags & STLINK_F_HAS_FPU_REG)) {
2288 int res = stlink_usb_write_debug_reg(h, DCB_DCRDR, val);
2289 if (res != ERROR_OK)
2292 return stlink_usb_write_debug_reg(h, DCB_DCRSR, DCRSR_WNR | (regsel & 0x7f));
2293 /* FIXME: poll DHCSR.S_REGRDY after write DCRSR */
2296 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2298 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2299 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2300 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
2302 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
2303 h->cmdbuf[h->cmdidx++] = regsel;
2304 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
2307 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2310 static int stlink_usb_get_rw_status(void *handle)
2312 struct stlink_usb_handle_s *h = handle;
2316 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2319 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2321 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2322 if (h->version.flags & STLINK_F_HAS_GETLASTRWSTATUS2) {
2323 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS2;
2324 return stlink_usb_xfer_errcheck(handle, h->databuf, 12);
2326 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
2327 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2332 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
2336 uint16_t read_len = len;
2337 struct stlink_usb_handle_s *h = handle;
2341 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2342 if (len > stlink_usb_block(h)) {
2343 LOG_DEBUG("max buffer (%d) length exceeded", stlink_usb_block(h));
2347 stlink_usb_init_buffer(handle, h->rx_ep, read_len);
2349 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2350 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
2351 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2353 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2356 /* we need to fix read length for single bytes */
2360 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, read_len);
2362 if (res != ERROR_OK)
2365 memcpy(buffer, h->databuf, len);
2367 return stlink_usb_get_rw_status(handle);
2371 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
2372 const uint8_t *buffer)
2375 struct stlink_usb_handle_s *h = handle;
2379 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2380 if (len > stlink_usb_block(h)) {
2381 LOG_DEBUG("max buffer length (%d) exceeded", stlink_usb_block(h));
2385 stlink_usb_init_buffer(handle, h->tx_ep, len);
2387 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2388 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
2389 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2391 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2394 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2396 if (res != ERROR_OK)
2399 return stlink_usb_get_rw_status(handle);
2403 static int stlink_usb_read_mem16(void *handle, uint32_t addr, uint16_t len,
2407 struct stlink_usb_handle_s *h = handle;
2411 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2412 return ERROR_COMMAND_NOTFOUND;
2414 /* data must be a multiple of 2 and half-word aligned */
2415 if (len % 2 || addr % 2) {
2416 LOG_DEBUG("Invalid data alignment");
2417 return ERROR_TARGET_UNALIGNED_ACCESS;
2420 stlink_usb_init_buffer(handle, h->rx_ep, len);
2422 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2423 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READMEM_16BIT;
2424 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2426 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2429 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2431 if (res != ERROR_OK)
2434 memcpy(buffer, h->databuf, len);
2436 return stlink_usb_get_rw_status(handle);
2440 static int stlink_usb_write_mem16(void *handle, uint32_t addr, uint16_t len,
2441 const uint8_t *buffer)
2444 struct stlink_usb_handle_s *h = handle;
2448 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2449 return ERROR_COMMAND_NOTFOUND;
2451 /* data must be a multiple of 2 and half-word aligned */
2452 if (len % 2 || addr % 2) {
2453 LOG_DEBUG("Invalid data alignment");
2454 return ERROR_TARGET_UNALIGNED_ACCESS;
2457 stlink_usb_init_buffer(handle, h->tx_ep, len);
2459 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2460 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEMEM_16BIT;
2461 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2463 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2466 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2468 if (res != ERROR_OK)
2471 return stlink_usb_get_rw_status(handle);
2475 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
2479 struct stlink_usb_handle_s *h = handle;
2483 /* data must be a multiple of 4 and word aligned */
2484 if (len % 4 || addr % 4) {
2485 LOG_DEBUG("Invalid data alignment");
2486 return ERROR_TARGET_UNALIGNED_ACCESS;
2489 stlink_usb_init_buffer(handle, h->rx_ep, len);
2491 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2492 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
2493 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2495 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2498 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2500 if (res != ERROR_OK)
2503 memcpy(buffer, h->databuf, len);
2505 return stlink_usb_get_rw_status(handle);
2509 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
2510 const uint8_t *buffer)
2513 struct stlink_usb_handle_s *h = handle;
2517 /* data must be a multiple of 4 and word aligned */
2518 if (len % 4 || addr % 4) {
2519 LOG_DEBUG("Invalid data alignment");
2520 return ERROR_TARGET_UNALIGNED_ACCESS;
2523 stlink_usb_init_buffer(handle, h->tx_ep, len);
2525 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2526 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
2527 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2529 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2532 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2534 if (res != ERROR_OK)
2537 return stlink_usb_get_rw_status(handle);
2540 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
2542 uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
2543 if (max_tar_block == 0)
2545 return max_tar_block;
2548 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
2549 uint32_t count, uint8_t *buffer)
2551 int retval = ERROR_OK;
2552 uint32_t bytes_remaining;
2554 struct stlink_usb_handle_s *h = handle;
2556 /* calculate byte count */
2559 /* switch to 8 bit if stlink does not support 16 bit memory read */
2560 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2565 bytes_remaining = (size != 1) ?
2566 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2568 if (count < bytes_remaining)
2569 bytes_remaining = count;
2572 * all stlink support 8/32bit memory read/writes and only from
2573 * stlink V2J26 there is support for 16 bit memory read/write.
2574 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2579 /* When in jtag mode the stlink uses the auto-increment functionality.
2580 * However it expects us to pass the data correctly, this includes
2581 * alignment and any page boundaries. We already do this as part of the
2582 * adi_v5 implementation, but the stlink is a hla adapter and so this
2583 * needs implementing manually.
2584 * currently this only affects jtag mode, according to ST they do single
2585 * access in SWD mode - but this may change and so we do it for both modes */
2587 /* we first need to check for any unaligned bytes */
2588 if (addr & (size - 1)) {
2590 uint32_t head_bytes = size - (addr & (size - 1));
2591 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
2592 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2593 usleep((1<<retries++) * 1000);
2596 if (retval != ERROR_OK)
2598 buffer += head_bytes;
2600 count -= head_bytes;
2601 bytes_remaining -= head_bytes;
2604 if (bytes_remaining & (size - 1))
2605 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
2607 retval = stlink_usb_read_mem16(handle, addr, bytes_remaining, buffer);
2609 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
2611 retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
2613 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2614 usleep((1<<retries++) * 1000);
2617 if (retval != ERROR_OK)
2620 buffer += bytes_remaining;
2621 addr += bytes_remaining;
2622 count -= bytes_remaining;
2628 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
2629 uint32_t count, const uint8_t *buffer)
2631 int retval = ERROR_OK;
2632 uint32_t bytes_remaining;
2634 struct stlink_usb_handle_s *h = handle;
2636 /* calculate byte count */
2639 /* switch to 8 bit if stlink does not support 16 bit memory read */
2640 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2645 bytes_remaining = (size != 1) ?
2646 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2648 if (count < bytes_remaining)
2649 bytes_remaining = count;
2652 * all stlink support 8/32bit memory read/writes and only from
2653 * stlink V2J26 there is support for 16 bit memory read/write.
2654 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2659 /* When in jtag mode the stlink uses the auto-increment functionality.
2660 * However it expects us to pass the data correctly, this includes
2661 * alignment and any page boundaries. We already do this as part of the
2662 * adi_v5 implementation, but the stlink is a hla adapter and so this
2663 * needs implementing manually.
2664 * currently this only affects jtag mode, according to ST they do single
2665 * access in SWD mode - but this may change and so we do it for both modes */
2667 /* we first need to check for any unaligned bytes */
2668 if (addr & (size - 1)) {
2670 uint32_t head_bytes = size - (addr & (size - 1));
2671 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
2672 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2673 usleep((1<<retries++) * 1000);
2676 if (retval != ERROR_OK)
2678 buffer += head_bytes;
2680 count -= head_bytes;
2681 bytes_remaining -= head_bytes;
2684 if (bytes_remaining & (size - 1))
2685 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
2687 retval = stlink_usb_write_mem16(handle, addr, bytes_remaining, buffer);
2689 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
2692 retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
2693 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2694 usleep((1<<retries++) * 1000);
2697 if (retval != ERROR_OK)
2700 buffer += bytes_remaining;
2701 addr += bytes_remaining;
2702 count -= bytes_remaining;
2709 static int stlink_usb_override_target(const char *targetname)
2711 return !strcmp(targetname, "cortex_m");
2714 static int stlink_speed_swim(void *handle, int khz, bool query)
2719 we only have low and high speed...
2720 before changing speed the SWIM_CSR HS bit
2724 retval = stlink_swim_speed(handle, (khz < SWIM_FREQ_HIGH) ? 0 : 1);
2725 if (retval != ERROR_OK)
2726 LOG_ERROR("Unable to set adapter speed");
2729 return (khz < SWIM_FREQ_HIGH) ? SWIM_FREQ_LOW : SWIM_FREQ_HIGH;
2732 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
2735 int speed_index = -1;
2736 int speed_diff = INT_MAX;
2737 int last_valid_speed = -1;
2740 for (i = 0; i < map_size; i++) {
2743 last_valid_speed = i;
2744 if (khz == map[i].speed) {
2748 int current_diff = khz - map[i].speed;
2749 /* get abs value for comparison */
2750 current_diff = (current_diff > 0) ? current_diff : -current_diff;
2751 if ((current_diff < speed_diff) && khz >= map[i].speed) {
2752 speed_diff = current_diff;
2758 if (speed_index == -1) {
2759 /* this will only be here if we cannot match the slow speed.
2760 * use the slowest speed we support.*/
2761 speed_index = last_valid_speed;
2763 } else if (i == map_size)
2766 if (!match && query) {
2767 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz",
2768 khz, map[speed_index].speed);
2774 static int stlink_speed_swd(void *handle, int khz, bool query)
2777 struct stlink_usb_handle_s *h = handle;
2779 /* old firmware cannot change it */
2780 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
2783 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
2784 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
2787 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
2788 if (result != ERROR_OK) {
2789 LOG_ERROR("Unable to set adapter speed");
2794 return stlink_khz_to_speed_map_swd[speed_index].speed;
2797 static int stlink_speed_jtag(void *handle, int khz, bool query)
2800 struct stlink_usb_handle_s *h = handle;
2802 /* old firmware cannot change it */
2803 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
2806 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2807 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2810 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2811 if (result != ERROR_OK) {
2812 LOG_ERROR("Unable to set adapter speed");
2817 return stlink_khz_to_speed_map_jtag[speed_index].speed;
2820 static void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2824 LOG_DEBUG("Supported clock speeds are:");
2825 for (i = 0; i < map_size; i++)
2827 LOG_DEBUG("%d kHz", map[i].speed);
2830 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map)
2832 struct stlink_usb_handle_s *h = handle;
2835 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2836 LOG_ERROR("Unknown command");
2840 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2842 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2843 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_COM_FREQ;
2844 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2846 int res = stlink_usb_xfer_errcheck(handle, h->databuf, 52);
2848 int size = h->databuf[8];
2850 if (size > STLINK_V3_MAX_FREQ_NB)
2851 size = STLINK_V3_MAX_FREQ_NB;
2853 for (i = 0; i < size; i++) {
2854 map[i].speed = le_to_h_u32(&h->databuf[12 + 4 * i]);
2855 map[i].speed_divisor = i;
2858 /* set to zero all the next entries */
2859 for (i = size; i < STLINK_V3_MAX_FREQ_NB; i++)
2865 static int stlink_set_com_freq(void *handle, bool is_jtag, unsigned int frequency)
2867 struct stlink_usb_handle_s *h = handle;
2869 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2870 LOG_ERROR("Unknown command");
2874 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2876 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2877 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_SET_COM_FREQ;
2878 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2879 h->cmdbuf[h->cmdidx++] = 0;
2881 h_u32_to_le(&h->cmdbuf[4], frequency);
2883 return stlink_usb_xfer_errcheck(handle, h->databuf, 8);
2886 static int stlink_speed_v3(void *handle, bool is_jtag, int khz, bool query)
2888 struct stlink_usb_handle_s *h = handle;
2890 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
2892 stlink_get_com_freq(h, is_jtag, map);
2894 speed_index = stlink_match_speed_map(map, ARRAY_SIZE(map), khz, query);
2897 int result = stlink_set_com_freq(h, is_jtag, map[speed_index].speed);
2898 if (result != ERROR_OK) {
2899 LOG_ERROR("Unable to set adapter speed");
2903 return map[speed_index].speed;
2906 static int stlink_speed(void *handle, int khz, bool query)
2908 struct stlink_usb_handle_s *h = handle;
2913 switch (h->st_mode) {
2914 case STLINK_MODE_DEBUG_SWIM:
2915 return stlink_speed_swim(handle, khz, query);
2916 case STLINK_MODE_DEBUG_SWD:
2917 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2918 return stlink_speed_v3(handle, false, khz, query);
2920 return stlink_speed_swd(handle, khz, query);
2922 case STLINK_MODE_DEBUG_JTAG:
2923 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2924 return stlink_speed_v3(handle, true, khz, query);
2926 return stlink_speed_jtag(handle, khz, query);
2936 static int stlink_usb_usb_close(void *handle)
2938 struct stlink_usb_handle_s *h = handle;
2943 if (h->usb_backend_priv.fd) {
2944 stlink_usb_exit_mode(h);
2945 /* do not check return code, it prevent
2946 us from closing jtag_libusb */
2947 jtag_libusb_close(h->usb_backend_priv.fd);
2957 static int stlink_tcp_close(void *handle)
2959 struct stlink_usb_handle_s *h = handle;
2965 if (h->tcp_backend_priv.connected) {
2966 if (h->tcp_backend_priv.connect_id) {
2967 stlink_usb_exit_mode(h);
2969 /* close the stlink */
2970 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_CLOSE_DEV;
2971 memset(&h->tcp_backend_priv.send_buf[1], 0, 4); /* reserved */
2972 h_u32_to_le(&h->tcp_backend_priv.send_buf[4], h->tcp_backend_priv.connect_id);
2973 ret = stlink_tcp_send_cmd(h, 8, 4, true);
2974 if (ret != ERROR_OK)
2975 LOG_ERROR("cannot close the STLINK");
2978 if (close_socket(h->tcp_backend_priv.fd) != 0)
2979 LOG_ERROR("error closing the socket, errno: %s", strerror(errno));
2982 free(h->tcp_backend_priv.send_buf);
2983 free(h->tcp_backend_priv.recv_buf);
2989 static int stlink_close(void *handle)
2992 struct stlink_usb_handle_s *h = handle;
2994 stlink_usb_close(handle);
3002 /* Compute ST-Link serial number from the device descriptor
3003 * this function will help to work-around a bug in old ST-Link/V2 DFU
3004 * the buggy DFU returns an incorrect serial in the USB descriptor
3005 * example for the following serial "57FF72067265575742132067"
3006 * - the correct descriptor serial is:
3007 * 0x32, 0x03, 0x35, 0x00, 0x37, 0x00, 0x46, 0x00, 0x46, 0x00, 0x37, 0x00, 0x32, 0x00 ...
3008 * this contains the length (0x32 = 50), the type (0x3 = DT_STRING) and the serial in unicode format
3009 * the serial part is: 0x0035, 0x0037, 0x0046, 0x0046, 0x0037, 0x0032 ... >> 57FF72 ...
3010 * this format could be read correctly by 'libusb_get_string_descriptor_ascii'
3011 * so this case is managed by libusb_helper::string_descriptor_equal
3012 * - the buggy DFU is not doing any unicode conversion and returns a raw serial data in the descriptor
3013 * 0x1a, 0x03, 0x57, 0x00, 0xFF, 0x00, 0x72, 0x00 ...
3015 * based on the length (0x1a = 26) we could easily decide if we have to fixup the serial
3016 * and then we have just to convert the raw data into printable characters using sprintf
3018 static char *stlink_usb_get_alternate_serial(struct libusb_device_handle *device,
3019 struct libusb_device_descriptor *dev_desc)
3022 unsigned char desc_serial[(STLINK_SERIAL_LEN + 1) * 2];
3024 if (dev_desc->iSerialNumber == 0)
3027 /* get the LANGID from String Descriptor Zero */
3028 usb_retval = libusb_get_string_descriptor(device, 0, 0, desc_serial,
3029 sizeof(desc_serial));
3031 if (usb_retval < LIBUSB_SUCCESS) {
3032 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
3033 libusb_error_name(usb_retval), usb_retval);
3035 } else if (usb_retval < 4) {
3036 /* the size should be least 4 bytes to contain a minimum of 1 supported LANGID */
3037 LOG_ERROR("could not get the LANGID");
3041 uint32_t langid = desc_serial[2] | (desc_serial[3] << 8);
3043 /* get the serial */
3044 usb_retval = libusb_get_string_descriptor(device, dev_desc->iSerialNumber,
3045 langid, desc_serial, sizeof(desc_serial));
3047 unsigned char len = desc_serial[0];
3049 if (usb_retval < LIBUSB_SUCCESS) {
3050 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
3051 libusb_error_name(usb_retval), usb_retval);
3053 } else if (desc_serial[1] != LIBUSB_DT_STRING || len > usb_retval) {
3054 LOG_ERROR("invalid string in ST-LINK USB serial descriptor");
3058 if (len == ((STLINK_SERIAL_LEN + 1) * 2)) {
3059 /* good ST-Link adapter, this case is managed by
3060 * libusb::libusb_get_string_descriptor_ascii */
3062 } else if (len != ((STLINK_SERIAL_LEN / 2 + 1) * 2)) {
3063 LOG_ERROR("unexpected serial length (%d) in descriptor", len);
3067 /* else (len == 26) => buggy ST-Link */
3069 char *alternate_serial = malloc((STLINK_SERIAL_LEN + 1) * sizeof(char));
3070 if (!alternate_serial)
3073 for (unsigned int i = 0; i < STLINK_SERIAL_LEN; i += 2)
3074 sprintf(alternate_serial + i, "%02X", desc_serial[i + 2]);
3076 alternate_serial[STLINK_SERIAL_LEN] = '\0';
3078 return alternate_serial;
3082 static int stlink_usb_usb_open(void *handle, struct hl_interface_param_s *param)
3084 struct stlink_usb_handle_s *h = handle;
3085 int err, retry_count = 1;
3087 h->cmdbuf = malloc(STLINK_SG_SIZE);
3088 h->databuf = malloc(STLINK_DATA_SIZE);
3090 if (!h->cmdbuf || !h->databuf)
3094 On certain host USB configurations(e.g. MacBook Air)
3095 STLINKv2 dongle seems to have its FW in a funky state if,
3096 after plugging it in, you try to use openocd with it more
3097 then once (by launching and closing openocd). In cases like
3098 that initial attempt to read the FW info via
3099 stlink_usb_version will fail and the device has to be reset
3100 in order to become operational.
3103 if (jtag_libusb_open(param->vid, param->pid, param->serial,
3104 &h->usb_backend_priv.fd, stlink_usb_get_alternate_serial) != ERROR_OK) {
3105 LOG_ERROR("open failed");
3109 jtag_libusb_set_configuration(h->usb_backend_priv.fd, 0);
3111 if (libusb_claim_interface(h->usb_backend_priv.fd, 0) != ERROR_OK) {
3112 LOG_DEBUG("claim interface failed");
3116 /* RX EP is common for all versions */
3117 h->rx_ep = STLINK_RX_EP;
3120 if (jtag_libusb_get_pid(libusb_get_device(h->usb_backend_priv.fd), &pid) != ERROR_OK) {
3121 LOG_DEBUG("libusb_get_pid failed");
3125 /* wrap version for first read */
3128 h->version.stlink = 1;
3129 h->tx_ep = STLINK_TX_EP;
3131 case STLINK_V3_USBLOADER_PID:
3132 case STLINK_V3E_PID:
3133 case STLINK_V3S_PID:
3134 case STLINK_V3_2VCP_PID:
3135 case STLINK_V3E_NO_MSD_PID:
3136 h->version.stlink = 3;
3137 h->tx_ep = STLINK_V2_1_TX_EP;
3138 h->trace_ep = STLINK_V2_1_TRACE_EP;
3140 case STLINK_V2_1_PID:
3141 case STLINK_V2_1_NO_MSD_PID:
3142 h->version.stlink = 2;
3143 h->tx_ep = STLINK_V2_1_TX_EP;
3144 h->trace_ep = STLINK_V2_1_TRACE_EP;
3147 /* fall through - we assume V2 to be the default version*/
3149 h->version.stlink = 2;
3150 h->tx_ep = STLINK_TX_EP;
3151 h->trace_ep = STLINK_TRACE_EP;
3155 /* get the device version */
3156 err = stlink_usb_version(h);
3158 if (err == ERROR_OK) {
3160 } else if (h->version.stlink == 1 ||
3162 LOG_ERROR("read version failed");
3165 err = libusb_release_interface(h->usb_backend_priv.fd, 0);
3166 if (err != ERROR_OK) {
3167 LOG_ERROR("release interface failed");
3171 err = libusb_reset_device(h->usb_backend_priv.fd);
3172 if (err != ERROR_OK) {
3173 LOG_ERROR("reset device failed");
3177 jtag_libusb_close(h->usb_backend_priv.fd);
3179 Give the device one second to settle down and
3182 usleep(1 * 1000 * 1000);
3191 static int stlink_tcp_open(void *handle, struct hl_interface_param_s *param)
3193 struct stlink_usb_handle_s *h = handle;
3196 /* SWIM is not supported using stlink-server */
3197 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
3198 LOG_ERROR("stlink-server does not support SWIM mode");
3202 h->tcp_backend_priv.send_buf = malloc(STLINK_TCP_SEND_BUFFER_SIZE);
3203 h->tcp_backend_priv.recv_buf = malloc(STLINK_TCP_RECV_BUFFER_SIZE);
3205 if (!h->tcp_backend_priv.send_buf || !h->tcp_backend_priv.recv_buf)
3208 h->cmdbuf = &h->tcp_backend_priv.send_buf[8];
3209 h->databuf = &h->tcp_backend_priv.recv_buf[4];
3211 /* configure directions */
3212 h->rx_ep = STLINK_TCP_REQUEST_READ;
3213 h->tx_ep = STLINK_TCP_REQUEST_WRITE;
3214 h->trace_ep = STLINK_TCP_REQUEST_READ_SWO;
3216 h->tcp_backend_priv.fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
3217 h->tcp_backend_priv.connected = false;
3218 h->tcp_backend_priv.device_id = 0;
3219 h->tcp_backend_priv.connect_id = 0;
3221 if (h->tcp_backend_priv.fd == -1) {
3222 LOG_ERROR("error creating the socket, errno: %s", strerror(errno));
3226 struct sockaddr_in serv;
3227 memset(&serv, 0, sizeof(struct sockaddr_in));
3228 serv.sin_family = AF_INET;
3229 serv.sin_port = htons(param->stlink_tcp_port);
3230 serv.sin_addr.s_addr = inet_addr("127.0.0.1");
3232 LOG_DEBUG("socket : %x", h->tcp_backend_priv.fd);
3235 if (setsockopt(h->tcp_backend_priv.fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&optval, sizeof(int)) == -1) {
3236 LOG_ERROR("cannot set sock option 'TCP_NODELAY', errno: %s", strerror(errno));
3240 optval = STLINK_TCP_RECV_BUFFER_SIZE;
3241 if (setsockopt(h->tcp_backend_priv.fd, SOL_SOCKET, SO_RCVBUF, (const void *)&optval, sizeof(int)) == -1) {
3242 LOG_ERROR("cannot set sock option 'SO_RCVBUF', errno: %s", strerror(errno));
3246 optval = STLINK_TCP_SEND_BUFFER_SIZE;
3247 if (setsockopt(h->tcp_backend_priv.fd, SOL_SOCKET, SO_SNDBUF, (const void *)&optval, sizeof(int)) == -1) {
3248 LOG_ERROR("cannot set sock option 'SO_SNDBUF', errno: %s", strerror(errno));
3252 if (connect(h->tcp_backend_priv.fd, (const struct sockaddr *)&serv, sizeof(serv)) == -1) {
3253 LOG_ERROR("cannot connect to stlink server, errno: %s", strerror(errno));
3257 h->tcp_backend_priv.connected = true;
3259 LOG_INFO("connected to stlink-server");
3261 /* print stlink-server version */
3262 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_GET_SERVER_VERSION;
3263 h->tcp_backend_priv.send_buf[1] = OPENOCD_STLINK_TCP_API_VERSION;
3264 memset(&h->tcp_backend_priv.send_buf[2], 0, 2); /* reserved */
3265 ret = stlink_tcp_send_cmd(h, 4, 16, false);
3266 if (ret != ERROR_OK) {
3267 LOG_ERROR("cannot get the stlink-server version");
3271 uint32_t api_ver = le_to_h_u32(&h->tcp_backend_priv.recv_buf[0]);
3272 uint32_t ver_major = le_to_h_u32(&h->tcp_backend_priv.recv_buf[4]);
3273 uint32_t ver_minor = le_to_h_u32(&h->tcp_backend_priv.recv_buf[8]);
3274 uint32_t ver_build = le_to_h_u32(&h->tcp_backend_priv.recv_buf[12]);
3275 LOG_INFO("stlink-server API v%d, version %d.%d.%d",
3276 api_ver, ver_major, ver_minor, ver_build);
3278 /* in stlink-server API v1 sending more than 1428 bytes will cause stlink-server
3279 * to crash in windows: select a safe default value (1K) */
3281 h->max_mem_packet = (1 << 10);
3283 /* refresh stlink list (re-enumerate) */
3284 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_REFRESH_DEVICE_LIST;
3285 h->tcp_backend_priv.send_buf[1] = 0; /* don't clear the list, just refresh it */
3286 ret = stlink_tcp_send_cmd(h, 2, 4, true);
3287 if (ret != ERROR_OK)
3290 /* get the number of connected stlinks */
3291 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_GET_NB_DEV;
3292 ret = stlink_tcp_send_cmd(h, 1, 4, false);
3293 if (ret != ERROR_OK)
3296 uint32_t connected_stlinks = le_to_h_u32(h->tcp_backend_priv.recv_buf);
3298 if (connected_stlinks == 0) {
3299 LOG_ERROR("no ST-LINK detected");
3303 LOG_DEBUG("%d ST-LINK detected", connected_stlinks);
3305 if (connected_stlinks > 255) {
3306 LOG_WARNING("STLink server cannot handle more than 255 ST-LINK connected");
3307 connected_stlinks = 255;
3310 /* list all connected ST-Link and seek for the requested vid:pid and serial */
3311 char serial[STLINK_TCP_SERIAL_SIZE + 1] = {0};
3312 uint8_t stlink_used;
3313 bool stlink_id_matched = false;
3314 bool stlink_serial_matched = (!param->serial);
3316 for (uint32_t stlink_id = 0; stlink_id < connected_stlinks; stlink_id++) {
3317 /* get the stlink info */
3318 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_GET_DEV_INFO;
3319 h->tcp_backend_priv.send_buf[1] = (uint8_t)stlink_id;
3320 memset(&h->tcp_backend_priv.send_buf[2], 0, 2); /* reserved */
3321 h_u32_to_le(&h->tcp_backend_priv.send_buf[4], 41); /* size of TDeviceInfo2 */
3322 ret = stlink_tcp_send_cmd(h, 8, 45, true);
3323 if (ret != ERROR_OK)
3326 h->tcp_backend_priv.device_id = le_to_h_u32(&h->tcp_backend_priv.recv_buf[4]);
3327 memcpy(serial, &h->tcp_backend_priv.recv_buf[8], STLINK_TCP_SERIAL_SIZE);
3328 h->vid = le_to_h_u16(&h->tcp_backend_priv.recv_buf[40]);
3329 h->pid = le_to_h_u16(&h->tcp_backend_priv.recv_buf[42]);
3330 stlink_used = h->tcp_backend_priv.recv_buf[44];
3332 /* check the vid:pid */
3333 for (int i = 0; param->vid[i]; i++) {
3334 if (param->vid[i] == h->vid && param->pid[i] == h->pid) {
3335 stlink_id_matched = true;
3340 if (!stlink_id_matched)
3343 /* check the serial if specified */
3344 if (param->serial) {
3345 /* ST-Link server fixes the buggy serial returned by old ST-Link DFU
3346 * for further details refer to stlink_usb_get_alternate_serial
3347 * so if the user passes the buggy serial, we need to fix it before
3348 * comparing with the serial returned by ST-Link server */
3349 if (strlen(param->serial) == STLINK_SERIAL_LEN / 2) {
3350 char fixed_serial[STLINK_SERIAL_LEN + 1];
3352 for (unsigned int i = 0; i < STLINK_SERIAL_LEN; i += 2)
3353 sprintf(fixed_serial + i, "%02X", param->serial[i / 2]);
3355 fixed_serial[STLINK_SERIAL_LEN] = '\0';
3357 stlink_serial_matched = strcmp(fixed_serial, serial) == 0;
3359 stlink_serial_matched = strcmp(param->serial, serial) == 0;
3362 if (!stlink_serial_matched)
3363 LOG_DEBUG("Device serial number '%s' doesn't match requested serial '%s'",
3364 serial, param->serial);
3365 else /* exit the search loop if there is match */
3369 if (!stlink_id_matched) {
3370 LOG_ERROR("ST-LINK open failed (vid/pid mismatch)");
3374 if (!stlink_serial_matched) {
3375 LOG_ERROR("ST-LINK open failed (serial mismatch)");
3379 /* check if device is 'exclusively' used by another application */
3381 LOG_ERROR("the selected device is already used");
3385 LOG_DEBUG("transport: vid: 0x%04x pid: 0x%04x serial: %s", h->vid, h->pid, serial);
3387 /* now let's open the stlink */
3388 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_OPEN_DEV;
3389 memset(&h->tcp_backend_priv.send_buf[1], 0, 4); /* reserved */
3390 h_u32_to_le(&h->tcp_backend_priv.send_buf[4], h->tcp_backend_priv.device_id);
3391 ret = stlink_tcp_send_cmd(h, 8, 8, true);
3392 if (ret != ERROR_OK)
3395 h->tcp_backend_priv.connect_id = le_to_h_u32(&h->tcp_backend_priv.recv_buf[4]);
3397 /* get stlink version */
3398 return stlink_usb_version(h);
3401 static struct stlink_backend_s stlink_usb_backend = {
3402 .open = stlink_usb_usb_open,
3403 .close = stlink_usb_usb_close,
3404 .xfer_noerrcheck = stlink_usb_usb_xfer_noerrcheck,
3405 .read_trace = stlink_usb_usb_read_trace,
3408 static struct stlink_backend_s stlink_tcp_backend = {
3409 .open = stlink_tcp_open,
3410 .close = stlink_tcp_close,
3411 .xfer_noerrcheck = stlink_tcp_xfer_noerrcheck,
3412 .read_trace = stlink_tcp_read_trace,
3415 static int stlink_open(struct hl_interface_param_s *param, enum stlink_mode mode, void **fd)
3417 struct stlink_usb_handle_s *h;
3419 LOG_DEBUG("stlink_open");
3421 h = calloc(1, sizeof(struct stlink_usb_handle_s));
3424 LOG_DEBUG("malloc failed");
3430 for (unsigned i = 0; param->vid[i]; i++) {
3431 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
3432 h->st_mode, param->vid[i], param->pid[i],
3433 param->serial ? param->serial : "");
3436 if (param->use_stlink_tcp)
3437 h->backend = &stlink_tcp_backend;
3439 h->backend = &stlink_usb_backend;
3441 if (stlink_usb_open(h, param) != ERROR_OK)
3444 /* check if mode is supported */
3447 switch (h->st_mode) {
3448 case STLINK_MODE_DEBUG_SWD:
3449 if (h->version.jtag_api == STLINK_JTAG_API_V1)
3452 case STLINK_MODE_DEBUG_JTAG:
3453 if (h->version.jtag == 0)
3456 case STLINK_MODE_DEBUG_SWIM:
3457 if (h->version.swim == 0)
3465 if (err != ERROR_OK) {
3466 LOG_ERROR("mode (transport) not supported by device");
3470 /* initialize the debug hardware */
3471 err = stlink_usb_init_mode(h, param->connect_under_reset, param->initial_interface_speed);
3473 if (err != ERROR_OK) {
3474 LOG_ERROR("init mode failed (unable to connect to the target)");
3478 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
3479 err = stlink_swim_enter(h);
3480 if (err != ERROR_OK) {
3481 LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
3485 h->max_mem_packet = STLINK_DATA_SIZE;
3489 /* set max_mem_packet if it was not set by the low-level interface */
3490 if (h->max_mem_packet == 0) {
3491 /* get cpuid, so we can determine the max page size
3492 * start with a safe default */
3493 h->max_mem_packet = (1 << 10);
3496 stlink_usb_open_ap(h, 0);
3497 err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
3498 if (err == ERROR_OK) {
3499 uint32_t cpuid = le_to_h_u32(buffer);
3500 int i = (cpuid >> 4) & 0xf;
3501 if (i == 4 || i == 3) {
3502 /* Cortex-M3/M4 has 4096 bytes autoincrement range */
3503 h->max_mem_packet = (1 << 12);
3507 LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
3519 static int stlink_usb_hl_open(struct hl_interface_param_s *param, void **fd)
3521 return stlink_open(param, stlink_get_mode(param->transport), fd);
3524 static int stlink_config_trace(void *handle, bool enabled,
3525 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
3526 unsigned int *trace_freq, unsigned int traceclkin_freq,
3527 uint16_t *prescaler)
3529 struct stlink_usb_handle_s *h = handle;
3531 if (!(h->version.flags & STLINK_F_HAS_TRACE)) {
3532 LOG_ERROR("The attached ST-LINK version doesn't support trace");
3537 stlink_usb_trace_disable(h);
3544 if (pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART) {
3545 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
3549 unsigned int max_trace_freq = (h->version.stlink == 3) ?
3550 STLINK_V3_TRACE_MAX_HZ : STLINK_TRACE_MAX_HZ;
3552 /* Only concern ourselves with the frequency if the STlink is processing it. */
3553 if (*trace_freq > max_trace_freq) {
3554 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
3560 *trace_freq = max_trace_freq;
3562 unsigned int presc = (traceclkin_freq + *trace_freq / 2) / *trace_freq;
3563 if (presc == 0 || presc > TPIU_ACPR_MAX_SWOSCALER + 1) {
3564 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
3569 /* Probe's UART speed must be within 3% of the TPIU's SWO baud rate. */
3570 unsigned int max_deviation = (traceclkin_freq * 3) / 100;
3571 if (presc * *trace_freq < traceclkin_freq - max_deviation ||
3572 presc * *trace_freq > traceclkin_freq + max_deviation) {
3573 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
3580 stlink_usb_trace_disable(h);
3582 h->trace.source_hz = *trace_freq;
3584 return stlink_usb_trace_enable(h);
3588 static int stlink_usb_init_access_port(void *handle, unsigned char ap_num)
3590 struct stlink_usb_handle_s *h = handle;
3594 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3595 return ERROR_COMMAND_NOTFOUND;
3597 LOG_DEBUG_IO("init ap_num = %d", ap_num);
3598 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3599 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3600 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_INIT_AP;
3601 h->cmdbuf[h->cmdidx++] = ap_num;
3603 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3607 static int stlink_usb_close_access_port(void *handle, unsigned char ap_num)
3609 struct stlink_usb_handle_s *h = handle;
3613 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3614 return ERROR_COMMAND_NOTFOUND;
3616 LOG_DEBUG_IO("close ap_num = %d", ap_num);
3617 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3618 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3619 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_CLOSE_AP_DBG;
3620 h->cmdbuf[h->cmdidx++] = ap_num;
3622 /* ignore incorrectly returned error on bogus FW */
3623 if (h->version.flags & STLINK_F_FIX_CLOSE_AP)
3624 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3626 return stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
3631 static int stlink_read_dap_register(void *handle, unsigned short dap_port,
3632 unsigned short addr, uint32_t *val)
3634 struct stlink_usb_handle_s *h = handle;
3639 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3640 return ERROR_COMMAND_NOTFOUND;
3642 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3643 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3644 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_DAP_REG;
3645 h_u16_to_le(&h->cmdbuf[2], dap_port);
3646 h_u16_to_le(&h->cmdbuf[4], addr);
3648 retval = stlink_usb_xfer_errcheck(handle, h->databuf, 8);
3649 *val = le_to_h_u32(h->databuf + 4);
3650 LOG_DEBUG_IO("dap_port_read = %d, addr = 0x%x, value = 0x%" PRIx32, dap_port, addr, *val);
3655 static int stlink_write_dap_register(void *handle, unsigned short dap_port,
3656 unsigned short addr, uint32_t val)
3658 struct stlink_usb_handle_s *h = handle;
3662 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3663 return ERROR_COMMAND_NOTFOUND;
3665 LOG_DEBUG_IO("dap_write port = %d, addr = 0x%x, value = 0x%" PRIx32, dap_port, addr, val);
3666 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3667 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3668 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITE_DAP_REG;
3669 h_u16_to_le(&h->cmdbuf[2], dap_port);
3670 h_u16_to_le(&h->cmdbuf[4], addr);
3671 h_u32_to_le(&h->cmdbuf[6], val);
3672 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3676 struct hl_layout_api_s stlink_usb_layout_api = {
3678 .open = stlink_usb_hl_open,
3680 .close = stlink_close,
3682 .idcode = stlink_usb_idcode,
3684 .state = stlink_usb_state,
3686 .reset = stlink_usb_reset,
3688 .assert_srst = stlink_usb_assert_srst,
3690 .run = stlink_usb_run,
3692 .halt = stlink_usb_halt,
3694 .step = stlink_usb_step,
3696 .read_regs = stlink_usb_read_regs,
3698 .read_reg = stlink_usb_read_reg,
3700 .write_reg = stlink_usb_write_reg,
3702 .read_mem = stlink_usb_read_mem,
3704 .write_mem = stlink_usb_write_mem,
3706 .write_debug_reg = stlink_usb_write_debug_reg,
3708 .override_target = stlink_usb_override_target,
3710 .speed = stlink_speed,
3712 .config_trace = stlink_config_trace,
3714 .poll_trace = stlink_usb_trace_read,
3717 /*****************************************************************************
3718 * DAP direct interface
3721 static struct stlink_usb_handle_s *stlink_dap_handle;
3722 static struct hl_interface_param_s stlink_dap_param;
3723 static DECLARE_BITMAP(opened_ap, DP_APSEL_MAX + 1);
3724 static int stlink_dap_error = ERROR_OK;
3726 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3730 static int stlink_dap_record_error(int error)
3732 if (stlink_dap_error == ERROR_OK)
3733 stlink_dap_error = error;
3738 static int stlink_dap_get_and_clear_error(void)
3740 int retval = stlink_dap_error;
3741 stlink_dap_error = ERROR_OK;
3745 static int stlink_usb_open_ap(void *handle, unsigned short apsel)
3747 struct stlink_usb_handle_s *h = handle;
3750 /* nothing to do on old versions */
3751 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3754 if (apsel > DP_APSEL_MAX)
3757 if (test_bit(apsel, opened_ap))
3760 retval = stlink_usb_init_access_port(h, apsel);
3761 if (retval != ERROR_OK)
3764 LOG_DEBUG("AP %d enabled", apsel);
3765 set_bit(apsel, opened_ap);
3769 static int stlink_dap_open_ap(unsigned short apsel)
3771 return stlink_usb_open_ap(stlink_dap_handle, apsel);
3775 static int stlink_dap_closeall_ap(void)
3779 /* nothing to do on old versions */
3780 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3783 for (apsel = 0; apsel <= DP_APSEL_MAX; apsel++) {
3784 if (!test_bit(apsel, opened_ap))
3786 retval = stlink_usb_close_access_port(stlink_dap_handle, apsel);
3787 if (retval != ERROR_OK)
3789 clear_bit(apsel, opened_ap);
3795 static int stlink_dap_reinit_interface(void)
3800 * On JTAG only, it should be enough to call stlink_usb_reset(). But on
3801 * some firmware version it does not work as expected, and there is no
3802 * equivalent for SWD.
3803 * At least for now, to reset the interface quit from JTAG/SWD mode then
3804 * select the mode again.
3807 if (!stlink_dap_handle->reconnect_pending) {
3808 stlink_dap_handle->reconnect_pending = true;
3809 stlink_usb_mode_leave(stlink_dap_handle, stlink_dap_handle->st_mode);
3812 retval = stlink_usb_mode_enter(stlink_dap_handle, stlink_dap_handle->st_mode);
3813 if (retval != ERROR_OK)
3816 stlink_dap_handle->reconnect_pending = false;
3817 /* on new FW, calling mode-leave closes all the opened AP; reopen them! */
3818 if (stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT)
3819 for (int apsel = 0; apsel <= DP_APSEL_MAX; apsel++)
3820 if (test_bit(apsel, opened_ap)) {
3821 clear_bit(apsel, opened_ap);
3822 stlink_dap_open_ap(apsel);
3828 static int stlink_dap_op_connect(struct adiv5_dap *dap)
3833 LOG_INFO("stlink_dap_op_connect(%sconnect)", dap->do_reconnect ? "re" : "");
3835 /* Check if we should reset srst already when connecting, but not if reconnecting. */
3836 if (!dap->do_reconnect) {
3837 enum reset_types jtag_reset_config = jtag_get_reset_config();
3839 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3840 if (jtag_reset_config & RESET_SRST_NO_GATING)
3841 adapter_assert_reset();
3843 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3847 dap->do_reconnect = false;
3848 dap_invalidate_cache(dap);
3850 retval = dap_dp_init(dap);
3851 if (retval != ERROR_OK) {
3852 dap->do_reconnect = true;
3856 retval = stlink_usb_idcode(stlink_dap_handle, &idcode);
3857 if (retval == ERROR_OK)
3858 LOG_INFO("%s %#8.8" PRIx32,
3859 (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) ? "JTAG IDCODE" : "SWD DPIDR",
3862 dap->do_reconnect = true;
3868 static int stlink_dap_check_reconnect(struct adiv5_dap *dap)
3872 if (!dap->do_reconnect)
3875 retval = stlink_dap_reinit_interface();
3876 if (retval != ERROR_OK)
3879 return stlink_dap_op_connect(dap);
3883 static int stlink_dap_op_send_sequence(struct adiv5_dap *dap, enum swd_special_seq seq)
3885 /* Ignore the request */
3890 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3896 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3897 if (reg & 0x000000F0) {
3898 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3899 return ERROR_COMMAND_NOTFOUND;
3902 retval = stlink_dap_check_reconnect(dap);
3903 if (retval != ERROR_OK)
3906 data = data ? data : &dummy;
3907 if (stlink_dap_handle->version.flags & STLINK_F_QUIRK_JTAG_DP_READ
3908 && stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) {
3909 /* Quirk required in JTAG. Read RDBUFF to get the data */
3910 retval = stlink_read_dap_register(stlink_dap_handle,
3911 STLINK_DEBUG_PORT_ACCESS, reg, &dummy);
3912 if (retval == ERROR_OK)
3913 retval = stlink_read_dap_register(stlink_dap_handle,
3914 STLINK_DEBUG_PORT_ACCESS, DP_RDBUFF, data);
3916 retval = stlink_read_dap_register(stlink_dap_handle,
3917 STLINK_DEBUG_PORT_ACCESS, reg, data);
3920 return stlink_dap_record_error(retval);
3924 static int stlink_dap_op_queue_dp_write(struct adiv5_dap *dap, unsigned reg,
3929 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3930 if (reg & 0x000000F0) {
3931 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3932 return ERROR_COMMAND_NOTFOUND;
3935 if (reg == DP_SELECT && (data & DP_SELECT_DPBANK) != 0) {
3936 /* ignored if STLINK_F_HAS_DPBANKSEL, not properly managed otherwise */
3937 LOG_DEBUG("Ignoring DPBANKSEL while write SELECT");
3938 data &= ~DP_SELECT_DPBANK;
3941 retval = stlink_dap_check_reconnect(dap);
3942 if (retval != ERROR_OK)
3945 /* ST-Link does not like that we set CORUNDETECT */
3946 if (reg == DP_CTRL_STAT)
3947 data &= ~CORUNDETECT;
3949 retval = stlink_write_dap_register(stlink_dap_handle,
3950 STLINK_DEBUG_PORT_ACCESS, reg, data);
3951 return stlink_dap_record_error(retval);
3955 static int stlink_dap_op_queue_ap_read(struct adiv5_ap *ap, unsigned reg,
3958 struct adiv5_dap *dap = ap->dap;
3962 retval = stlink_dap_check_reconnect(dap);
3963 if (retval != ERROR_OK)
3966 if (reg != AP_REG_IDR) {
3967 retval = stlink_dap_open_ap(ap->ap_num);
3968 if (retval != ERROR_OK)
3971 data = data ? data : &dummy;
3972 retval = stlink_read_dap_register(stlink_dap_handle, ap->ap_num, reg,
3974 dap->stlink_flush_ap_write = false;
3975 return stlink_dap_record_error(retval);
3979 static int stlink_dap_op_queue_ap_write(struct adiv5_ap *ap, unsigned reg,
3982 struct adiv5_dap *dap = ap->dap;
3985 retval = stlink_dap_check_reconnect(dap);
3986 if (retval != ERROR_OK)
3989 retval = stlink_dap_open_ap(ap->ap_num);
3990 if (retval != ERROR_OK)
3993 retval = stlink_write_dap_register(stlink_dap_handle, ap->ap_num, reg,
3995 dap->stlink_flush_ap_write = true;
3996 return stlink_dap_record_error(retval);
4000 static int stlink_dap_op_queue_ap_abort(struct adiv5_dap *dap, uint8_t *ack)
4002 LOG_WARNING("stlink_dap_op_queue_ap_abort()");
4007 static int stlink_dap_op_run(struct adiv5_dap *dap)
4009 uint32_t ctrlstat, pwrmask;
4010 int retval, saved_retval;
4012 /* Here no LOG_DEBUG. This is called continuously! */
4015 * ST-Link returns immediately after a DAP write, without waiting for it
4017 * Run a dummy read to DP_RDBUFF, as suggested in
4018 * http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka16363.html
4020 if (dap->stlink_flush_ap_write) {
4021 dap->stlink_flush_ap_write = false;
4022 retval = stlink_dap_op_queue_dp_read(dap, DP_RDBUFF, NULL);
4023 if (retval != ERROR_OK) {
4024 dap->do_reconnect = true;
4029 saved_retval = stlink_dap_get_and_clear_error();
4031 retval = stlink_dap_op_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
4032 if (retval != ERROR_OK) {
4033 dap->do_reconnect = true;
4036 retval = stlink_dap_get_and_clear_error();
4037 if (retval != ERROR_OK) {
4038 LOG_ERROR("Fail reading CTRL/STAT register. Force reconnect");
4039 dap->do_reconnect = true;
4043 if (ctrlstat & SSTICKYERR) {
4044 if (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG)
4045 retval = stlink_dap_op_queue_dp_write(dap, DP_CTRL_STAT,
4046 ctrlstat & (dap->dp_ctrl_stat | SSTICKYERR));
4048 retval = stlink_dap_op_queue_dp_write(dap, DP_ABORT, STKERRCLR);
4049 if (retval != ERROR_OK) {
4050 dap->do_reconnect = true;
4053 retval = stlink_dap_get_and_clear_error();
4054 if (retval != ERROR_OK) {
4055 dap->do_reconnect = true;
4060 /* check for power lost */
4061 pwrmask = dap->dp_ctrl_stat & (CDBGPWRUPREQ | CSYSPWRUPREQ);
4062 if ((ctrlstat & pwrmask) != pwrmask)
4063 dap->do_reconnect = true;
4065 return saved_retval;
4069 static void stlink_dap_op_quit(struct adiv5_dap *dap)
4073 retval = stlink_dap_closeall_ap();
4074 if (retval != ERROR_OK)
4075 LOG_ERROR("Error closing APs");
4078 static int stlink_swim_op_srst(void)
4080 return stlink_swim_generate_rst(stlink_dap_handle);
4083 static int stlink_swim_op_read_mem(uint32_t addr, uint32_t size,
4084 uint32_t count, uint8_t *buffer)
4087 uint32_t bytes_remaining;
4089 LOG_DEBUG_IO("read at 0x%08" PRIx32 " len %" PRIu32 "*0x%08" PRIx32, addr, size, count);
4093 bytes_remaining = (count > STLINK_DATA_SIZE) ? STLINK_DATA_SIZE : count;
4094 retval = stlink_swim_readbytes(stlink_dap_handle, addr, bytes_remaining, buffer);
4095 if (retval != ERROR_OK)
4098 buffer += bytes_remaining;
4099 addr += bytes_remaining;
4100 count -= bytes_remaining;
4106 static int stlink_swim_op_write_mem(uint32_t addr, uint32_t size,
4107 uint32_t count, const uint8_t *buffer)
4110 uint32_t bytes_remaining;
4112 LOG_DEBUG_IO("write at 0x%08" PRIx32 " len %" PRIu32 "*0x%08" PRIx32, addr, size, count);
4116 bytes_remaining = (count > STLINK_DATA_SIZE) ? STLINK_DATA_SIZE : count;
4117 retval = stlink_swim_writebytes(stlink_dap_handle, addr, bytes_remaining, buffer);
4118 if (retval != ERROR_OK)
4121 buffer += bytes_remaining;
4122 addr += bytes_remaining;
4123 count -= bytes_remaining;
4129 static int stlink_swim_op_reconnect(void)
4133 retval = stlink_usb_mode_enter(stlink_dap_handle, STLINK_MODE_DEBUG_SWIM);
4134 if (retval != ERROR_OK)
4137 return stlink_swim_resync(stlink_dap_handle);
4140 static int stlink_dap_config_trace(bool enabled,
4141 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
4142 unsigned int *trace_freq, unsigned int traceclkin_freq,
4143 uint16_t *prescaler)
4145 return stlink_config_trace(stlink_dap_handle, enabled, pin_protocol,
4146 port_size, trace_freq, traceclkin_freq,
4150 static int stlink_dap_trace_read(uint8_t *buf, size_t *size)
4152 return stlink_usb_trace_read(stlink_dap_handle, buf, size);
4156 COMMAND_HANDLER(stlink_dap_serial_command)
4158 LOG_DEBUG("stlink_dap_serial_command");
4160 if (CMD_ARGC != 1) {
4161 LOG_ERROR("Expected exactly one argument for \"st-link serial <serial-number>\".");
4162 return ERROR_COMMAND_SYNTAX_ERROR;
4165 if (stlink_dap_param.serial) {
4166 LOG_WARNING("Command \"st-link serial\" already used. Replacing previous value");
4167 free((void *)stlink_dap_param.serial);
4170 stlink_dap_param.serial = strdup(CMD_ARGV[0]);
4175 COMMAND_HANDLER(stlink_dap_vid_pid)
4177 unsigned int i, max_usb_ids = HLA_MAX_USB_IDS;
4179 if (CMD_ARGC > max_usb_ids * 2) {
4180 LOG_WARNING("ignoring extra IDs in vid_pid "
4181 "(maximum is %d pairs)", max_usb_ids);
4182 CMD_ARGC = max_usb_ids * 2;
4184 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
4185 LOG_WARNING("incomplete vid_pid configuration directive");
4186 return ERROR_COMMAND_SYNTAX_ERROR;
4188 for (i = 0; i < CMD_ARGC; i += 2) {
4189 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], stlink_dap_param.vid[i / 2]);
4190 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], stlink_dap_param.pid[i / 2]);
4193 /* null termination */
4194 stlink_dap_param.vid[i / 2] = stlink_dap_param.pid[i / 2] = 0;
4200 COMMAND_HANDLER(stlink_dap_backend_command)
4202 /* default values */
4203 bool use_stlink_tcp = false;
4204 uint16_t stlink_tcp_port = 7184;
4206 if (CMD_ARGC == 0 || CMD_ARGC > 2)
4207 return ERROR_COMMAND_SYNTAX_ERROR;
4208 else if (strcmp(CMD_ARGV[0], "usb") == 0) {
4210 return ERROR_COMMAND_SYNTAX_ERROR;
4211 /* else use_stlink_tcp = false (already the case ) */
4212 } else if (strcmp(CMD_ARGV[0], "tcp") == 0) {
4213 use_stlink_tcp = true;
4215 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], stlink_tcp_port);
4217 return ERROR_COMMAND_SYNTAX_ERROR;
4219 stlink_dap_param.use_stlink_tcp = use_stlink_tcp;
4220 stlink_dap_param.stlink_tcp_port = stlink_tcp_port;
4225 #define BYTES_PER_LINE 16
4226 COMMAND_HANDLER(stlink_dap_cmd_command)
4228 unsigned int rx_n, tx_n;
4229 struct stlink_usb_handle_s *h = stlink_dap_handle;
4232 return ERROR_COMMAND_SYNTAX_ERROR;
4234 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], rx_n);
4235 tx_n = CMD_ARGC - 1;
4236 if (tx_n > STLINK_SG_SIZE || rx_n > STLINK_DATA_SIZE) {
4237 LOG_ERROR("max %x byte sent and %d received", STLINK_SG_SIZE, STLINK_DATA_SIZE);
4238 return ERROR_COMMAND_SYNTAX_ERROR;
4241 stlink_usb_init_buffer(h, h->rx_ep, rx_n);
4243 for (unsigned int i = 0; i < tx_n; i++) {
4245 COMMAND_PARSE_NUMBER(u8, CMD_ARGV[i + 1], byte);
4246 h->cmdbuf[h->cmdidx++] = byte;
4249 int retval = stlink_usb_xfer_noerrcheck(h, h->databuf, rx_n);
4250 if (retval != ERROR_OK) {
4251 LOG_ERROR("Error %d", retval);
4255 for (unsigned int i = 0; i < rx_n; i++)
4256 command_print_sameline(CMD, "0x%02x%c", h->databuf[i],
4257 ((i == (rx_n - 1)) || ((i % BYTES_PER_LINE) == (BYTES_PER_LINE - 1))) ? '\n' : ' ');
4263 static const struct command_registration stlink_dap_subcommand_handlers[] = {
4266 .handler = stlink_dap_serial_command,
4267 .mode = COMMAND_CONFIG,
4268 .help = "set the serial number of the adapter",
4269 .usage = "<serial_number>",
4273 .handler = stlink_dap_vid_pid,
4274 .mode = COMMAND_CONFIG,
4275 .help = "USB VID and PID of the adapter",
4276 .usage = "(vid pid)+",
4280 .handler = &stlink_dap_backend_command,
4281 .mode = COMMAND_CONFIG,
4282 .help = "select which ST-Link backend to use",
4283 .usage = "usb | tcp [port]",
4287 .handler = stlink_dap_cmd_command,
4288 .mode = COMMAND_EXEC,
4289 .help = "send arbitrary command",
4290 .usage = "rx_n (tx_byte)+",
4292 COMMAND_REGISTRATION_DONE
4296 static const struct command_registration stlink_dap_command_handlers[] = {
4299 .mode = COMMAND_ANY,
4300 .help = "perform st-link management",
4301 .chain = stlink_dap_subcommand_handlers,
4304 COMMAND_REGISTRATION_DONE
4308 static int stlink_dap_init(void)
4310 enum reset_types jtag_reset_config = jtag_get_reset_config();
4311 enum stlink_mode mode;
4314 LOG_DEBUG("stlink_dap_init()");
4316 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
4317 if (jtag_reset_config & RESET_SRST_NO_GATING)
4318 stlink_dap_param.connect_under_reset = true;
4320 LOG_WARNING("\'srst_nogate\' reset_config option is required");
4323 if (transport_is_dapdirect_swd())
4324 mode = STLINK_MODE_DEBUG_SWD;
4325 else if (transport_is_dapdirect_jtag())
4326 mode = STLINK_MODE_DEBUG_JTAG;
4327 else if (transport_is_swim())
4328 mode = STLINK_MODE_DEBUG_SWIM;
4330 LOG_ERROR("Unsupported transport");
4334 retval = stlink_open(&stlink_dap_param, mode, (void **)&stlink_dap_handle);
4335 if (retval != ERROR_OK)
4338 if ((mode != STLINK_MODE_DEBUG_SWIM) &&
4339 !(stlink_dap_handle->version.flags & STLINK_F_HAS_DAP_REG)) {
4340 LOG_ERROR("ST-Link version does not support DAP direct transport");
4347 static int stlink_dap_quit(void)
4349 LOG_DEBUG("stlink_dap_quit()");
4351 free((void *)stlink_dap_param.serial);
4352 stlink_dap_param.serial = NULL;
4354 return stlink_close(stlink_dap_handle);
4358 static int stlink_dap_reset(int req_trst, int req_srst)
4360 LOG_DEBUG("stlink_dap_reset(%d)", req_srst);
4361 return stlink_usb_assert_srst(stlink_dap_handle,
4362 req_srst ? STLINK_DEBUG_APIV2_DRIVE_NRST_LOW
4363 : STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH);
4367 static int stlink_dap_speed(int speed)
4370 LOG_ERROR("RTCK not supported. Set nonzero adapter_khz.");
4371 return ERROR_JTAG_NOT_IMPLEMENTED;
4374 stlink_dap_param.initial_interface_speed = speed;
4375 stlink_speed(stlink_dap_handle, speed, false);
4380 static int stlink_dap_khz(int khz, int *jtag_speed)
4383 LOG_ERROR("RCLK not supported");
4387 *jtag_speed = stlink_speed(stlink_dap_handle, khz, true);
4392 static int stlink_dap_speed_div(int speed, int *khz)
4398 static const struct dap_ops stlink_dap_ops = {
4399 .connect = stlink_dap_op_connect,
4400 .send_sequence = stlink_dap_op_send_sequence,
4401 .queue_dp_read = stlink_dap_op_queue_dp_read,
4402 .queue_dp_write = stlink_dap_op_queue_dp_write,
4403 .queue_ap_read = stlink_dap_op_queue_ap_read,
4404 .queue_ap_write = stlink_dap_op_queue_ap_write,
4405 .queue_ap_abort = stlink_dap_op_queue_ap_abort,
4406 .run = stlink_dap_op_run,
4407 .sync = NULL, /* optional */
4408 .quit = stlink_dap_op_quit, /* optional */
4411 static const struct swim_driver stlink_swim_ops = {
4412 .srst = stlink_swim_op_srst,
4413 .read_mem = stlink_swim_op_read_mem,
4414 .write_mem = stlink_swim_op_write_mem,
4415 .reconnect = stlink_swim_op_reconnect,
4418 static const char *const stlink_dap_transport[] = { "dapdirect_swd", "dapdirect_jtag", "swim", NULL };
4420 struct adapter_driver stlink_dap_adapter_driver = {
4422 .transports = stlink_dap_transport,
4423 .commands = stlink_dap_command_handlers,
4425 .init = stlink_dap_init,
4426 .quit = stlink_dap_quit,
4427 .reset = stlink_dap_reset,
4428 .speed = stlink_dap_speed,
4429 .khz = stlink_dap_khz,
4430 .speed_div = stlink_dap_speed_div,
4431 .config_trace = stlink_dap_config_trace,
4432 .poll_trace = stlink_dap_trace_read,
4434 .dap_jtag_ops = &stlink_dap_ops,
4435 .dap_swd_ops = &stlink_dap_ops,
4436 .swim_ops = &stlink_swim_ops,