stlink: check buffer size on 16 and 32 bit memory transfer
[openocd.git] / src / jtag / drivers / stlink_usb.c
1 /***************************************************************************
2 * Copyright (C) 2020 by Tarek Bochkati *
3 * Tarek Bochkati <tarek.bouchkati@gmail.com> *
4 * *
5 * SWIM contributions by Ake Rehnman *
6 * Copyright (C) 2017 Ake Rehnman *
7 * ake.rehnman(at)gmail.com *
8 * *
9 * Copyright (C) 2011-2012 by Mathias Kuester *
10 * Mathias Kuester <kesmtp@freenet.de> *
11 * *
12 * Copyright (C) 2012 by Spencer Oliver *
13 * spen@spen-soft.co.uk *
14 * *
15 * This code is based on https://github.com/texane/stlink *
16 * *
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. *
21 * *
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. *
26 * *
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 ***************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
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>
47
48 #include <target/cortex_m.h>
49
50 #include <helper/system.h>
51
52 #ifdef HAVE_ARPA_INET_H
53 #include <arpa/inet.h>
54 #endif
55
56 #ifdef HAVE_NETINET_TCP_H
57 #include <netinet/tcp.h>
58 #endif
59
60 #include "libusb_helper.h"
61
62 #ifdef HAVE_LIBUSB1
63 #define USE_LIBUSB_ASYNCIO
64 #endif
65
66 #define STLINK_SERIAL_LEN 24
67
68 #define ENDPOINT_IN 0x80
69 #define ENDPOINT_OUT 0x00
70
71 #define STLINK_WRITE_TIMEOUT 1000
72 #define STLINK_READ_TIMEOUT 1000
73
74 #define STLINK_RX_EP (1|ENDPOINT_IN)
75 #define STLINK_TX_EP (2|ENDPOINT_OUT)
76 #define STLINK_TRACE_EP (3|ENDPOINT_IN)
77
78 #define STLINK_V2_1_TX_EP (1|ENDPOINT_OUT)
79 #define STLINK_V2_1_TRACE_EP (2|ENDPOINT_IN)
80
81 #define STLINK_SG_SIZE (31)
82 #define STLINK_DATA_SIZE (6144)
83 #define STLINK_CMD_SIZE_V2 (16)
84 #define STLINK_CMD_SIZE_V1 (10)
85
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)
95
96 /*
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.
100 *
101 * For 16 and 32bit read/writes stlink handles USB packet split and the limit
102 * is the internal buffer size of 6144 bytes.
103 * TODO: override ADIv5 layer's tar_autoincr_block that limits the transfer
104 * to 1024 or 4096 bytes
105 */
106 #define STLINK_MAX_RW8 (64)
107 #define STLINKV3_MAX_RW8 (512)
108 #define STLINK_MAX_RW16_32 STLINK_DATA_SIZE
109 #define STLINK_SWIM_DATA_SIZE STLINK_DATA_SIZE
110
111 /* "WAIT" responses will be retried (with exponential backoff) at
112 * most this many times before failing to caller.
113 */
114 #define MAX_WAIT_RETRIES 8
115
116 enum stlink_jtag_api_version {
117 STLINK_JTAG_API_V1 = 1,
118 STLINK_JTAG_API_V2,
119 STLINK_JTAG_API_V3,
120 };
121
122 enum stlink_mode {
123 STLINK_MODE_UNKNOWN = 0,
124 STLINK_MODE_DFU,
125 STLINK_MODE_MASS,
126 STLINK_MODE_DEBUG_JTAG,
127 STLINK_MODE_DEBUG_SWD,
128 STLINK_MODE_DEBUG_SWIM
129 };
130
131 /** */
132 struct stlink_usb_version {
133 /** */
134 int stlink;
135 /** */
136 int jtag;
137 /** */
138 int swim;
139 /** jtag api version supported */
140 enum stlink_jtag_api_version jtag_api;
141 /** one bit for each feature supported. See macros STLINK_F_* */
142 uint32_t flags;
143 };
144
145 struct stlink_usb_priv_s {
146 /** */
147 struct libusb_device_handle *fd;
148 /** */
149 struct libusb_transfer *trans;
150 };
151
152 struct stlink_tcp_priv_s {
153 /** */
154 int fd;
155 /** */
156 bool connected;
157 /** */
158 uint32_t device_id;
159 /** */
160 uint32_t connect_id;
161 /** */
162 uint8_t *send_buf;
163 /** */
164 uint8_t *recv_buf;
165 };
166
167 struct stlink_backend_s {
168 /** */
169 int (*open)(void *handle, struct hl_interface_param_s *param);
170 /** */
171 int (*close)(void *handle);
172 /** */
173 int (*xfer_noerrcheck)(void *handle, const uint8_t *buf, int size);
174 /** */
175 int (*read_trace)(void *handle, const uint8_t *buf, int size);
176 };
177
178 /** */
179 struct stlink_usb_handle_s {
180 /** */
181 struct stlink_backend_s *backend;
182 /** */
183 union {
184 struct stlink_usb_priv_s usb_backend_priv;
185 struct stlink_tcp_priv_s tcp_backend_priv;
186 };
187 /** */
188 uint8_t rx_ep;
189 /** */
190 uint8_t tx_ep;
191 /** */
192 uint8_t trace_ep;
193 /** */
194 uint8_t *cmdbuf;
195 /** */
196 uint8_t cmdidx;
197 /** */
198 uint8_t direction;
199 /** */
200 uint8_t *databuf;
201 /** */
202 uint32_t max_mem_packet;
203 /** */
204 enum stlink_mode st_mode;
205 /** */
206 struct stlink_usb_version version;
207 /** */
208 uint16_t vid;
209 /** */
210 uint16_t pid;
211 /** */
212 struct {
213 /** whether SWO tracing is enabled or not */
214 bool enabled;
215 /** trace module source clock */
216 uint32_t source_hz;
217 } trace;
218 /** reconnect is needed next time we try to query the
219 * status */
220 bool reconnect_pending;
221 };
222
223 /** */
224 static inline int stlink_usb_open(void *handle, struct hl_interface_param_s *param)
225 {
226 struct stlink_usb_handle_s *h = handle;
227 return h->backend->open(handle, param);
228 }
229
230 /** */
231 static inline int stlink_usb_close(void *handle)
232 {
233 struct stlink_usb_handle_s *h = handle;
234 return h->backend->close(handle);
235 }
236 /** */
237 static inline int stlink_usb_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
238 {
239 struct stlink_usb_handle_s *h = handle;
240 return h->backend->xfer_noerrcheck(handle, buf, size);
241 }
242
243 #define STLINK_SWIM_ERR_OK 0x00
244 #define STLINK_SWIM_BUSY 0x01
245 #define STLINK_DEBUG_ERR_OK 0x80
246 #define STLINK_DEBUG_ERR_FAULT 0x81
247 #define STLINK_SWD_AP_WAIT 0x10
248 #define STLINK_SWD_AP_FAULT 0x11
249 #define STLINK_SWD_AP_ERROR 0x12
250 #define STLINK_SWD_AP_PARITY_ERROR 0x13
251 #define STLINK_JTAG_GET_IDCODE_ERROR 0x09
252 #define STLINK_JTAG_WRITE_ERROR 0x0c
253 #define STLINK_JTAG_WRITE_VERIF_ERROR 0x0d
254 #define STLINK_SWD_DP_WAIT 0x14
255 #define STLINK_SWD_DP_FAULT 0x15
256 #define STLINK_SWD_DP_ERROR 0x16
257 #define STLINK_SWD_DP_PARITY_ERROR 0x17
258
259 #define STLINK_SWD_AP_WDATA_ERROR 0x18
260 #define STLINK_SWD_AP_STICKY_ERROR 0x19
261 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
262
263 #define STLINK_BAD_AP_ERROR 0x1d
264
265 #define STLINK_CORE_RUNNING 0x80
266 #define STLINK_CORE_HALTED 0x81
267 #define STLINK_CORE_STAT_UNKNOWN -1
268
269 #define STLINK_GET_VERSION 0xF1
270 #define STLINK_DEBUG_COMMAND 0xF2
271 #define STLINK_DFU_COMMAND 0xF3
272 #define STLINK_SWIM_COMMAND 0xF4
273 #define STLINK_GET_CURRENT_MODE 0xF5
274 #define STLINK_GET_TARGET_VOLTAGE 0xF7
275
276 #define STLINK_DEV_DFU_MODE 0x00
277 #define STLINK_DEV_MASS_MODE 0x01
278 #define STLINK_DEV_DEBUG_MODE 0x02
279 #define STLINK_DEV_SWIM_MODE 0x03
280 #define STLINK_DEV_BOOTLOADER_MODE 0x04
281 #define STLINK_DEV_UNKNOWN_MODE -1
282
283 #define STLINK_DFU_EXIT 0x07
284
285 /*
286 STLINK_SWIM_ENTER_SEQ
287 1.3ms low then 750Hz then 1.5kHz
288
289 STLINK_SWIM_GEN_RST
290 STM8 DM pulls reset pin low 50us
291
292 STLINK_SWIM_SPEED
293 uint8_t (0=low|1=high)
294
295 STLINK_SWIM_WRITEMEM
296 uint16_t length
297 uint32_t address
298
299 STLINK_SWIM_RESET
300 send synchronization seq (16us low, response 64 clocks low)
301 */
302 #define STLINK_SWIM_ENTER 0x00
303 #define STLINK_SWIM_EXIT 0x01
304 #define STLINK_SWIM_READ_CAP 0x02
305 #define STLINK_SWIM_SPEED 0x03
306 #define STLINK_SWIM_ENTER_SEQ 0x04
307 #define STLINK_SWIM_GEN_RST 0x05
308 #define STLINK_SWIM_RESET 0x06
309 #define STLINK_SWIM_ASSERT_RESET 0x07
310 #define STLINK_SWIM_DEASSERT_RESET 0x08
311 #define STLINK_SWIM_READSTATUS 0x09
312 #define STLINK_SWIM_WRITEMEM 0x0a
313 #define STLINK_SWIM_READMEM 0x0b
314 #define STLINK_SWIM_READBUF 0x0c
315
316 #define STLINK_DEBUG_GETSTATUS 0x01
317 #define STLINK_DEBUG_FORCEDEBUG 0x02
318 #define STLINK_DEBUG_APIV1_RESETSYS 0x03
319 #define STLINK_DEBUG_APIV1_READALLREGS 0x04
320 #define STLINK_DEBUG_APIV1_READREG 0x05
321 #define STLINK_DEBUG_APIV1_WRITEREG 0x06
322 #define STLINK_DEBUG_READMEM_32BIT 0x07
323 #define STLINK_DEBUG_WRITEMEM_32BIT 0x08
324 #define STLINK_DEBUG_RUNCORE 0x09
325 #define STLINK_DEBUG_STEPCORE 0x0a
326 #define STLINK_DEBUG_APIV1_SETFP 0x0b
327 #define STLINK_DEBUG_READMEM_8BIT 0x0c
328 #define STLINK_DEBUG_WRITEMEM_8BIT 0x0d
329 #define STLINK_DEBUG_APIV1_CLEARFP 0x0e
330 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG 0x0f
331 #define STLINK_DEBUG_APIV1_SETWATCHPOINT 0x10
332
333 #define STLINK_DEBUG_ENTER_JTAG_RESET 0x00
334 #define STLINK_DEBUG_ENTER_SWD_NO_RESET 0xa3
335 #define STLINK_DEBUG_ENTER_JTAG_NO_RESET 0xa4
336
337 #define STLINK_DEBUG_APIV1_ENTER 0x20
338 #define STLINK_DEBUG_EXIT 0x21
339 #define STLINK_DEBUG_READCOREID 0x22
340
341 #define STLINK_DEBUG_APIV2_ENTER 0x30
342 #define STLINK_DEBUG_APIV2_READ_IDCODES 0x31
343 #define STLINK_DEBUG_APIV2_RESETSYS 0x32
344 #define STLINK_DEBUG_APIV2_READREG 0x33
345 #define STLINK_DEBUG_APIV2_WRITEREG 0x34
346 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG 0x35
347 #define STLINK_DEBUG_APIV2_READDEBUGREG 0x36
348
349 #define STLINK_DEBUG_APIV2_READALLREGS 0x3A
350 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
351 #define STLINK_DEBUG_APIV2_DRIVE_NRST 0x3C
352
353 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS2 0x3E
354
355 #define STLINK_DEBUG_APIV2_START_TRACE_RX 0x40
356 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX 0x41
357 #define STLINK_DEBUG_APIV2_GET_TRACE_NB 0x42
358 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ 0x43
359 #define STLINK_DEBUG_APIV2_JTAG_SET_FREQ 0x44
360 #define STLINK_DEBUG_APIV2_READ_DAP_REG 0x45
361 #define STLINK_DEBUG_APIV2_WRITE_DAP_REG 0x46
362 #define STLINK_DEBUG_APIV2_READMEM_16BIT 0x47
363 #define STLINK_DEBUG_APIV2_WRITEMEM_16BIT 0x48
364
365 #define STLINK_DEBUG_APIV2_INIT_AP 0x4B
366 #define STLINK_DEBUG_APIV2_CLOSE_AP_DBG 0x4C
367
368 #define STLINK_APIV3_SET_COM_FREQ 0x61
369 #define STLINK_APIV3_GET_COM_FREQ 0x62
370
371 #define STLINK_APIV3_GET_VERSION_EX 0xFB
372
373 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW 0x00
374 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH 0x01
375 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
376
377 #define STLINK_DEBUG_PORT_ACCESS 0xffff
378
379 #define STLINK_TRACE_SIZE 4096
380 #define STLINK_TRACE_MAX_HZ 2000000
381 #define STLINK_V3_TRACE_MAX_HZ 24000000
382
383 #define STLINK_V3_MAX_FREQ_NB 10
384
385 #define REQUEST_SENSE 0x03
386 #define REQUEST_SENSE_LENGTH 18
387
388 /* STLINK TCP commands */
389 #define STLINK_TCP_CMD_REFRESH_DEVICE_LIST 0x00
390 #define STLINK_TCP_CMD_GET_NB_DEV 0x01
391 #define STLINK_TCP_CMD_GET_DEV_INFO 0x02
392 #define STLINK_TCP_CMD_OPEN_DEV 0x03
393 #define STLINK_TCP_CMD_CLOSE_DEV 0x04
394 #define STLINK_TCP_CMD_SEND_USB_CMD 0x05
395 #define STLINK_TCP_CMD_GET_SERVER_VERSION 0x06
396 #define STLINK_TCP_CMD_GET_NB_OF_DEV_CLIENTS 0x07
397
398 /* STLINK TCP constants */
399 #define OPENOCD_STLINK_TCP_API_VERSION 1
400 #define STLINK_TCP_REQUEST_WRITE 0
401 #define STLINK_TCP_REQUEST_READ 1
402 #define STLINK_TCP_REQUEST_READ_SWO 3
403 #define STLINK_TCP_SS_SIZE 4
404 #define STLINK_TCP_USB_CMD_SIZE 32
405 #define STLINK_TCP_SERIAL_SIZE 32
406 #define STLINK_TCP_SEND_BUFFER_SIZE 10240
407 #define STLINK_TCP_RECV_BUFFER_SIZE 10240
408
409 /* STLINK TCP command status */
410 #define STLINK_TCP_SS_OK 0x00000001
411 #define STLINK_TCP_SS_MEMORY_PROBLEM 0x00001000
412 #define STLINK_TCP_SS_TIMEOUT 0x00001001
413 #define STLINK_TCP_SS_BAD_PARAMETER 0x00001002
414 #define STLINK_TCP_SS_OPEN_ERR 0x00001003
415 #define STLINK_TCP_SS_TRUNCATED_DATA 0x00001052
416 #define STLINK_TCP_SS_CMD_NOT_AVAILABLE 0x00001053
417 #define STLINK_TCP_SS_TCP_ERROR 0x00002001
418 #define STLINK_TCP_SS_TCP_CANT_CONNECT 0x00002002
419 #define STLINK_TCP_SS_WIN32_ERROR 0x00010000
420
421 /*
422 * Map the relevant features, quirks and workaround for specific firmware
423 * version of stlink
424 */
425 #define STLINK_F_HAS_TRACE BIT(0) /* v2>=j13 || v3 */
426 #define STLINK_F_HAS_GETLASTRWSTATUS2 BIT(1) /* v2>=j15 || v3 */
427 #define STLINK_F_HAS_SWD_SET_FREQ BIT(2) /* v2>=j22 */
428 #define STLINK_F_HAS_JTAG_SET_FREQ BIT(3) /* v2>=j24 */
429 #define STLINK_F_QUIRK_JTAG_DP_READ BIT(4) /* v2>=j24 && v2<j32 */
430 #define STLINK_F_HAS_DAP_REG BIT(5) /* v2>=j24 || v3 */
431 #define STLINK_F_HAS_MEM_16BIT BIT(6) /* v2>=j26 || v3 */
432 #define STLINK_F_HAS_AP_INIT BIT(7) /* v2>=j28 || v3 */
433 #define STLINK_F_FIX_CLOSE_AP BIT(8) /* v2>=j29 || v3 */
434 #define STLINK_F_HAS_DPBANKSEL BIT(9) /* v2>=j32 || v3>=j2 */
435 #define STLINK_F_HAS_RW8_512BYTES BIT(10) /* v3>=j6 */
436
437 /* aliases */
438 #define STLINK_F_HAS_TARGET_VOLT STLINK_F_HAS_TRACE
439 #define STLINK_F_HAS_FPU_REG STLINK_F_HAS_GETLASTRWSTATUS2
440
441 #define STLINK_REGSEL_IS_FPU(x) ((x) > 0x1F)
442
443 struct speed_map {
444 int speed;
445 int speed_divisor;
446 };
447
448 /* SWD clock speed */
449 static const struct speed_map stlink_khz_to_speed_map_swd[] = {
450 {4000, 0},
451 {1800, 1}, /* default */
452 {1200, 2},
453 {950, 3},
454 {480, 7},
455 {240, 15},
456 {125, 31},
457 {100, 40},
458 {50, 79},
459 {25, 158},
460 {15, 265},
461 {5, 798}
462 };
463
464 /* JTAG clock speed */
465 static const struct speed_map stlink_khz_to_speed_map_jtag[] = {
466 {9000, 4},
467 {4500, 8},
468 {2250, 16},
469 {1125, 32}, /* default */
470 {562, 64},
471 {281, 128},
472 {140, 256}
473 };
474
475 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
476 static int stlink_swim_status(void *handle);
477 static void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size);
478 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map);
479 static int stlink_speed(void *handle, int khz, bool query);
480 static int stlink_usb_open_ap(void *handle, unsigned short apsel);
481
482 /** */
483 static unsigned int stlink_usb_block(void *handle)
484 {
485 struct stlink_usb_handle_s *h = handle;
486
487 assert(handle);
488
489 if (h->version.flags & STLINK_F_HAS_RW8_512BYTES)
490 return STLINKV3_MAX_RW8;
491 else
492 return STLINK_MAX_RW8;
493 }
494
495 #ifdef USE_LIBUSB_ASYNCIO
496
497 static LIBUSB_CALL void sync_transfer_cb(struct libusb_transfer *transfer)
498 {
499 int *completed = transfer->user_data;
500 *completed = 1;
501 /* caller interprets result and frees transfer */
502 }
503
504
505 static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
506 {
507 int r, *completed = transfer->user_data;
508
509 while (!*completed) {
510 r = jtag_libusb_handle_events_completed(completed);
511 if (r < 0) {
512 if (r == LIBUSB_ERROR_INTERRUPTED)
513 continue;
514 libusb_cancel_transfer(transfer);
515 continue;
516 }
517 }
518 }
519
520
521 static int transfer_error_status(const struct libusb_transfer *transfer)
522 {
523 int r = 0;
524
525 switch (transfer->status) {
526 case LIBUSB_TRANSFER_COMPLETED:
527 r = 0;
528 break;
529 case LIBUSB_TRANSFER_TIMED_OUT:
530 r = LIBUSB_ERROR_TIMEOUT;
531 break;
532 case LIBUSB_TRANSFER_STALL:
533 r = LIBUSB_ERROR_PIPE;
534 break;
535 case LIBUSB_TRANSFER_OVERFLOW:
536 r = LIBUSB_ERROR_OVERFLOW;
537 break;
538 case LIBUSB_TRANSFER_NO_DEVICE:
539 r = LIBUSB_ERROR_NO_DEVICE;
540 break;
541 case LIBUSB_TRANSFER_ERROR:
542 case LIBUSB_TRANSFER_CANCELLED:
543 r = LIBUSB_ERROR_IO;
544 break;
545 default:
546 r = LIBUSB_ERROR_OTHER;
547 break;
548 }
549
550 return r;
551 }
552
553 struct jtag_xfer {
554 int ep;
555 uint8_t *buf;
556 size_t size;
557 /* Internal */
558 int retval;
559 int completed;
560 size_t transfer_size;
561 struct libusb_transfer *transfer;
562 };
563
564 static int jtag_libusb_bulk_transfer_n(
565 struct libusb_device_handle *dev_handle,
566 struct jtag_xfer *transfers,
567 size_t n_transfers,
568 int timeout)
569 {
570 int retval = 0;
571 int returnval = ERROR_OK;
572
573
574 for (size_t i = 0; i < n_transfers; ++i) {
575 transfers[i].retval = 0;
576 transfers[i].completed = 0;
577 transfers[i].transfer_size = 0;
578 transfers[i].transfer = libusb_alloc_transfer(0);
579
580 if (!transfers[i].transfer) {
581 for (size_t j = 0; j < i; ++j)
582 libusb_free_transfer(transfers[j].transfer);
583
584 LOG_DEBUG("ERROR, failed to alloc usb transfers");
585 for (size_t k = 0; k < n_transfers; ++k)
586 transfers[k].retval = LIBUSB_ERROR_NO_MEM;
587 return ERROR_FAIL;
588 }
589 }
590
591 for (size_t i = 0; i < n_transfers; ++i) {
592 libusb_fill_bulk_transfer(
593 transfers[i].transfer,
594 dev_handle,
595 transfers[i].ep, transfers[i].buf, transfers[i].size,
596 sync_transfer_cb, &transfers[i].completed, timeout);
597 transfers[i].transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
598
599 retval = libusb_submit_transfer(transfers[i].transfer);
600 if (retval < 0) {
601 LOG_DEBUG("ERROR, failed to submit transfer %zu, error %d", i, retval);
602
603 /* Probably no point continuing to submit transfers once a submission fails.
604 * As a result, tag all remaining transfers as errors.
605 */
606 for (size_t j = i; j < n_transfers; ++j)
607 transfers[j].retval = retval;
608
609 returnval = ERROR_FAIL;
610 break;
611 }
612 }
613
614 /* Wait for every submitted USB transfer to complete.
615 */
616 for (size_t i = 0; i < n_transfers; ++i) {
617 if (transfers[i].retval == 0) {
618 sync_transfer_wait_for_completion(transfers[i].transfer);
619
620 retval = transfer_error_status(transfers[i].transfer);
621 if (retval) {
622 returnval = ERROR_FAIL;
623 transfers[i].retval = retval;
624 LOG_DEBUG("ERROR, transfer %zu failed, error %d", i, retval);
625 } else {
626 /* Assuming actual_length is only valid if there is no transfer error.
627 */
628 transfers[i].transfer_size = transfers[i].transfer->actual_length;
629 }
630 }
631
632 libusb_free_transfer(transfers[i].transfer);
633 transfers[i].transfer = NULL;
634 }
635
636 return returnval;
637 }
638
639 #endif
640
641
642 /** */
643 static int stlink_usb_xfer_v1_get_status(void *handle)
644 {
645 struct stlink_usb_handle_s *h = handle;
646 int tr, ret;
647
648 assert(handle);
649
650 /* read status */
651 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
652
653 ret = jtag_libusb_bulk_read(h->usb_backend_priv.fd, h->rx_ep, (char *)h->cmdbuf, 13,
654 STLINK_READ_TIMEOUT, &tr);
655 if (ret || tr != 13)
656 return ERROR_FAIL;
657
658 uint32_t t1;
659
660 t1 = buf_get_u32(h->cmdbuf, 0, 32);
661
662 /* check for USBS */
663 if (t1 != 0x53425355)
664 return ERROR_FAIL;
665 /*
666 * CSW status:
667 * 0 success
668 * 1 command failure
669 * 2 phase error
670 */
671 if (h->cmdbuf[12] != 0)
672 return ERROR_FAIL;
673
674 return ERROR_OK;
675 }
676
677 #ifdef USE_LIBUSB_ASYNCIO
678 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
679 {
680 struct stlink_usb_handle_s *h = handle;
681
682 assert(handle);
683
684 size_t n_transfers = 0;
685 struct jtag_xfer transfers[2];
686
687 memset(transfers, 0, sizeof(transfers));
688
689 transfers[0].ep = h->tx_ep;
690 transfers[0].buf = h->cmdbuf;
691 transfers[0].size = cmdsize;
692
693 ++n_transfers;
694
695 if (h->direction == h->tx_ep && size) {
696 transfers[1].ep = h->tx_ep;
697 transfers[1].buf = (uint8_t *)buf;
698 transfers[1].size = size;
699
700 ++n_transfers;
701 } else if (h->direction == h->rx_ep && size) {
702 transfers[1].ep = h->rx_ep;
703 transfers[1].buf = (uint8_t *)buf;
704 transfers[1].size = size;
705
706 ++n_transfers;
707 }
708
709 return jtag_libusb_bulk_transfer_n(
710 h->usb_backend_priv.fd,
711 transfers,
712 n_transfers,
713 STLINK_WRITE_TIMEOUT);
714 }
715 #else
716 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
717 {
718 struct stlink_usb_handle_s *h = handle;
719 int tr, ret;
720
721 assert(handle);
722
723 ret = jtag_libusb_bulk_write(h->usb_backend_priv.fd, h->tx_ep, (char *)h->cmdbuf,
724 cmdsize, STLINK_WRITE_TIMEOUT, &tr);
725 if (ret || tr != cmdsize)
726 return ERROR_FAIL;
727
728 if (h->direction == h->tx_ep && size) {
729 ret = jtag_libusb_bulk_write(h->usb_backend_priv.fd, h->tx_ep, (char *)buf,
730 size, STLINK_WRITE_TIMEOUT, &tr);
731 if (ret || tr != size) {
732 LOG_DEBUG("bulk write failed");
733 return ERROR_FAIL;
734 }
735 } else if (h->direction == h->rx_ep && size) {
736 ret = jtag_libusb_bulk_read(h->usb_backend_priv.fd, h->rx_ep, (char *)buf,
737 size, STLINK_READ_TIMEOUT, &tr);
738 if (ret || tr != size) {
739 LOG_DEBUG("bulk read failed");
740 return ERROR_FAIL;
741 }
742 }
743
744 return ERROR_OK;
745 }
746 #endif
747
748 /** */
749 static int stlink_usb_xfer_v1_get_sense(void *handle)
750 {
751 int res;
752 struct stlink_usb_handle_s *h = handle;
753
754 assert(handle);
755
756 stlink_usb_init_buffer(handle, h->rx_ep, 16);
757
758 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE;
759 h->cmdbuf[h->cmdidx++] = 0;
760 h->cmdbuf[h->cmdidx++] = 0;
761 h->cmdbuf[h->cmdidx++] = 0;
762 h->cmdbuf[h->cmdidx++] = REQUEST_SENSE_LENGTH;
763
764 res = stlink_usb_xfer_rw(handle, REQUEST_SENSE_LENGTH, h->databuf, 16);
765
766 if (res != ERROR_OK)
767 return res;
768
769 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK)
770 return ERROR_FAIL;
771
772 return ERROR_OK;
773 }
774
775 /** */
776 static int stlink_usb_usb_read_trace(void *handle, const uint8_t *buf, int size)
777 {
778 struct stlink_usb_handle_s *h = handle;
779 int tr, ret;
780
781 ret = jtag_libusb_bulk_read(h->usb_backend_priv.fd, h->trace_ep, (char *)buf, size,
782 STLINK_READ_TIMEOUT, &tr);
783 if (ret || tr != size) {
784 LOG_ERROR("bulk trace read failed");
785 return ERROR_FAIL;
786 }
787
788 return ERROR_OK;
789 }
790
791 /*
792 transfers block in cmdbuf
793 <size> indicates number of bytes in the following
794 data phase.
795 Ignore the (eventual) error code in the received packet.
796 */
797 static int stlink_usb_usb_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
798 {
799 int err, cmdsize = STLINK_CMD_SIZE_V2;
800 struct stlink_usb_handle_s *h = handle;
801
802 assert(handle);
803
804 if (h->version.stlink == 1) {
805 cmdsize = STLINK_SG_SIZE;
806 /* put length in bCBWCBLength */
807 h->cmdbuf[14] = h->cmdidx-15;
808 }
809
810 err = stlink_usb_xfer_rw(handle, cmdsize, buf, size);
811
812 if (err != ERROR_OK)
813 return err;
814
815 if (h->version.stlink == 1) {
816 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK) {
817 /* check csw status */
818 if (h->cmdbuf[12] == 1) {
819 LOG_DEBUG("get sense");
820 if (stlink_usb_xfer_v1_get_sense(handle) != ERROR_OK)
821 return ERROR_FAIL;
822 }
823 return ERROR_FAIL;
824 }
825 }
826
827 return ERROR_OK;
828 }
829
830
831 static int stlink_tcp_send_cmd(void *handle, int send_size, int recv_size, bool check_tcp_status)
832 {
833 struct stlink_usb_handle_s *h = handle;
834
835 assert(handle);
836
837 /* send the TCP command */
838 int sent_size = send(h->tcp_backend_priv.fd, (void *)h->tcp_backend_priv.send_buf, send_size, 0);
839 if (sent_size != send_size) {
840 LOG_ERROR("failed to send USB CMD");
841 if (sent_size == -1)
842 LOG_DEBUG("socket send error: %s (errno %d)", strerror(errno), errno);
843 else
844 LOG_DEBUG("sent size %d (expected %d)", sent_size, send_size);
845 return ERROR_FAIL;
846 }
847
848 keep_alive();
849
850 /* read the TCP response */
851 int received_size = recv(h->tcp_backend_priv.fd, (void *)h->tcp_backend_priv.recv_buf, recv_size, 0);
852 if (received_size != recv_size) {
853 LOG_ERROR("failed to receive USB CMD response");
854 if (received_size == -1)
855 LOG_DEBUG("socket recv error: %s (errno %d)", strerror(errno), errno);
856 else
857 LOG_DEBUG("received size %d (expected %d)", received_size, recv_size);
858 return ERROR_FAIL;
859 }
860
861 if (check_tcp_status) {
862 uint32_t tcp_ss = le_to_h_u32(h->tcp_backend_priv.recv_buf);
863 if (tcp_ss != STLINK_TCP_SS_OK) {
864 LOG_ERROR("TCP error status 0x%X", tcp_ss);
865 return ERROR_FAIL;
866 }
867 }
868
869 return ERROR_OK;
870 }
871
872 /** */
873 static int stlink_tcp_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
874 {
875 struct stlink_usb_handle_s *h = handle;
876
877 int send_size = STLINK_TCP_USB_CMD_SIZE;
878 int recv_size = STLINK_TCP_SS_SIZE;
879
880 assert(handle);
881
882 /* prepare the TCP command */
883 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_SEND_USB_CMD;
884 memset(&h->tcp_backend_priv.send_buf[1], 0, 3); /* reserved for alignment and future use, must be zero */
885 h_u32_to_le(&h->tcp_backend_priv.send_buf[4], h->tcp_backend_priv.connect_id);
886 /* tcp_backend_priv.send_buf[8..23] already contains the constructed stlink command */
887 h->tcp_backend_priv.send_buf[24] = h->direction;
888 memset(&h->tcp_backend_priv.send_buf[25], 0, 3); /* reserved for alignment and future use, must be zero */
889
890 h_u32_to_le(&h->tcp_backend_priv.send_buf[28], size);
891
892 /*
893 * if the xfer is a write request (tx_ep)
894 * > then buf content will be copied
895 * into &cmdbuf[32].
896 * else : the xfer is a read or trace read request (rx_ep or trace_ep)
897 * > the buf content will be filled from &databuf[4].
898 *
899 * note : if h->direction is trace_ep, h->cmdbuf is zeros.
900 */
901
902 if (h->direction == h->tx_ep) { /* STLINK_TCP_REQUEST_WRITE */
903 send_size += size;
904 if (send_size > STLINK_TCP_SEND_BUFFER_SIZE) {
905 LOG_ERROR("STLINK_TCP command buffer overflow");
906 return ERROR_FAIL;
907 }
908 memcpy(&h->tcp_backend_priv.send_buf[32], buf, size);
909 } else { /* STLINK_TCP_REQUEST_READ or STLINK_TCP_REQUEST_READ_SWO */
910 recv_size += size;
911 if (recv_size > STLINK_TCP_RECV_BUFFER_SIZE) {
912 LOG_ERROR("STLINK_TCP data buffer overflow");
913 return ERROR_FAIL;
914 }
915 }
916
917 int ret = stlink_tcp_send_cmd(h, send_size, recv_size, true);
918 if (ret != ERROR_OK)
919 return ret;
920
921 if (h->direction != h->tx_ep) {
922 /* the read data is located in tcp_backend_priv.recv_buf[4] */
923 /* most of the case it will be copying the data from tcp_backend_priv.recv_buf[4]
924 * to handle->cmd_buff which are the same, so let's avoid unnecessary copying */
925 if (buf != &h->tcp_backend_priv.recv_buf[4])
926 memcpy((uint8_t *)buf, &h->tcp_backend_priv.recv_buf[4], size);
927 }
928
929 return ERROR_OK;
930 }
931
932 /** */
933 static int stlink_tcp_read_trace(void *handle, const uint8_t *buf, int size)
934 {
935 struct stlink_usb_handle_s *h = handle;
936
937 stlink_usb_init_buffer(h, h->trace_ep, 0);
938 return stlink_tcp_xfer_noerrcheck(handle, buf, size);
939 }
940
941 /**
942 Converts an STLINK status code held in the first byte of a response
943 to an openocd error, logs any error/wait status as debug output.
944 */
945 static int stlink_usb_error_check(void *handle)
946 {
947 struct stlink_usb_handle_s *h = handle;
948
949 assert(handle);
950
951 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
952 switch (h->databuf[0]) {
953 case STLINK_SWIM_ERR_OK:
954 return ERROR_OK;
955 case STLINK_SWIM_BUSY:
956 return ERROR_WAIT;
957 default:
958 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
959 return ERROR_FAIL;
960 }
961 }
962
963 /* TODO: no error checking yet on api V1 */
964 if (h->version.jtag_api == STLINK_JTAG_API_V1)
965 h->databuf[0] = STLINK_DEBUG_ERR_OK;
966
967 switch (h->databuf[0]) {
968 case STLINK_DEBUG_ERR_OK:
969 return ERROR_OK;
970 case STLINK_DEBUG_ERR_FAULT:
971 LOG_DEBUG("SWD fault response (0x%x)", STLINK_DEBUG_ERR_FAULT);
972 return ERROR_FAIL;
973 case STLINK_SWD_AP_WAIT:
974 LOG_DEBUG("wait status SWD_AP_WAIT (0x%x)", STLINK_SWD_AP_WAIT);
975 return ERROR_WAIT;
976 case STLINK_SWD_DP_WAIT:
977 LOG_DEBUG("wait status SWD_DP_WAIT (0x%x)", STLINK_SWD_DP_WAIT);
978 return ERROR_WAIT;
979 case STLINK_JTAG_GET_IDCODE_ERROR:
980 LOG_DEBUG("STLINK_JTAG_GET_IDCODE_ERROR");
981 return ERROR_FAIL;
982 case STLINK_JTAG_WRITE_ERROR:
983 LOG_DEBUG("Write error");
984 return ERROR_FAIL;
985 case STLINK_JTAG_WRITE_VERIF_ERROR:
986 LOG_DEBUG("Write verify error, ignoring");
987 return ERROR_OK;
988 case STLINK_SWD_AP_FAULT:
989 /* git://git.ac6.fr/openocd commit 657e3e885b9ee10
990 * returns ERROR_OK with the comment:
991 * Change in error status when reading outside RAM.
992 * This fix allows CDT plugin to visualize memory.
993 */
994 LOG_DEBUG("STLINK_SWD_AP_FAULT");
995 return ERROR_FAIL;
996 case STLINK_SWD_AP_ERROR:
997 LOG_DEBUG("STLINK_SWD_AP_ERROR");
998 return ERROR_FAIL;
999 case STLINK_SWD_AP_PARITY_ERROR:
1000 LOG_DEBUG("STLINK_SWD_AP_PARITY_ERROR");
1001 return ERROR_FAIL;
1002 case STLINK_SWD_DP_FAULT:
1003 LOG_DEBUG("STLINK_SWD_DP_FAULT");
1004 return ERROR_FAIL;
1005 case STLINK_SWD_DP_ERROR:
1006 LOG_DEBUG("STLINK_SWD_DP_ERROR");
1007 return ERROR_FAIL;
1008 case STLINK_SWD_DP_PARITY_ERROR:
1009 LOG_DEBUG("STLINK_SWD_DP_PARITY_ERROR");
1010 return ERROR_FAIL;
1011 case STLINK_SWD_AP_WDATA_ERROR:
1012 LOG_DEBUG("STLINK_SWD_AP_WDATA_ERROR");
1013 return ERROR_FAIL;
1014 case STLINK_SWD_AP_STICKY_ERROR:
1015 LOG_DEBUG("STLINK_SWD_AP_STICKY_ERROR");
1016 return ERROR_FAIL;
1017 case STLINK_SWD_AP_STICKYORUN_ERROR:
1018 LOG_DEBUG("STLINK_SWD_AP_STICKYORUN_ERROR");
1019 return ERROR_FAIL;
1020 case STLINK_BAD_AP_ERROR:
1021 LOG_DEBUG("STLINK_BAD_AP_ERROR");
1022 return ERROR_FAIL;
1023 default:
1024 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
1025 return ERROR_FAIL;
1026 }
1027 }
1028
1029 /*
1030 * Wrapper around stlink_usb_xfer_noerrcheck()
1031 * to check the error code in the received packet
1032 */
1033 static int stlink_usb_xfer_errcheck(void *handle, const uint8_t *buf, int size)
1034 {
1035 int retval;
1036
1037 assert(size > 0);
1038
1039 retval = stlink_usb_xfer_noerrcheck(handle, buf, size);
1040 if (retval != ERROR_OK)
1041 return retval;
1042
1043 return stlink_usb_error_check(handle);
1044 }
1045
1046 /** Issue an STLINK command via USB transfer, with retries on any wait status responses.
1047
1048 Works for commands where the STLINK_DEBUG status is returned in the first
1049 byte of the response packet. For SWIM a SWIM_READSTATUS is requested instead.
1050
1051 Returns an openocd result code.
1052 */
1053 static int stlink_cmd_allow_retry(void *handle, const uint8_t *buf, int size)
1054 {
1055 int retries = 0;
1056 int res;
1057 struct stlink_usb_handle_s *h = handle;
1058
1059 while (1) {
1060 if ((h->st_mode != STLINK_MODE_DEBUG_SWIM) || !retries) {
1061 res = stlink_usb_xfer_noerrcheck(handle, buf, size);
1062 if (res != ERROR_OK)
1063 return res;
1064 }
1065
1066 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
1067 res = stlink_swim_status(handle);
1068 if (res != ERROR_OK)
1069 return res;
1070 }
1071
1072 res = stlink_usb_error_check(handle);
1073 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1074 unsigned int delay_us = (1<<retries++) * 1000;
1075 LOG_DEBUG("stlink_cmd_allow_retry ERROR_WAIT, retry %d, delaying %u microseconds", retries, delay_us);
1076 usleep(delay_us);
1077 continue;
1078 }
1079 return res;
1080 }
1081 }
1082
1083 /** */
1084 static int stlink_usb_read_trace(void *handle, const uint8_t *buf, int size)
1085 {
1086 struct stlink_usb_handle_s *h = handle;
1087
1088 assert(handle);
1089
1090 assert(h->version.flags & STLINK_F_HAS_TRACE);
1091
1092 return h->backend->read_trace(handle, buf, size);
1093 }
1094
1095 /*
1096 this function writes transfer length in
1097 the right place in the cb
1098 */
1099 static void stlink_usb_set_cbw_transfer_datalength(void *handle, uint32_t size)
1100 {
1101 struct stlink_usb_handle_s *h = handle;
1102
1103 buf_set_u32(h->cmdbuf+8, 0, 32, size);
1104 }
1105
1106 static void stlink_usb_xfer_v1_create_cmd(void *handle, uint8_t direction, uint32_t size)
1107 {
1108 struct stlink_usb_handle_s *h = handle;
1109
1110 /* fill the send buffer */
1111 strcpy((char *)h->cmdbuf, "USBC");
1112 h->cmdidx += 4;
1113 /* csw tag not used */
1114 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, 0);
1115 h->cmdidx += 4;
1116 /* cbw data transfer length (in the following data phase in or out) */
1117 buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, size);
1118 h->cmdidx += 4;
1119 /* cbw flags */
1120 h->cmdbuf[h->cmdidx++] = (direction == h->rx_ep ? ENDPOINT_IN : ENDPOINT_OUT);
1121 h->cmdbuf[h->cmdidx++] = 0; /* lun */
1122 /* cdb clength (is filled in at xfer) */
1123 h->cmdbuf[h->cmdidx++] = 0;
1124 }
1125
1126 /** */
1127 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size)
1128 {
1129 struct stlink_usb_handle_s *h = handle;
1130
1131 h->direction = direction;
1132
1133 h->cmdidx = 0;
1134
1135 memset(h->cmdbuf, 0, STLINK_SG_SIZE);
1136 memset(h->databuf, 0, STLINK_DATA_SIZE);
1137
1138 if (h->version.stlink == 1)
1139 stlink_usb_xfer_v1_create_cmd(handle, direction, size);
1140 }
1141
1142 /** */
1143 static int stlink_usb_version(void *handle)
1144 {
1145 int res;
1146 uint32_t flags;
1147 uint16_t version;
1148 uint8_t v, x, y, jtag, swim, msd, bridge = 0;
1149 char v_str[5 * (1 + 3) + 1]; /* VvJjMmBbSs */
1150 char *p;
1151 struct stlink_usb_handle_s *h = handle;
1152
1153 assert(handle);
1154
1155 stlink_usb_init_buffer(handle, h->rx_ep, 6);
1156
1157 h->cmdbuf[h->cmdidx++] = STLINK_GET_VERSION;
1158
1159 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 6);
1160
1161 if (res != ERROR_OK)
1162 return res;
1163
1164 version = be_to_h_u16(h->databuf);
1165 v = (version >> 12) & 0x0f;
1166 x = (version >> 6) & 0x3f;
1167 y = version & 0x3f;
1168
1169 h->vid = le_to_h_u16(h->databuf + 2);
1170 h->pid = le_to_h_u16(h->databuf + 4);
1171
1172 switch (h->pid) {
1173 case STLINK_V2_1_PID:
1174 case STLINK_V2_1_NO_MSD_PID:
1175 if ((x <= 22 && y == 7) || (x >= 25 && y >= 7 && y <= 12)) {
1176 /* MxSy : STM8 V2.1 - SWIM only */
1177 msd = x;
1178 swim = y;
1179 jtag = 0;
1180 } else {
1181 /* JxMy : STM32 V2.1 - JTAG/SWD only */
1182 jtag = x;
1183 msd = y;
1184 swim = 0;
1185 }
1186 break;
1187 default:
1188 jtag = x;
1189 swim = y;
1190 msd = 0;
1191 break;
1192 }
1193
1194 /* STLINK-V3 requires a specific command */
1195 if (v == 3 && x == 0 && y == 0) {
1196 stlink_usb_init_buffer(handle, h->rx_ep, 16);
1197
1198 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_VERSION_EX;
1199
1200 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 12);
1201 if (res != ERROR_OK)
1202 return res;
1203
1204 v = h->databuf[0];
1205 swim = h->databuf[1];
1206 jtag = h->databuf[2];
1207 msd = h->databuf[3];
1208 bridge = h->databuf[4];
1209 h->vid = le_to_h_u16(h->databuf + 8);
1210 h->pid = le_to_h_u16(h->databuf + 10);
1211 }
1212
1213 h->version.stlink = v;
1214 h->version.jtag = jtag;
1215 h->version.swim = swim;
1216
1217 flags = 0;
1218 switch (h->version.stlink) {
1219 case 1:
1220 /* ST-LINK/V1 from J11 switch to api-v2 (and support SWD) */
1221 if (h->version.jtag >= 11)
1222 h->version.jtag_api = STLINK_JTAG_API_V2;
1223 else
1224 h->version.jtag_api = STLINK_JTAG_API_V1;
1225
1226 break;
1227 case 2:
1228 /* all ST-LINK/V2 and ST-Link/V2.1 use api-v2 */
1229 h->version.jtag_api = STLINK_JTAG_API_V2;
1230
1231 /* API for trace from J13 */
1232 /* API for target voltage from J13 */
1233 if (h->version.jtag >= 13)
1234 flags |= STLINK_F_HAS_TRACE;
1235
1236 /* preferred API to get last R/W status from J15 */
1237 if (h->version.jtag >= 15)
1238 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1239
1240 /* API to set SWD frequency from J22 */
1241 if (h->version.jtag >= 22)
1242 flags |= STLINK_F_HAS_SWD_SET_FREQ;
1243
1244 /* API to set JTAG frequency from J24 */
1245 /* API to access DAP registers from J24 */
1246 if (h->version.jtag >= 24) {
1247 flags |= STLINK_F_HAS_JTAG_SET_FREQ;
1248 flags |= STLINK_F_HAS_DAP_REG;
1249 }
1250
1251 /* Quirk for read DP in JTAG mode (V2 only) from J24, fixed in J32 */
1252 if (h->version.jtag >= 24 && h->version.jtag < 32)
1253 flags |= STLINK_F_QUIRK_JTAG_DP_READ;
1254
1255 /* API to read/write memory at 16 bit from J26 */
1256 if (h->version.jtag >= 26)
1257 flags |= STLINK_F_HAS_MEM_16BIT;
1258
1259 /* API required to init AP before any AP access from J28 */
1260 if (h->version.jtag >= 28)
1261 flags |= STLINK_F_HAS_AP_INIT;
1262
1263 /* API required to return proper error code on close AP from J29 */
1264 if (h->version.jtag >= 29)
1265 flags |= STLINK_F_FIX_CLOSE_AP;
1266
1267 /* Banked regs (DPv1 & DPv2) support from V2J32 */
1268 if (h->version.jtag >= 32)
1269 flags |= STLINK_F_HAS_DPBANKSEL;
1270
1271 break;
1272 case 3:
1273 /* all STLINK-V3 use api-v3 */
1274 h->version.jtag_api = STLINK_JTAG_API_V3;
1275
1276 /* STLINK-V3 is a superset of ST-LINK/V2 */
1277
1278 /* API for trace */
1279 /* API for target voltage */
1280 flags |= STLINK_F_HAS_TRACE;
1281
1282 /* preferred API to get last R/W status */
1283 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1284
1285 /* API to access DAP registers */
1286 flags |= STLINK_F_HAS_DAP_REG;
1287
1288 /* API to read/write memory at 16 bit */
1289 flags |= STLINK_F_HAS_MEM_16BIT;
1290
1291 /* API required to init AP before any AP access */
1292 flags |= STLINK_F_HAS_AP_INIT;
1293
1294 /* API required to return proper error code on close AP */
1295 flags |= STLINK_F_FIX_CLOSE_AP;
1296
1297 /* Banked regs (DPv1 & DPv2) support from V3J2 */
1298 if (h->version.jtag >= 2)
1299 flags |= STLINK_F_HAS_DPBANKSEL;
1300
1301 /* 8bit read/write max packet size 512 bytes from V3J6 */
1302 if (h->version.jtag >= 6)
1303 flags |= STLINK_F_HAS_RW8_512BYTES;
1304
1305 break;
1306 default:
1307 break;
1308 }
1309 h->version.flags = flags;
1310
1311 p = v_str;
1312 p += sprintf(p, "V%d", v);
1313 if (jtag || !msd)
1314 p += sprintf(p, "J%d", jtag);
1315 if (msd)
1316 p += sprintf(p, "M%d", msd);
1317 if (bridge)
1318 p += sprintf(p, "B%d", bridge);
1319 if (swim || !msd)
1320 sprintf(p, "S%d", swim);
1321
1322 LOG_INFO("STLINK %s (API v%d) VID:PID %04X:%04X",
1323 v_str,
1324 h->version.jtag_api,
1325 h->vid,
1326 h->pid);
1327
1328 return ERROR_OK;
1329 }
1330
1331 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
1332 {
1333 struct stlink_usb_handle_s *h = handle;
1334 uint32_t adc_results[2];
1335
1336 /* no error message, simply quit with error */
1337 if (!(h->version.flags & STLINK_F_HAS_TARGET_VOLT))
1338 return ERROR_COMMAND_NOTFOUND;
1339
1340 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1341
1342 h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
1343
1344 int result = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1345
1346 if (result != ERROR_OK)
1347 return result;
1348
1349 /* convert result */
1350 adc_results[0] = le_to_h_u32(h->databuf);
1351 adc_results[1] = le_to_h_u32(h->databuf + 4);
1352
1353 *target_voltage = 0;
1354
1355 if (adc_results[0])
1356 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
1357
1358 LOG_INFO("Target voltage: %f", (double)*target_voltage);
1359
1360 return ERROR_OK;
1361 }
1362
1363 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
1364 {
1365 struct stlink_usb_handle_s *h = handle;
1366
1367 assert(handle);
1368
1369 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
1370 return ERROR_COMMAND_NOTFOUND;
1371
1372 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1373
1374 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1375 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
1376 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1377 h->cmdidx += 2;
1378
1379 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1380
1381 if (result != ERROR_OK)
1382 return result;
1383
1384 return ERROR_OK;
1385 }
1386
1387 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
1388 {
1389 struct stlink_usb_handle_s *h = handle;
1390
1391 assert(handle);
1392
1393 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
1394 return ERROR_COMMAND_NOTFOUND;
1395
1396 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1397
1398 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1399 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
1400 h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1401 h->cmdidx += 2;
1402
1403 int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1404
1405 if (result != ERROR_OK)
1406 return result;
1407
1408 return ERROR_OK;
1409 }
1410
1411 /** */
1412 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
1413 {
1414 int res;
1415 struct stlink_usb_handle_s *h = handle;
1416
1417 assert(handle);
1418
1419 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1420
1421 h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
1422
1423 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1424
1425 if (res != ERROR_OK)
1426 return res;
1427
1428 *mode = h->databuf[0];
1429
1430 return ERROR_OK;
1431 }
1432
1433 /** */
1434 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
1435 {
1436 int rx_size = 0;
1437 struct stlink_usb_handle_s *h = handle;
1438
1439 assert(handle);
1440
1441 /* on api V2 we are able the read the latest command
1442 * status
1443 * TODO: we need the test on api V1 too
1444 */
1445 if (h->version.jtag_api != STLINK_JTAG_API_V1)
1446 rx_size = 2;
1447
1448 stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
1449
1450 switch (type) {
1451 case STLINK_MODE_DEBUG_JTAG:
1452 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1453 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1454 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1455 else
1456 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1457 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG_NO_RESET;
1458 break;
1459 case STLINK_MODE_DEBUG_SWD:
1460 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1461 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1462 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1463 else
1464 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1465 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD_NO_RESET;
1466 break;
1467 case STLINK_MODE_DEBUG_SWIM:
1468 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1469 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
1470 /* swim enter does not return any response or status */
1471 return stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1472 case STLINK_MODE_DFU:
1473 case STLINK_MODE_MASS:
1474 default:
1475 return ERROR_FAIL;
1476 }
1477
1478 return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
1479 }
1480
1481 /** */
1482 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
1483 {
1484 int res;
1485 struct stlink_usb_handle_s *h = handle;
1486
1487 assert(handle);
1488
1489 /* command with no reply, use a valid endpoint but zero size */
1490 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1491
1492 switch (type) {
1493 case STLINK_MODE_DEBUG_JTAG:
1494 case STLINK_MODE_DEBUG_SWD:
1495 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1496 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
1497 break;
1498 case STLINK_MODE_DEBUG_SWIM:
1499 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1500 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
1501 break;
1502 case STLINK_MODE_DFU:
1503 h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
1504 h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
1505 break;
1506 case STLINK_MODE_MASS:
1507 default:
1508 return ERROR_FAIL;
1509 }
1510
1511 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1512
1513 if (res != ERROR_OK)
1514 return res;
1515
1516 return ERROR_OK;
1517 }
1518
1519 static int stlink_usb_assert_srst(void *handle, int srst);
1520
1521 static enum stlink_mode stlink_get_mode(enum hl_transports t)
1522 {
1523 switch (t) {
1524 case HL_TRANSPORT_SWD:
1525 return STLINK_MODE_DEBUG_SWD;
1526 case HL_TRANSPORT_JTAG:
1527 return STLINK_MODE_DEBUG_JTAG;
1528 default:
1529 return STLINK_MODE_UNKNOWN;
1530 }
1531 }
1532
1533 /** */
1534 static int stlink_usb_exit_mode(void *handle)
1535 {
1536 int res;
1537 uint8_t mode;
1538 enum stlink_mode emode;
1539
1540 assert(handle);
1541
1542 res = stlink_usb_current_mode(handle, &mode);
1543
1544 if (res != ERROR_OK)
1545 return res;
1546
1547 LOG_DEBUG("MODE: 0x%02X", mode);
1548
1549 /* try to exit current mode */
1550 switch (mode) {
1551 case STLINK_DEV_DFU_MODE:
1552 emode = STLINK_MODE_DFU;
1553 break;
1554 case STLINK_DEV_DEBUG_MODE:
1555 emode = STLINK_MODE_DEBUG_SWD;
1556 break;
1557 case STLINK_DEV_SWIM_MODE:
1558 emode = STLINK_MODE_DEBUG_SWIM;
1559 break;
1560 case STLINK_DEV_BOOTLOADER_MODE:
1561 case STLINK_DEV_MASS_MODE:
1562 default:
1563 emode = STLINK_MODE_UNKNOWN;
1564 break;
1565 }
1566
1567 if (emode != STLINK_MODE_UNKNOWN)
1568 return stlink_usb_mode_leave(handle, emode);
1569
1570 return ERROR_OK;
1571 }
1572
1573 /** */
1574 static int stlink_usb_init_mode(void *handle, bool connect_under_reset, int initial_interface_speed)
1575 {
1576 int res;
1577 uint8_t mode;
1578 enum stlink_mode emode;
1579 struct stlink_usb_handle_s *h = handle;
1580
1581 assert(handle);
1582
1583 res = stlink_usb_exit_mode(handle);
1584 if (res != ERROR_OK)
1585 return res;
1586
1587 res = stlink_usb_current_mode(handle, &mode);
1588
1589 if (res != ERROR_OK)
1590 return res;
1591
1592 /* we check the target voltage here as an aid to debugging connection problems.
1593 * the stlink requires the target Vdd to be connected for reliable debugging.
1594 * this cmd is supported in all modes except DFU
1595 */
1596 if (mode != STLINK_DEV_DFU_MODE) {
1597
1598 float target_voltage;
1599
1600 /* check target voltage (if supported) */
1601 res = stlink_usb_check_voltage(h, &target_voltage);
1602
1603 if (res != ERROR_OK) {
1604 if (res != ERROR_COMMAND_NOTFOUND)
1605 LOG_ERROR("voltage check failed");
1606 /* attempt to continue as it is not a catastrophic failure */
1607 } else {
1608 /* check for a sensible target voltage, operating range is 1.65-5.5v
1609 * according to datasheet */
1610 if (target_voltage < 1.5)
1611 LOG_ERROR("target voltage may be too low for reliable debugging");
1612 }
1613 }
1614
1615 LOG_DEBUG("MODE: 0x%02X", mode);
1616
1617 /* set selected mode */
1618 emode = h->st_mode;
1619
1620 if (emode == STLINK_MODE_UNKNOWN) {
1621 LOG_ERROR("selected mode (transport) not supported");
1622 return ERROR_FAIL;
1623 }
1624
1625 /* set the speed before entering the mode, as the chip discovery phase should be done at this speed too */
1626 if (emode == STLINK_MODE_DEBUG_JTAG) {
1627 if (h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ) {
1628 stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
1629 stlink_speed(h, initial_interface_speed, false);
1630 }
1631 } else if (emode == STLINK_MODE_DEBUG_SWD) {
1632 if (h->version.flags & STLINK_F_HAS_SWD_SET_FREQ) {
1633 stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
1634 stlink_speed(h, initial_interface_speed, false);
1635 }
1636 }
1637
1638 if (h->version.jtag_api == STLINK_JTAG_API_V3 &&
1639 (emode == STLINK_MODE_DEBUG_JTAG || emode == STLINK_MODE_DEBUG_SWD)) {
1640 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
1641
1642 stlink_get_com_freq(h, (emode == STLINK_MODE_DEBUG_JTAG), map);
1643 stlink_dump_speed_map(map, ARRAY_SIZE(map));
1644 stlink_speed(h, initial_interface_speed, false);
1645 }
1646
1647 /* preliminary SRST assert:
1648 * We want SRST is asserted before activating debug signals (mode_enter).
1649 * As the required mode has not been set, the adapter may not know what pin to use.
1650 * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
1651 * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
1652 * after power on, SWIM_RST stays unchanged */
1653 if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
1654 stlink_usb_assert_srst(handle, 0);
1655 /* do not check the return status here, we will
1656 proceed and enter the desired mode below
1657 and try asserting srst again. */
1658
1659 res = stlink_usb_mode_enter(handle, emode);
1660 if (res != ERROR_OK)
1661 return res;
1662
1663 /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
1664 if (connect_under_reset) {
1665 res = stlink_usb_assert_srst(handle, 0);
1666 if (res != ERROR_OK)
1667 return res;
1668 }
1669
1670 res = stlink_usb_current_mode(handle, &mode);
1671
1672 if (res != ERROR_OK)
1673 return res;
1674
1675 LOG_DEBUG("MODE: 0x%02X", mode);
1676
1677 return ERROR_OK;
1678 }
1679
1680 /* request status from last swim request */
1681 static int stlink_swim_status(void *handle)
1682 {
1683 struct stlink_usb_handle_s *h = handle;
1684 int res;
1685
1686 stlink_usb_init_buffer(handle, h->rx_ep, 4);
1687 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1688 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
1689 /* error is checked by the caller */
1690 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1691 if (res != ERROR_OK)
1692 return res;
1693 return ERROR_OK;
1694 }
1695 /*
1696 the purpose of this function is unknown...
1697 capabilities? anyway for swim v6 it returns
1698 0001020600000000
1699 */
1700 __attribute__((unused))
1701 static int stlink_swim_cap(void *handle, uint8_t *cap)
1702 {
1703 struct stlink_usb_handle_s *h = handle;
1704 int res;
1705
1706 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1707 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1708 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1709 h->cmdbuf[h->cmdidx++] = 0x01;
1710 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1711 if (res != ERROR_OK)
1712 return res;
1713 memcpy(cap, h->databuf, 8);
1714 return ERROR_OK;
1715 }
1716
1717 /* debug dongle assert/deassert sreset line */
1718 static int stlink_swim_assert_reset(void *handle, int reset)
1719 {
1720 struct stlink_usb_handle_s *h = handle;
1721 int res;
1722
1723 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1724 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1725 if (!reset)
1726 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1727 else
1728 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1729 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1730 if (res != ERROR_OK)
1731 return res;
1732 return ERROR_OK;
1733 }
1734
1735 /*
1736 send swim enter seq
1737 1.3ms low then 750Hz then 1.5kHz
1738 */
1739 static int stlink_swim_enter(void *handle)
1740 {
1741 struct stlink_usb_handle_s *h = handle;
1742 int res;
1743
1744 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1745 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1746 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1747 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1748 if (res != ERROR_OK)
1749 return res;
1750 return ERROR_OK;
1751 }
1752
1753 /* switch high/low speed swim */
1754 static int stlink_swim_speed(void *handle, int speed)
1755 {
1756 struct stlink_usb_handle_s *h = handle;
1757 int res;
1758
1759 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1760 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1761 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1762 if (speed)
1763 h->cmdbuf[h->cmdidx++] = 1;
1764 else
1765 h->cmdbuf[h->cmdidx++] = 0;
1766 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1767 if (res != ERROR_OK)
1768 return res;
1769 return ERROR_OK;
1770 }
1771
1772 /*
1773 initiate srst from swim.
1774 nrst is pulled low for 50us.
1775 */
1776 static int stlink_swim_generate_rst(void *handle)
1777 {
1778 struct stlink_usb_handle_s *h = handle;
1779 int res;
1780
1781 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1782 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1783 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1784 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1785 if (res != ERROR_OK)
1786 return res;
1787 return ERROR_OK;
1788 }
1789
1790 /*
1791 send resynchronize sequence
1792 swim is pulled low for 16us
1793 reply is 64 clks low
1794 */
1795 static int stlink_swim_resync(void *handle)
1796 {
1797 struct stlink_usb_handle_s *h = handle;
1798 int res;
1799
1800 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1801 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1802 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_RESET;
1803 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1804 if (res != ERROR_OK)
1805 return res;
1806 return ERROR_OK;
1807 }
1808
1809 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1810 {
1811 struct stlink_usb_handle_s *h = handle;
1812 int res;
1813 unsigned int i;
1814 unsigned int datalen = 0;
1815 int cmdsize = STLINK_CMD_SIZE_V2;
1816
1817 if (len > STLINK_SWIM_DATA_SIZE)
1818 return ERROR_FAIL;
1819
1820 if (h->version.stlink == 1)
1821 cmdsize = STLINK_SG_SIZE;
1822
1823 stlink_usb_init_buffer(handle, h->tx_ep, 0);
1824 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1825 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1826 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1827 h->cmdidx += 2;
1828 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1829 h->cmdidx += 4;
1830 for (i = 0; i < len; i++) {
1831 if (h->cmdidx == cmdsize)
1832 h->databuf[datalen++] = *(data++);
1833 else
1834 h->cmdbuf[h->cmdidx++] = *(data++);
1835 }
1836 if (h->version.stlink == 1)
1837 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1838
1839 res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1840 if (res != ERROR_OK)
1841 return res;
1842 return ERROR_OK;
1843 }
1844
1845 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1846 {
1847 struct stlink_usb_handle_s *h = handle;
1848 int res;
1849
1850 if (len > STLINK_SWIM_DATA_SIZE)
1851 return ERROR_FAIL;
1852
1853 stlink_usb_init_buffer(handle, h->rx_ep, 0);
1854 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1855 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1856 h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1857 h->cmdidx += 2;
1858 h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1859 h->cmdidx += 4;
1860 res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1861 if (res != ERROR_OK)
1862 return res;
1863
1864 stlink_usb_init_buffer(handle, h->rx_ep, len);
1865 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1866 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1867 res = stlink_usb_xfer_noerrcheck(handle, data, len);
1868 if (res != ERROR_OK)
1869 return res;
1870
1871 return ERROR_OK;
1872 }
1873
1874 /** */
1875 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1876 {
1877 int res, offset;
1878 struct stlink_usb_handle_s *h = handle;
1879
1880 assert(handle);
1881
1882 /* there is no swim read core id cmd */
1883 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
1884 *idcode = 0;
1885 return ERROR_OK;
1886 }
1887
1888 stlink_usb_init_buffer(handle, h->rx_ep, 12);
1889
1890 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1891 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1892 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1893
1894 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1895 offset = 0;
1896 } else {
1897 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_IDCODES;
1898
1899 res = stlink_usb_xfer_errcheck(handle, h->databuf, 12);
1900 offset = 4;
1901 }
1902
1903 if (res != ERROR_OK)
1904 return res;
1905
1906 *idcode = le_to_h_u32(h->databuf + offset);
1907
1908 LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1909
1910 return ERROR_OK;
1911 }
1912
1913 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1914 {
1915 struct stlink_usb_handle_s *h = handle;
1916 int res;
1917
1918 assert(handle);
1919
1920 stlink_usb_init_buffer(handle, h->rx_ep, 8);
1921
1922 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1923 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1924 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1925 h->cmdidx += 4;
1926
1927 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1928 if (res != ERROR_OK)
1929 return res;
1930
1931 *val = le_to_h_u32(h->databuf + 4);
1932 return ERROR_OK;
1933 }
1934
1935 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1936 {
1937 struct stlink_usb_handle_s *h = handle;
1938
1939 assert(handle);
1940
1941 stlink_usb_init_buffer(handle, h->rx_ep, 2);
1942
1943 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1944 if (h->version.jtag_api == STLINK_JTAG_API_V1)
1945 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1946 else
1947 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1948 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1949 h->cmdidx += 4;
1950 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1951 h->cmdidx += 4;
1952
1953 return stlink_cmd_allow_retry(handle, h->databuf, 2);
1954 }
1955
1956 /** */
1957 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1958 {
1959 struct stlink_usb_handle_s *h = handle;
1960
1961 assert(handle);
1962
1963 if (h->trace.enabled && (h->version.flags & STLINK_F_HAS_TRACE)) {
1964 int res;
1965
1966 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1967
1968 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1969 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1970
1971 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1972 if (res != ERROR_OK)
1973 return res;
1974
1975 size_t bytes_avail = le_to_h_u16(h->databuf);
1976 *size = bytes_avail < *size ? bytes_avail : *size;
1977
1978 if (*size > 0) {
1979 res = stlink_usb_read_trace(handle, buf, *size);
1980 if (res != ERROR_OK)
1981 return res;
1982 return ERROR_OK;
1983 }
1984 }
1985 *size = 0;
1986 return ERROR_OK;
1987 }
1988
1989 static enum target_state stlink_usb_v2_get_status(void *handle)
1990 {
1991 int result;
1992 uint32_t status;
1993
1994 result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1995 if (result != ERROR_OK)
1996 return TARGET_UNKNOWN;
1997
1998 if (status & S_HALT)
1999 return TARGET_HALTED;
2000 else if (status & S_RESET_ST)
2001 return TARGET_RESET;
2002
2003 return TARGET_RUNNING;
2004 }
2005
2006 /** */
2007 static enum target_state stlink_usb_state(void *handle)
2008 {
2009 int res;
2010 struct stlink_usb_handle_s *h = handle;
2011
2012 assert(handle);
2013
2014 if (h->reconnect_pending) {
2015 LOG_INFO("Previous state query failed, trying to reconnect");
2016 res = stlink_usb_mode_enter(handle, h->st_mode);
2017 if (res != ERROR_OK)
2018 return TARGET_UNKNOWN;
2019
2020 h->reconnect_pending = false;
2021 }
2022
2023 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
2024 res = stlink_usb_v2_get_status(handle);
2025 if (res == TARGET_UNKNOWN)
2026 h->reconnect_pending = true;
2027 return res;
2028 }
2029
2030 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2031
2032 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2033 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
2034
2035 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
2036
2037 if (res != ERROR_OK)
2038 return TARGET_UNKNOWN;
2039
2040 if (h->databuf[0] == STLINK_CORE_RUNNING)
2041 return TARGET_RUNNING;
2042 if (h->databuf[0] == STLINK_CORE_HALTED)
2043 return TARGET_HALTED;
2044
2045 h->reconnect_pending = true;
2046
2047 return TARGET_UNKNOWN;
2048 }
2049
2050 static int stlink_usb_assert_srst(void *handle, int srst)
2051 {
2052 struct stlink_usb_handle_s *h = handle;
2053
2054 assert(handle);
2055
2056 if (h->st_mode == STLINK_MODE_DEBUG_SWIM)
2057 return stlink_swim_assert_reset(handle, srst);
2058
2059 if (h->version.stlink == 1)
2060 return ERROR_COMMAND_NOTFOUND;
2061
2062 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2063
2064 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2065 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
2066 h->cmdbuf[h->cmdidx++] = srst;
2067
2068 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2069 }
2070
2071 /** */
2072 static void stlink_usb_trace_disable(void *handle)
2073 {
2074 int res = ERROR_OK;
2075 struct stlink_usb_handle_s *h = handle;
2076
2077 assert(handle);
2078
2079 assert(h->version.flags & STLINK_F_HAS_TRACE);
2080
2081 LOG_DEBUG("Tracing: disable");
2082
2083 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2084 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2085 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
2086 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2087
2088 if (res == ERROR_OK)
2089 h->trace.enabled = false;
2090 }
2091
2092
2093 /** */
2094 static int stlink_usb_trace_enable(void *handle)
2095 {
2096 int res;
2097 struct stlink_usb_handle_s *h = handle;
2098
2099 assert(handle);
2100
2101 if (h->version.flags & STLINK_F_HAS_TRACE) {
2102 stlink_usb_init_buffer(handle, h->rx_ep, 10);
2103
2104 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2105 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
2106 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
2107 h->cmdidx += 2;
2108 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
2109 h->cmdidx += 4;
2110
2111 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2112
2113 if (res == ERROR_OK) {
2114 h->trace.enabled = true;
2115 LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
2116 }
2117 } else {
2118 LOG_ERROR("Tracing is not supported by this version.");
2119 res = ERROR_FAIL;
2120 }
2121
2122 return res;
2123 }
2124
2125 /** */
2126 static int stlink_usb_reset(void *handle)
2127 {
2128 struct stlink_usb_handle_s *h = handle;
2129 int retval;
2130
2131 assert(handle);
2132
2133 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2134
2135 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2136
2137 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2138 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
2139 else
2140 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
2141
2142 retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
2143 if (retval != ERROR_OK)
2144 return retval;
2145
2146 if (h->trace.enabled) {
2147 stlink_usb_trace_disable(h);
2148 return stlink_usb_trace_enable(h);
2149 }
2150
2151 return ERROR_OK;
2152 }
2153
2154 /** */
2155 static int stlink_usb_run(void *handle)
2156 {
2157 int res;
2158 struct stlink_usb_handle_s *h = handle;
2159
2160 assert(handle);
2161
2162 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
2163 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
2164
2165 return res;
2166 }
2167
2168 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2169
2170 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2171 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
2172
2173 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2174 }
2175
2176 /** */
2177 static int stlink_usb_halt(void *handle)
2178 {
2179 int res;
2180 struct stlink_usb_handle_s *h = handle;
2181
2182 assert(handle);
2183
2184 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
2185 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
2186
2187 return res;
2188 }
2189
2190 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2191
2192 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2193 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
2194
2195 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2196 }
2197
2198 /** */
2199 static int stlink_usb_step(void *handle)
2200 {
2201 struct stlink_usb_handle_s *h = handle;
2202
2203 assert(handle);
2204
2205 if (h->version.jtag_api != STLINK_JTAG_API_V1) {
2206 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
2207 * that the Cortex-M3 currently does. */
2208 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
2209 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
2210 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
2211 }
2212
2213 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2214
2215 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2216 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
2217
2218 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2219 }
2220
2221 /** */
2222 static int stlink_usb_read_regs(void *handle)
2223 {
2224 int res;
2225 struct stlink_usb_handle_s *h = handle;
2226
2227 assert(handle);
2228
2229 stlink_usb_init_buffer(handle, h->rx_ep, 88);
2230
2231 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2232 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2233
2234 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
2235 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 84);
2236 /* regs data from offset 0 */
2237 } else {
2238 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
2239 res = stlink_usb_xfer_errcheck(handle, h->databuf, 88);
2240 /* status at offset 0, regs data from offset 4 */
2241 }
2242
2243 return res;
2244 }
2245
2246 /** */
2247 static int stlink_usb_read_reg(void *handle, unsigned int regsel, uint32_t *val)
2248 {
2249 int res;
2250 struct stlink_usb_handle_s *h = handle;
2251
2252 assert(handle);
2253
2254 if (STLINK_REGSEL_IS_FPU(regsel) && !(h->version.flags & STLINK_F_HAS_FPU_REG)) {
2255 res = stlink_usb_write_debug_reg(h, DCB_DCRSR, regsel & 0x7f);
2256 if (res != ERROR_OK)
2257 return res;
2258
2259 /* FIXME: poll DHCSR.S_REGRDY before read DCRDR */
2260 return stlink_usb_v2_read_debug_reg(h, DCB_DCRDR, val);
2261 }
2262
2263 stlink_usb_init_buffer(handle, h->rx_ep, h->version.jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
2264
2265 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2266 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2267 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
2268 else
2269 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
2270 h->cmdbuf[h->cmdidx++] = regsel;
2271
2272 if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2273 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
2274 if (res != ERROR_OK)
2275 return res;
2276 *val = le_to_h_u32(h->databuf);
2277 return ERROR_OK;
2278 } else {
2279 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
2280 if (res != ERROR_OK)
2281 return res;
2282 *val = le_to_h_u32(h->databuf + 4);
2283 return ERROR_OK;
2284 }
2285 }
2286
2287 /** */
2288 static int stlink_usb_write_reg(void *handle, unsigned int regsel, uint32_t val)
2289 {
2290 struct stlink_usb_handle_s *h = handle;
2291
2292 assert(handle);
2293
2294 if (STLINK_REGSEL_IS_FPU(regsel) && !(h->version.flags & STLINK_F_HAS_FPU_REG)) {
2295 int res = stlink_usb_write_debug_reg(h, DCB_DCRDR, val);
2296 if (res != ERROR_OK)
2297 return res;
2298
2299 return stlink_usb_write_debug_reg(h, DCB_DCRSR, DCRSR_WNR | (regsel & 0x7f));
2300 /* FIXME: poll DHCSR.S_REGRDY after write DCRSR */
2301 }
2302
2303 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2304
2305 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2306 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2307 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
2308 else
2309 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
2310 h->cmdbuf[h->cmdidx++] = regsel;
2311 h_u32_to_le(h->cmdbuf+h->cmdidx, val);
2312 h->cmdidx += 4;
2313
2314 return stlink_cmd_allow_retry(handle, h->databuf, 2);
2315 }
2316
2317 static int stlink_usb_get_rw_status(void *handle)
2318 {
2319 struct stlink_usb_handle_s *h = handle;
2320
2321 assert(handle);
2322
2323 if (h->version.jtag_api == STLINK_JTAG_API_V1)
2324 return ERROR_OK;
2325
2326 stlink_usb_init_buffer(handle, h->rx_ep, 2);
2327
2328 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2329 if (h->version.flags & STLINK_F_HAS_GETLASTRWSTATUS2) {
2330 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS2;
2331 return stlink_usb_xfer_errcheck(handle, h->databuf, 12);
2332 } else {
2333 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
2334 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2335 }
2336 }
2337
2338 /** */
2339 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
2340 uint8_t *buffer)
2341 {
2342 int res;
2343 uint16_t read_len = len;
2344 struct stlink_usb_handle_s *h = handle;
2345
2346 assert(handle);
2347
2348 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2349 if (len > stlink_usb_block(h)) {
2350 LOG_DEBUG("max buffer (%d) length exceeded", stlink_usb_block(h));
2351 return ERROR_FAIL;
2352 }
2353
2354 stlink_usb_init_buffer(handle, h->rx_ep, read_len);
2355
2356 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2357 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
2358 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2359 h->cmdidx += 4;
2360 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2361 h->cmdidx += 2;
2362
2363 /* we need to fix read length for single bytes */
2364 if (read_len == 1)
2365 read_len++;
2366
2367 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, read_len);
2368
2369 if (res != ERROR_OK)
2370 return res;
2371
2372 memcpy(buffer, h->databuf, len);
2373
2374 return stlink_usb_get_rw_status(handle);
2375 }
2376
2377 /** */
2378 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
2379 const uint8_t *buffer)
2380 {
2381 int res;
2382 struct stlink_usb_handle_s *h = handle;
2383
2384 assert(handle);
2385
2386 /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2387 if (len > stlink_usb_block(h)) {
2388 LOG_DEBUG("max buffer length (%d) exceeded", stlink_usb_block(h));
2389 return ERROR_FAIL;
2390 }
2391
2392 stlink_usb_init_buffer(handle, h->tx_ep, len);
2393
2394 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2395 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
2396 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2397 h->cmdidx += 4;
2398 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2399 h->cmdidx += 2;
2400
2401 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2402
2403 if (res != ERROR_OK)
2404 return res;
2405
2406 return stlink_usb_get_rw_status(handle);
2407 }
2408
2409 /** */
2410 static int stlink_usb_read_mem16(void *handle, uint32_t addr, uint16_t len,
2411 uint8_t *buffer)
2412 {
2413 int res;
2414 struct stlink_usb_handle_s *h = handle;
2415
2416 assert(handle);
2417
2418 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2419 return ERROR_COMMAND_NOTFOUND;
2420
2421 if (len > STLINK_MAX_RW16_32) {
2422 LOG_DEBUG("max buffer (%d) length exceeded", STLINK_MAX_RW16_32);
2423 return ERROR_FAIL;
2424 }
2425
2426 /* data must be a multiple of 2 and half-word aligned */
2427 if (len % 2 || addr % 2) {
2428 LOG_DEBUG("Invalid data alignment");
2429 return ERROR_TARGET_UNALIGNED_ACCESS;
2430 }
2431
2432 stlink_usb_init_buffer(handle, h->rx_ep, len);
2433
2434 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2435 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READMEM_16BIT;
2436 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2437 h->cmdidx += 4;
2438 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2439 h->cmdidx += 2;
2440
2441 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2442
2443 if (res != ERROR_OK)
2444 return res;
2445
2446 memcpy(buffer, h->databuf, len);
2447
2448 return stlink_usb_get_rw_status(handle);
2449 }
2450
2451 /** */
2452 static int stlink_usb_write_mem16(void *handle, uint32_t addr, uint16_t len,
2453 const uint8_t *buffer)
2454 {
2455 int res;
2456 struct stlink_usb_handle_s *h = handle;
2457
2458 assert(handle);
2459
2460 if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2461 return ERROR_COMMAND_NOTFOUND;
2462
2463 if (len > STLINK_MAX_RW16_32) {
2464 LOG_DEBUG("max buffer (%d) length exceeded", STLINK_MAX_RW16_32);
2465 return ERROR_FAIL;
2466 }
2467
2468 /* data must be a multiple of 2 and half-word aligned */
2469 if (len % 2 || addr % 2) {
2470 LOG_DEBUG("Invalid data alignment");
2471 return ERROR_TARGET_UNALIGNED_ACCESS;
2472 }
2473
2474 stlink_usb_init_buffer(handle, h->tx_ep, len);
2475
2476 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2477 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEMEM_16BIT;
2478 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2479 h->cmdidx += 4;
2480 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2481 h->cmdidx += 2;
2482
2483 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2484
2485 if (res != ERROR_OK)
2486 return res;
2487
2488 return stlink_usb_get_rw_status(handle);
2489 }
2490
2491 /** */
2492 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
2493 uint8_t *buffer)
2494 {
2495 int res;
2496 struct stlink_usb_handle_s *h = handle;
2497
2498 assert(handle);
2499
2500 if (len > STLINK_MAX_RW16_32) {
2501 LOG_DEBUG("max buffer (%d) length exceeded", STLINK_MAX_RW16_32);
2502 return ERROR_FAIL;
2503 }
2504
2505 /* data must be a multiple of 4 and word aligned */
2506 if (len % 4 || addr % 4) {
2507 LOG_DEBUG("Invalid data alignment");
2508 return ERROR_TARGET_UNALIGNED_ACCESS;
2509 }
2510
2511 stlink_usb_init_buffer(handle, h->rx_ep, len);
2512
2513 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2514 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
2515 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2516 h->cmdidx += 4;
2517 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2518 h->cmdidx += 2;
2519
2520 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2521
2522 if (res != ERROR_OK)
2523 return res;
2524
2525 memcpy(buffer, h->databuf, len);
2526
2527 return stlink_usb_get_rw_status(handle);
2528 }
2529
2530 /** */
2531 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
2532 const uint8_t *buffer)
2533 {
2534 int res;
2535 struct stlink_usb_handle_s *h = handle;
2536
2537 assert(handle);
2538
2539 if (len > STLINK_MAX_RW16_32) {
2540 LOG_DEBUG("max buffer (%d) length exceeded", STLINK_MAX_RW16_32);
2541 return ERROR_FAIL;
2542 }
2543
2544 /* data must be a multiple of 4 and word aligned */
2545 if (len % 4 || addr % 4) {
2546 LOG_DEBUG("Invalid data alignment");
2547 return ERROR_TARGET_UNALIGNED_ACCESS;
2548 }
2549
2550 stlink_usb_init_buffer(handle, h->tx_ep, len);
2551
2552 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2553 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
2554 h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2555 h->cmdidx += 4;
2556 h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2557 h->cmdidx += 2;
2558
2559 res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2560
2561 if (res != ERROR_OK)
2562 return res;
2563
2564 return stlink_usb_get_rw_status(handle);
2565 }
2566
2567 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
2568 {
2569 uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
2570 if (max_tar_block == 0)
2571 max_tar_block = 4;
2572 return max_tar_block;
2573 }
2574
2575 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
2576 uint32_t count, uint8_t *buffer)
2577 {
2578 int retval = ERROR_OK;
2579 uint32_t bytes_remaining;
2580 int retries = 0;
2581 struct stlink_usb_handle_s *h = handle;
2582
2583 /* calculate byte count */
2584 count *= size;
2585
2586 /* switch to 8 bit if stlink does not support 16 bit memory read */
2587 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2588 size = 1;
2589
2590 while (count) {
2591
2592 bytes_remaining = (size != 1) ?
2593 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2594
2595 if (count < bytes_remaining)
2596 bytes_remaining = count;
2597
2598 /*
2599 * all stlink support 8/32bit memory read/writes and only from
2600 * stlink V2J26 there is support for 16 bit memory read/write.
2601 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2602 * as 8bit access.
2603 */
2604 if (size != 1) {
2605
2606 /* When in jtag mode the stlink uses the auto-increment functionality.
2607 * However it expects us to pass the data correctly, this includes
2608 * alignment and any page boundaries. We already do this as part of the
2609 * adi_v5 implementation, but the stlink is a hla adapter and so this
2610 * needs implementing manually.
2611 * currently this only affects jtag mode, according to ST they do single
2612 * access in SWD mode - but this may change and so we do it for both modes */
2613
2614 /* we first need to check for any unaligned bytes */
2615 if (addr & (size - 1)) {
2616
2617 uint32_t head_bytes = size - (addr & (size - 1));
2618 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
2619 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2620 usleep((1<<retries++) * 1000);
2621 continue;
2622 }
2623 if (retval != ERROR_OK)
2624 return retval;
2625 buffer += head_bytes;
2626 addr += head_bytes;
2627 count -= head_bytes;
2628 bytes_remaining -= head_bytes;
2629 }
2630
2631 if (bytes_remaining & (size - 1))
2632 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
2633 else if (size == 2)
2634 retval = stlink_usb_read_mem16(handle, addr, bytes_remaining, buffer);
2635 else
2636 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
2637 } else
2638 retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
2639
2640 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2641 usleep((1<<retries++) * 1000);
2642 continue;
2643 }
2644 if (retval != ERROR_OK)
2645 return retval;
2646
2647 buffer += bytes_remaining;
2648 addr += bytes_remaining;
2649 count -= bytes_remaining;
2650 }
2651
2652 return retval;
2653 }
2654
2655 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
2656 uint32_t count, const uint8_t *buffer)
2657 {
2658 int retval = ERROR_OK;
2659 uint32_t bytes_remaining;
2660 int retries = 0;
2661 struct stlink_usb_handle_s *h = handle;
2662
2663 /* calculate byte count */
2664 count *= size;
2665
2666 /* switch to 8 bit if stlink does not support 16 bit memory read */
2667 if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2668 size = 1;
2669
2670 while (count) {
2671
2672 bytes_remaining = (size != 1) ?
2673 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2674
2675 if (count < bytes_remaining)
2676 bytes_remaining = count;
2677
2678 /*
2679 * all stlink support 8/32bit memory read/writes and only from
2680 * stlink V2J26 there is support for 16 bit memory read/write.
2681 * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2682 * as 8bit access.
2683 */
2684 if (size != 1) {
2685
2686 /* When in jtag mode the stlink uses the auto-increment functionality.
2687 * However it expects us to pass the data correctly, this includes
2688 * alignment and any page boundaries. We already do this as part of the
2689 * adi_v5 implementation, but the stlink is a hla adapter and so this
2690 * needs implementing manually.
2691 * currently this only affects jtag mode, according to ST they do single
2692 * access in SWD mode - but this may change and so we do it for both modes */
2693
2694 /* we first need to check for any unaligned bytes */
2695 if (addr & (size - 1)) {
2696
2697 uint32_t head_bytes = size - (addr & (size - 1));
2698 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
2699 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2700 usleep((1<<retries++) * 1000);
2701 continue;
2702 }
2703 if (retval != ERROR_OK)
2704 return retval;
2705 buffer += head_bytes;
2706 addr += head_bytes;
2707 count -= head_bytes;
2708 bytes_remaining -= head_bytes;
2709 }
2710
2711 if (bytes_remaining & (size - 1))
2712 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
2713 else if (size == 2)
2714 retval = stlink_usb_write_mem16(handle, addr, bytes_remaining, buffer);
2715 else
2716 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
2717
2718 } else
2719 retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
2720 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2721 usleep((1<<retries++) * 1000);
2722 continue;
2723 }
2724 if (retval != ERROR_OK)
2725 return retval;
2726
2727 buffer += bytes_remaining;
2728 addr += bytes_remaining;
2729 count -= bytes_remaining;
2730 }
2731
2732 return retval;
2733 }
2734
2735 /** */
2736 static int stlink_usb_override_target(const char *targetname)
2737 {
2738 return !strcmp(targetname, "cortex_m");
2739 }
2740
2741 static int stlink_speed_swim(void *handle, int khz, bool query)
2742 {
2743 int retval;
2744
2745 /*
2746 we only have low and high speed...
2747 before changing speed the SWIM_CSR HS bit
2748 must be updated
2749 */
2750 if (!query) {
2751 retval = stlink_swim_speed(handle, (khz < SWIM_FREQ_HIGH) ? 0 : 1);
2752 if (retval != ERROR_OK)
2753 LOG_ERROR("Unable to set adapter speed");
2754 }
2755
2756 return (khz < SWIM_FREQ_HIGH) ? SWIM_FREQ_LOW : SWIM_FREQ_HIGH;
2757 }
2758
2759 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
2760 {
2761 unsigned int i;
2762 int speed_index = -1;
2763 int speed_diff = INT_MAX;
2764 int last_valid_speed = -1;
2765 bool match = true;
2766
2767 for (i = 0; i < map_size; i++) {
2768 if (!map[i].speed)
2769 continue;
2770 last_valid_speed = i;
2771 if (khz == map[i].speed) {
2772 speed_index = i;
2773 break;
2774 } else {
2775 int current_diff = khz - map[i].speed;
2776 /* get abs value for comparison */
2777 current_diff = (current_diff > 0) ? current_diff : -current_diff;
2778 if ((current_diff < speed_diff) && khz >= map[i].speed) {
2779 speed_diff = current_diff;
2780 speed_index = i;
2781 }
2782 }
2783 }
2784
2785 if (speed_index == -1) {
2786 /* this will only be here if we cannot match the slow speed.
2787 * use the slowest speed we support.*/
2788 speed_index = last_valid_speed;
2789 match = false;
2790 } else if (i == map_size)
2791 match = false;
2792
2793 if (!match && query) {
2794 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz",
2795 khz, map[speed_index].speed);
2796 }
2797
2798 return speed_index;
2799 }
2800
2801 static int stlink_speed_swd(void *handle, int khz, bool query)
2802 {
2803 int speed_index;
2804 struct stlink_usb_handle_s *h = handle;
2805
2806 /* old firmware cannot change it */
2807 if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
2808 return khz;
2809
2810 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
2811 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
2812
2813 if (!query) {
2814 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
2815 if (result != ERROR_OK) {
2816 LOG_ERROR("Unable to set adapter speed");
2817 return khz;
2818 }
2819 }
2820
2821 return stlink_khz_to_speed_map_swd[speed_index].speed;
2822 }
2823
2824 static int stlink_speed_jtag(void *handle, int khz, bool query)
2825 {
2826 int speed_index;
2827 struct stlink_usb_handle_s *h = handle;
2828
2829 /* old firmware cannot change it */
2830 if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
2831 return khz;
2832
2833 speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2834 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2835
2836 if (!query) {
2837 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2838 if (result != ERROR_OK) {
2839 LOG_ERROR("Unable to set adapter speed");
2840 return khz;
2841 }
2842 }
2843
2844 return stlink_khz_to_speed_map_jtag[speed_index].speed;
2845 }
2846
2847 static void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2848 {
2849 unsigned int i;
2850
2851 LOG_DEBUG("Supported clock speeds are:");
2852 for (i = 0; i < map_size; i++)
2853 if (map[i].speed)
2854 LOG_DEBUG("%d kHz", map[i].speed);
2855 }
2856
2857 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map)
2858 {
2859 struct stlink_usb_handle_s *h = handle;
2860 int i;
2861
2862 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2863 LOG_ERROR("Unknown command");
2864 return 0;
2865 }
2866
2867 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2868
2869 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2870 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_COM_FREQ;
2871 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2872
2873 int res = stlink_usb_xfer_errcheck(handle, h->databuf, 52);
2874
2875 int size = h->databuf[8];
2876
2877 if (size > STLINK_V3_MAX_FREQ_NB)
2878 size = STLINK_V3_MAX_FREQ_NB;
2879
2880 for (i = 0; i < size; i++) {
2881 map[i].speed = le_to_h_u32(&h->databuf[12 + 4 * i]);
2882 map[i].speed_divisor = i;
2883 }
2884
2885 /* set to zero all the next entries */
2886 for (i = size; i < STLINK_V3_MAX_FREQ_NB; i++)
2887 map[i].speed = 0;
2888
2889 return res;
2890 }
2891
2892 static int stlink_set_com_freq(void *handle, bool is_jtag, unsigned int frequency)
2893 {
2894 struct stlink_usb_handle_s *h = handle;
2895
2896 if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2897 LOG_ERROR("Unknown command");
2898 return 0;
2899 }
2900
2901 stlink_usb_init_buffer(handle, h->rx_ep, 16);
2902
2903 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2904 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_SET_COM_FREQ;
2905 h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2906 h->cmdbuf[h->cmdidx++] = 0;
2907
2908 h_u32_to_le(&h->cmdbuf[4], frequency);
2909
2910 return stlink_usb_xfer_errcheck(handle, h->databuf, 8);
2911 }
2912
2913 static int stlink_speed_v3(void *handle, bool is_jtag, int khz, bool query)
2914 {
2915 struct stlink_usb_handle_s *h = handle;
2916 int speed_index;
2917 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
2918
2919 stlink_get_com_freq(h, is_jtag, map);
2920
2921 speed_index = stlink_match_speed_map(map, ARRAY_SIZE(map), khz, query);
2922
2923 if (!query) {
2924 int result = stlink_set_com_freq(h, is_jtag, map[speed_index].speed);
2925 if (result != ERROR_OK) {
2926 LOG_ERROR("Unable to set adapter speed");
2927 return khz;
2928 }
2929 }
2930 return map[speed_index].speed;
2931 }
2932
2933 static int stlink_speed(void *handle, int khz, bool query)
2934 {
2935 struct stlink_usb_handle_s *h = handle;
2936
2937 if (!handle)
2938 return khz;
2939
2940 switch (h->st_mode) {
2941 case STLINK_MODE_DEBUG_SWIM:
2942 return stlink_speed_swim(handle, khz, query);
2943 case STLINK_MODE_DEBUG_SWD:
2944 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2945 return stlink_speed_v3(handle, false, khz, query);
2946 else
2947 return stlink_speed_swd(handle, khz, query);
2948 break;
2949 case STLINK_MODE_DEBUG_JTAG:
2950 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2951 return stlink_speed_v3(handle, true, khz, query);
2952 else
2953 return stlink_speed_jtag(handle, khz, query);
2954 break;
2955 default:
2956 break;
2957 }
2958
2959 return khz;
2960 }
2961
2962 /** */
2963 static int stlink_usb_usb_close(void *handle)
2964 {
2965 struct stlink_usb_handle_s *h = handle;
2966
2967 if (!h)
2968 return ERROR_OK;
2969
2970 if (h->usb_backend_priv.fd) {
2971 stlink_usb_exit_mode(h);
2972 /* do not check return code, it prevent
2973 us from closing jtag_libusb */
2974 jtag_libusb_close(h->usb_backend_priv.fd);
2975 }
2976
2977 free(h->cmdbuf);
2978 free(h->databuf);
2979
2980 return ERROR_OK;
2981 }
2982
2983 /** */
2984 static int stlink_tcp_close(void *handle)
2985 {
2986 struct stlink_usb_handle_s *h = handle;
2987
2988 if (!h)
2989 return ERROR_OK;
2990
2991 int ret = ERROR_OK;
2992 if (h->tcp_backend_priv.connected) {
2993 if (h->tcp_backend_priv.connect_id) {
2994 stlink_usb_exit_mode(h);
2995
2996 /* close the stlink */
2997 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_CLOSE_DEV;
2998 memset(&h->tcp_backend_priv.send_buf[1], 0, 4); /* reserved */
2999 h_u32_to_le(&h->tcp_backend_priv.send_buf[4], h->tcp_backend_priv.connect_id);
3000 ret = stlink_tcp_send_cmd(h, 8, 4, true);
3001 if (ret != ERROR_OK)
3002 LOG_ERROR("cannot close the STLINK");
3003 }
3004
3005 if (close_socket(h->tcp_backend_priv.fd) != 0)
3006 LOG_ERROR("error closing the socket, errno: %s", strerror(errno));
3007 }
3008
3009 free(h->tcp_backend_priv.send_buf);
3010 free(h->tcp_backend_priv.recv_buf);
3011
3012 return ret;
3013 }
3014
3015 /** */
3016 static int stlink_close(void *handle)
3017 {
3018 if (handle) {
3019 struct stlink_usb_handle_s *h = handle;
3020
3021 stlink_usb_close(handle);
3022
3023 free(h);
3024 }
3025
3026 return ERROR_OK;
3027 }
3028
3029 /* Compute ST-Link serial number from the device descriptor
3030 * this function will help to work-around a bug in old ST-Link/V2 DFU
3031 * the buggy DFU returns an incorrect serial in the USB descriptor
3032 * example for the following serial "57FF72067265575742132067"
3033 * - the correct descriptor serial is:
3034 * 0x32, 0x03, 0x35, 0x00, 0x37, 0x00, 0x46, 0x00, 0x46, 0x00, 0x37, 0x00, 0x32, 0x00 ...
3035 * this contains the length (0x32 = 50), the type (0x3 = DT_STRING) and the serial in unicode format
3036 * the serial part is: 0x0035, 0x0037, 0x0046, 0x0046, 0x0037, 0x0032 ... >> 57FF72 ...
3037 * this format could be read correctly by 'libusb_get_string_descriptor_ascii'
3038 * so this case is managed by libusb_helper::string_descriptor_equal
3039 * - the buggy DFU is not doing any unicode conversion and returns a raw serial data in the descriptor
3040 * 0x1a, 0x03, 0x57, 0x00, 0xFF, 0x00, 0x72, 0x00 ...
3041 * >> 57 FF 72 ...
3042 * based on the length (0x1a = 26) we could easily decide if we have to fixup the serial
3043 * and then we have just to convert the raw data into printable characters using sprintf
3044 */
3045 static char *stlink_usb_get_alternate_serial(struct libusb_device_handle *device,
3046 struct libusb_device_descriptor *dev_desc)
3047 {
3048 int usb_retval;
3049 unsigned char desc_serial[(STLINK_SERIAL_LEN + 1) * 2];
3050
3051 if (dev_desc->iSerialNumber == 0)
3052 return NULL;
3053
3054 /* get the LANGID from String Descriptor Zero */
3055 usb_retval = libusb_get_string_descriptor(device, 0, 0, desc_serial,
3056 sizeof(desc_serial));
3057
3058 if (usb_retval < LIBUSB_SUCCESS) {
3059 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
3060 libusb_error_name(usb_retval), usb_retval);
3061 return NULL;
3062 } else if (usb_retval < 4) {
3063 /* the size should be least 4 bytes to contain a minimum of 1 supported LANGID */
3064 LOG_ERROR("could not get the LANGID");
3065 return NULL;
3066 }
3067
3068 uint32_t langid = desc_serial[2] | (desc_serial[3] << 8);
3069
3070 /* get the serial */
3071 usb_retval = libusb_get_string_descriptor(device, dev_desc->iSerialNumber,
3072 langid, desc_serial, sizeof(desc_serial));
3073
3074 unsigned char len = desc_serial[0];
3075
3076 if (usb_retval < LIBUSB_SUCCESS) {
3077 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
3078 libusb_error_name(usb_retval), usb_retval);
3079 return NULL;
3080 } else if (desc_serial[1] != LIBUSB_DT_STRING || len > usb_retval) {
3081 LOG_ERROR("invalid string in ST-LINK USB serial descriptor");
3082 return NULL;
3083 }
3084
3085 if (len == ((STLINK_SERIAL_LEN + 1) * 2)) {
3086 /* good ST-Link adapter, this case is managed by
3087 * libusb::libusb_get_string_descriptor_ascii */
3088 return NULL;
3089 } else if (len != ((STLINK_SERIAL_LEN / 2 + 1) * 2)) {
3090 LOG_ERROR("unexpected serial length (%d) in descriptor", len);
3091 return NULL;
3092 }
3093
3094 /* else (len == 26) => buggy ST-Link */
3095
3096 char *alternate_serial = malloc((STLINK_SERIAL_LEN + 1) * sizeof(char));
3097 if (!alternate_serial)
3098 return NULL;
3099
3100 for (unsigned int i = 0; i < STLINK_SERIAL_LEN; i += 2)
3101 sprintf(alternate_serial + i, "%02X", desc_serial[i + 2]);
3102
3103 alternate_serial[STLINK_SERIAL_LEN] = '\0';
3104
3105 return alternate_serial;
3106 }
3107
3108 /** */
3109 static int stlink_usb_usb_open(void *handle, struct hl_interface_param_s *param)
3110 {
3111 struct stlink_usb_handle_s *h = handle;
3112 int err, retry_count = 1;
3113
3114 h->cmdbuf = malloc(STLINK_SG_SIZE);
3115 h->databuf = malloc(STLINK_DATA_SIZE);
3116
3117 if (!h->cmdbuf || !h->databuf)
3118 return ERROR_FAIL;
3119
3120 /*
3121 On certain host USB configurations(e.g. MacBook Air)
3122 STLINKv2 dongle seems to have its FW in a funky state if,
3123 after plugging it in, you try to use openocd with it more
3124 then once (by launching and closing openocd). In cases like
3125 that initial attempt to read the FW info via
3126 stlink_usb_version will fail and the device has to be reset
3127 in order to become operational.
3128 */
3129 do {
3130 if (jtag_libusb_open(param->vid, param->pid, param->serial,
3131 &h->usb_backend_priv.fd, stlink_usb_get_alternate_serial) != ERROR_OK) {
3132 LOG_ERROR("open failed");
3133 return ERROR_FAIL;
3134 }
3135
3136 jtag_libusb_set_configuration(h->usb_backend_priv.fd, 0);
3137
3138 if (libusb_claim_interface(h->usb_backend_priv.fd, 0) != ERROR_OK) {
3139 LOG_DEBUG("claim interface failed");
3140 return ERROR_FAIL;
3141 }
3142
3143 /* RX EP is common for all versions */
3144 h->rx_ep = STLINK_RX_EP;
3145
3146 uint16_t pid;
3147 if (jtag_libusb_get_pid(libusb_get_device(h->usb_backend_priv.fd), &pid) != ERROR_OK) {
3148 LOG_DEBUG("libusb_get_pid failed");
3149 return ERROR_FAIL;
3150 }
3151
3152 /* wrap version for first read */
3153 switch (pid) {
3154 case STLINK_V1_PID:
3155 h->version.stlink = 1;
3156 h->tx_ep = STLINK_TX_EP;
3157 break;
3158 case STLINK_V3_USBLOADER_PID:
3159 case STLINK_V3E_PID:
3160 case STLINK_V3S_PID:
3161 case STLINK_V3_2VCP_PID:
3162 case STLINK_V3E_NO_MSD_PID:
3163 h->version.stlink = 3;
3164 h->tx_ep = STLINK_V2_1_TX_EP;
3165 h->trace_ep = STLINK_V2_1_TRACE_EP;
3166 break;
3167 case STLINK_V2_1_PID:
3168 case STLINK_V2_1_NO_MSD_PID:
3169 h->version.stlink = 2;
3170 h->tx_ep = STLINK_V2_1_TX_EP;
3171 h->trace_ep = STLINK_V2_1_TRACE_EP;
3172 break;
3173 default:
3174 /* fall through - we assume V2 to be the default version*/
3175 case STLINK_V2_PID:
3176 h->version.stlink = 2;
3177 h->tx_ep = STLINK_TX_EP;
3178 h->trace_ep = STLINK_TRACE_EP;
3179 break;
3180 }
3181
3182 /* get the device version */
3183 err = stlink_usb_version(h);
3184
3185 if (err == ERROR_OK) {
3186 break;
3187 } else if (h->version.stlink == 1 ||
3188 retry_count == 0) {
3189 LOG_ERROR("read version failed");
3190 return ERROR_FAIL;
3191 } else {
3192 err = libusb_release_interface(h->usb_backend_priv.fd, 0);
3193 if (err != ERROR_OK) {
3194 LOG_ERROR("release interface failed");
3195 return ERROR_FAIL;
3196 }
3197
3198 err = libusb_reset_device(h->usb_backend_priv.fd);
3199 if (err != ERROR_OK) {
3200 LOG_ERROR("reset device failed");
3201 return ERROR_FAIL;
3202 }
3203
3204 jtag_libusb_close(h->usb_backend_priv.fd);
3205 /*
3206 Give the device one second to settle down and
3207 reenumerate.
3208 */
3209 usleep(1 * 1000 * 1000);
3210 retry_count--;
3211 }
3212 } while (1);
3213
3214 return ERROR_OK;
3215 }
3216
3217 /** */
3218 static int stlink_tcp_open(void *handle, struct hl_interface_param_s *param)
3219 {
3220 struct stlink_usb_handle_s *h = handle;
3221 int ret;
3222
3223 /* SWIM is not supported using stlink-server */
3224 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
3225 LOG_ERROR("stlink-server does not support SWIM mode");
3226 return ERROR_FAIL;
3227 }
3228
3229 h->tcp_backend_priv.send_buf = malloc(STLINK_TCP_SEND_BUFFER_SIZE);
3230 h->tcp_backend_priv.recv_buf = malloc(STLINK_TCP_RECV_BUFFER_SIZE);
3231
3232 if (!h->tcp_backend_priv.send_buf || !h->tcp_backend_priv.recv_buf)
3233 return ERROR_FAIL;
3234
3235 h->cmdbuf = &h->tcp_backend_priv.send_buf[8];
3236 h->databuf = &h->tcp_backend_priv.recv_buf[4];
3237
3238 /* configure directions */
3239 h->rx_ep = STLINK_TCP_REQUEST_READ;
3240 h->tx_ep = STLINK_TCP_REQUEST_WRITE;
3241 h->trace_ep = STLINK_TCP_REQUEST_READ_SWO;
3242
3243 h->tcp_backend_priv.fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
3244 h->tcp_backend_priv.connected = false;
3245 h->tcp_backend_priv.device_id = 0;
3246 h->tcp_backend_priv.connect_id = 0;
3247
3248 if (h->tcp_backend_priv.fd == -1) {
3249 LOG_ERROR("error creating the socket, errno: %s", strerror(errno));
3250 return ERROR_FAIL;
3251 }
3252
3253 struct sockaddr_in serv;
3254 memset(&serv, 0, sizeof(struct sockaddr_in));
3255 serv.sin_family = AF_INET;
3256 serv.sin_port = htons(param->stlink_tcp_port);
3257 serv.sin_addr.s_addr = inet_addr("127.0.0.1");
3258
3259 LOG_DEBUG("socket : %x", h->tcp_backend_priv.fd);
3260
3261 int optval = 1;
3262 if (setsockopt(h->tcp_backend_priv.fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&optval, sizeof(int)) == -1) {
3263 LOG_ERROR("cannot set sock option 'TCP_NODELAY', errno: %s", strerror(errno));
3264 return ERROR_FAIL;
3265 }
3266
3267 optval = STLINK_TCP_RECV_BUFFER_SIZE;
3268 if (setsockopt(h->tcp_backend_priv.fd, SOL_SOCKET, SO_RCVBUF, (const void *)&optval, sizeof(int)) == -1) {
3269 LOG_ERROR("cannot set sock option 'SO_RCVBUF', errno: %s", strerror(errno));
3270 return ERROR_FAIL;
3271 }
3272
3273 optval = STLINK_TCP_SEND_BUFFER_SIZE;
3274 if (setsockopt(h->tcp_backend_priv.fd, SOL_SOCKET, SO_SNDBUF, (const void *)&optval, sizeof(int)) == -1) {
3275 LOG_ERROR("cannot set sock option 'SO_SNDBUF', errno: %s", strerror(errno));
3276 return ERROR_FAIL;
3277 }
3278
3279 if (connect(h->tcp_backend_priv.fd, (const struct sockaddr *)&serv, sizeof(serv)) == -1) {
3280 LOG_ERROR("cannot connect to stlink server, errno: %s", strerror(errno));
3281 return ERROR_FAIL;
3282 }
3283
3284 h->tcp_backend_priv.connected = true;
3285
3286 LOG_INFO("connected to stlink-server");
3287
3288 /* print stlink-server version */
3289 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_GET_SERVER_VERSION;
3290 h->tcp_backend_priv.send_buf[1] = OPENOCD_STLINK_TCP_API_VERSION;
3291 memset(&h->tcp_backend_priv.send_buf[2], 0, 2); /* reserved */
3292 ret = stlink_tcp_send_cmd(h, 4, 16, false);
3293 if (ret != ERROR_OK) {
3294 LOG_ERROR("cannot get the stlink-server version");
3295 return ERROR_FAIL;
3296 }
3297
3298 uint32_t api_ver = le_to_h_u32(&h->tcp_backend_priv.recv_buf[0]);
3299 uint32_t ver_major = le_to_h_u32(&h->tcp_backend_priv.recv_buf[4]);
3300 uint32_t ver_minor = le_to_h_u32(&h->tcp_backend_priv.recv_buf[8]);
3301 uint32_t ver_build = le_to_h_u32(&h->tcp_backend_priv.recv_buf[12]);
3302 LOG_INFO("stlink-server API v%d, version %d.%d.%d",
3303 api_ver, ver_major, ver_minor, ver_build);
3304
3305 /* in stlink-server API v1 sending more than 1428 bytes will cause stlink-server
3306 * to crash in windows: select a safe default value (1K) */
3307 if (api_ver < 2)
3308 h->max_mem_packet = (1 << 10);
3309
3310 /* refresh stlink list (re-enumerate) */
3311 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_REFRESH_DEVICE_LIST;
3312 h->tcp_backend_priv.send_buf[1] = 0; /* don't clear the list, just refresh it */
3313 ret = stlink_tcp_send_cmd(h, 2, 4, true);
3314 if (ret != ERROR_OK)
3315 return ret;
3316
3317 /* get the number of connected stlinks */
3318 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_GET_NB_DEV;
3319 ret = stlink_tcp_send_cmd(h, 1, 4, false);
3320 if (ret != ERROR_OK)
3321 return ret;
3322
3323 uint32_t connected_stlinks = le_to_h_u32(h->tcp_backend_priv.recv_buf);
3324
3325 if (connected_stlinks == 0) {
3326 LOG_ERROR("no ST-LINK detected");
3327 return ERROR_FAIL;
3328 }
3329
3330 LOG_DEBUG("%d ST-LINK detected", connected_stlinks);
3331
3332 if (connected_stlinks > 255) {
3333 LOG_WARNING("STLink server cannot handle more than 255 ST-LINK connected");
3334 connected_stlinks = 255;
3335 }
3336
3337 /* list all connected ST-Link and seek for the requested vid:pid and serial */
3338 char serial[STLINK_TCP_SERIAL_SIZE + 1] = {0};
3339 uint8_t stlink_used;
3340 bool stlink_id_matched = false;
3341 bool stlink_serial_matched = (!param->serial);
3342
3343 for (uint32_t stlink_id = 0; stlink_id < connected_stlinks; stlink_id++) {
3344 /* get the stlink info */
3345 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_GET_DEV_INFO;
3346 h->tcp_backend_priv.send_buf[1] = (uint8_t)stlink_id;
3347 memset(&h->tcp_backend_priv.send_buf[2], 0, 2); /* reserved */
3348 h_u32_to_le(&h->tcp_backend_priv.send_buf[4], 41); /* size of TDeviceInfo2 */
3349 ret = stlink_tcp_send_cmd(h, 8, 45, true);
3350 if (ret != ERROR_OK)
3351 return ret;
3352
3353 h->tcp_backend_priv.device_id = le_to_h_u32(&h->tcp_backend_priv.recv_buf[4]);
3354 memcpy(serial, &h->tcp_backend_priv.recv_buf[8], STLINK_TCP_SERIAL_SIZE);
3355 h->vid = le_to_h_u16(&h->tcp_backend_priv.recv_buf[40]);
3356 h->pid = le_to_h_u16(&h->tcp_backend_priv.recv_buf[42]);
3357 stlink_used = h->tcp_backend_priv.recv_buf[44];
3358
3359 /* check the vid:pid */
3360 for (int i = 0; param->vid[i]; i++) {
3361 if (param->vid[i] == h->vid && param->pid[i] == h->pid) {
3362 stlink_id_matched = true;
3363 break;
3364 }
3365 }
3366
3367 if (!stlink_id_matched)
3368 continue;
3369
3370 /* check the serial if specified */
3371 if (param->serial) {
3372 /* ST-Link server fixes the buggy serial returned by old ST-Link DFU
3373 * for further details refer to stlink_usb_get_alternate_serial
3374 * so if the user passes the buggy serial, we need to fix it before
3375 * comparing with the serial returned by ST-Link server */
3376 if (strlen(param->serial) == STLINK_SERIAL_LEN / 2) {
3377 char fixed_serial[STLINK_SERIAL_LEN + 1];
3378
3379 for (unsigned int i = 0; i < STLINK_SERIAL_LEN; i += 2)
3380 sprintf(fixed_serial + i, "%02X", param->serial[i / 2]);
3381
3382 fixed_serial[STLINK_SERIAL_LEN] = '\0';
3383
3384 stlink_serial_matched = strcmp(fixed_serial, serial) == 0;
3385 } else
3386 stlink_serial_matched = strcmp(param->serial, serial) == 0;
3387 }
3388
3389 if (!stlink_serial_matched)
3390 LOG_DEBUG("Device serial number '%s' doesn't match requested serial '%s'",
3391 serial, param->serial);
3392 else /* exit the search loop if there is match */
3393 break;
3394 }
3395
3396 if (!stlink_id_matched) {
3397 LOG_ERROR("ST-LINK open failed (vid/pid mismatch)");
3398 return ERROR_FAIL;
3399 }
3400
3401 if (!stlink_serial_matched) {
3402 LOG_ERROR("ST-LINK open failed (serial mismatch)");
3403 return ERROR_FAIL;
3404 }
3405
3406 /* check if device is 'exclusively' used by another application */
3407 if (stlink_used) {
3408 LOG_ERROR("the selected device is already used");
3409 return ERROR_FAIL;
3410 }
3411
3412 LOG_DEBUG("transport: vid: 0x%04x pid: 0x%04x serial: %s", h->vid, h->pid, serial);
3413
3414 /* now let's open the stlink */
3415 h->tcp_backend_priv.send_buf[0] = STLINK_TCP_CMD_OPEN_DEV;
3416 memset(&h->tcp_backend_priv.send_buf[1], 0, 4); /* reserved */
3417 h_u32_to_le(&h->tcp_backend_priv.send_buf[4], h->tcp_backend_priv.device_id);
3418 ret = stlink_tcp_send_cmd(h, 8, 8, true);
3419 if (ret != ERROR_OK)
3420 return ret;
3421
3422 h->tcp_backend_priv.connect_id = le_to_h_u32(&h->tcp_backend_priv.recv_buf[4]);
3423
3424 /* get stlink version */
3425 return stlink_usb_version(h);
3426 }
3427
3428 static struct stlink_backend_s stlink_usb_backend = {
3429 .open = stlink_usb_usb_open,
3430 .close = stlink_usb_usb_close,
3431 .xfer_noerrcheck = stlink_usb_usb_xfer_noerrcheck,
3432 .read_trace = stlink_usb_usb_read_trace,
3433 };
3434
3435 static struct stlink_backend_s stlink_tcp_backend = {
3436 .open = stlink_tcp_open,
3437 .close = stlink_tcp_close,
3438 .xfer_noerrcheck = stlink_tcp_xfer_noerrcheck,
3439 .read_trace = stlink_tcp_read_trace,
3440 };
3441
3442 static int stlink_open(struct hl_interface_param_s *param, enum stlink_mode mode, void **fd)
3443 {
3444 struct stlink_usb_handle_s *h;
3445
3446 LOG_DEBUG("stlink_open");
3447
3448 h = calloc(1, sizeof(struct stlink_usb_handle_s));
3449
3450 if (h == 0) {
3451 LOG_DEBUG("malloc failed");
3452 return ERROR_FAIL;
3453 }
3454
3455 h->st_mode = mode;
3456
3457 for (unsigned i = 0; param->vid[i]; i++) {
3458 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
3459 h->st_mode, param->vid[i], param->pid[i],
3460 param->serial ? param->serial : "");
3461 }
3462
3463 if (param->use_stlink_tcp)
3464 h->backend = &stlink_tcp_backend;
3465 else
3466 h->backend = &stlink_usb_backend;
3467
3468 if (stlink_usb_open(h, param) != ERROR_OK)
3469 goto error_open;
3470
3471 /* check if mode is supported */
3472 int err = ERROR_OK;
3473
3474 switch (h->st_mode) {
3475 case STLINK_MODE_DEBUG_SWD:
3476 if (h->version.jtag_api == STLINK_JTAG_API_V1)
3477 err = ERROR_FAIL;
3478 /* fall-through */
3479 case STLINK_MODE_DEBUG_JTAG:
3480 if (h->version.jtag == 0)
3481 err = ERROR_FAIL;
3482 break;
3483 case STLINK_MODE_DEBUG_SWIM:
3484 if (h->version.swim == 0)
3485 err = ERROR_FAIL;
3486 break;
3487 default:
3488 err = ERROR_FAIL;
3489 break;
3490 }
3491
3492 if (err != ERROR_OK) {
3493 LOG_ERROR("mode (transport) not supported by device");
3494 goto error_open;
3495 }
3496
3497 /* initialize the debug hardware */
3498 err = stlink_usb_init_mode(h, param->connect_under_reset, param->initial_interface_speed);
3499
3500 if (err != ERROR_OK) {
3501 LOG_ERROR("init mode failed (unable to connect to the target)");
3502 goto error_open;
3503 }
3504
3505 if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
3506 err = stlink_swim_enter(h);
3507 if (err != ERROR_OK) {
3508 LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
3509 goto error_open;
3510 }
3511 *fd = h;
3512 h->max_mem_packet = STLINK_SWIM_DATA_SIZE;
3513 return ERROR_OK;
3514 }
3515
3516 /* set max_mem_packet if it was not set by the low-level interface */
3517 if (h->max_mem_packet == 0) {
3518 /* get cpuid, so we can determine the max page size
3519 * start with a safe default */
3520 h->max_mem_packet = (1 << 10);
3521
3522 uint8_t buffer[4];
3523 stlink_usb_open_ap(h, 0);
3524 err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
3525 if (err == ERROR_OK) {
3526 uint32_t cpuid = le_to_h_u32(buffer);
3527 int i = (cpuid >> 4) & 0xf;
3528 if (i == 4 || i == 3) {
3529 /* Cortex-M3/M4 has 4096 bytes autoincrement range */
3530 h->max_mem_packet = (1 << 12);
3531 }
3532 }
3533
3534 LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
3535 }
3536
3537 *fd = h;
3538
3539 return ERROR_OK;
3540
3541 error_open:
3542 stlink_close(h);
3543 return ERROR_FAIL;
3544 }
3545
3546 static int stlink_usb_hl_open(struct hl_interface_param_s *param, void **fd)
3547 {
3548 return stlink_open(param, stlink_get_mode(param->transport), fd);
3549 }
3550
3551 static int stlink_config_trace(void *handle, bool enabled,
3552 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
3553 unsigned int *trace_freq, unsigned int traceclkin_freq,
3554 uint16_t *prescaler)
3555 {
3556 struct stlink_usb_handle_s *h = handle;
3557
3558 if (!(h->version.flags & STLINK_F_HAS_TRACE)) {
3559 LOG_ERROR("The attached ST-LINK version doesn't support trace");
3560 return ERROR_FAIL;
3561 }
3562
3563 if (!enabled) {
3564 stlink_usb_trace_disable(h);
3565 return ERROR_OK;
3566 }
3567
3568 assert(trace_freq);
3569 assert(prescaler);
3570
3571 if (pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART) {
3572 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
3573 return ERROR_FAIL;
3574 }
3575
3576 unsigned int max_trace_freq = (h->version.stlink == 3) ?
3577 STLINK_V3_TRACE_MAX_HZ : STLINK_TRACE_MAX_HZ;
3578
3579 /* Only concern ourselves with the frequency if the STlink is processing it. */
3580 if (*trace_freq > max_trace_freq) {
3581 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
3582 max_trace_freq);
3583 return ERROR_FAIL;
3584 }
3585
3586 if (!*trace_freq)
3587 *trace_freq = max_trace_freq;
3588
3589 unsigned int presc = (traceclkin_freq + *trace_freq / 2) / *trace_freq;
3590 if (presc == 0 || presc > TPIU_ACPR_MAX_SWOSCALER + 1) {
3591 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
3592 "frequency.");
3593 return ERROR_FAIL;
3594 }
3595
3596 /* Probe's UART speed must be within 3% of the TPIU's SWO baud rate. */
3597 unsigned int max_deviation = (traceclkin_freq * 3) / 100;
3598 if (presc * *trace_freq < traceclkin_freq - max_deviation ||
3599 presc * *trace_freq > traceclkin_freq + max_deviation) {
3600 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
3601 "frequency.");
3602 return ERROR_FAIL;
3603 }
3604
3605 *prescaler = presc;
3606
3607 stlink_usb_trace_disable(h);
3608
3609 h->trace.source_hz = *trace_freq;
3610
3611 return stlink_usb_trace_enable(h);
3612 }
3613
3614 /** */
3615 static int stlink_usb_init_access_port(void *handle, unsigned char ap_num)
3616 {
3617 struct stlink_usb_handle_s *h = handle;
3618
3619 assert(handle);
3620
3621 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3622 return ERROR_COMMAND_NOTFOUND;
3623
3624 LOG_DEBUG_IO("init ap_num = %d", ap_num);
3625 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3626 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3627 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_INIT_AP;
3628 h->cmdbuf[h->cmdidx++] = ap_num;
3629
3630 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3631 }
3632
3633 /** */
3634 static int stlink_usb_close_access_port(void *handle, unsigned char ap_num)
3635 {
3636 struct stlink_usb_handle_s *h = handle;
3637
3638 assert(handle);
3639
3640 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3641 return ERROR_COMMAND_NOTFOUND;
3642
3643 LOG_DEBUG_IO("close ap_num = %d", ap_num);
3644 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3645 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3646 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_CLOSE_AP_DBG;
3647 h->cmdbuf[h->cmdidx++] = ap_num;
3648
3649 /* ignore incorrectly returned error on bogus FW */
3650 if (h->version.flags & STLINK_F_FIX_CLOSE_AP)
3651 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3652 else
3653 return stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
3654
3655 }
3656
3657 /** */
3658 static int stlink_read_dap_register(void *handle, unsigned short dap_port,
3659 unsigned short addr, uint32_t *val)
3660 {
3661 struct stlink_usb_handle_s *h = handle;
3662 int retval;
3663
3664 assert(handle);
3665
3666 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3667 return ERROR_COMMAND_NOTFOUND;
3668
3669 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3670 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3671 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_DAP_REG;
3672 h_u16_to_le(&h->cmdbuf[2], dap_port);
3673 h_u16_to_le(&h->cmdbuf[4], addr);
3674
3675 retval = stlink_usb_xfer_errcheck(handle, h->databuf, 8);
3676 *val = le_to_h_u32(h->databuf + 4);
3677 LOG_DEBUG_IO("dap_port_read = %d, addr = 0x%x, value = 0x%" PRIx32, dap_port, addr, *val);
3678 return retval;
3679 }
3680
3681 /** */
3682 static int stlink_write_dap_register(void *handle, unsigned short dap_port,
3683 unsigned short addr, uint32_t val)
3684 {
3685 struct stlink_usb_handle_s *h = handle;
3686
3687 assert(handle);
3688
3689 if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3690 return ERROR_COMMAND_NOTFOUND;
3691
3692 LOG_DEBUG_IO("dap_write port = %d, addr = 0x%x, value = 0x%" PRIx32, dap_port, addr, val);
3693 stlink_usb_init_buffer(handle, h->rx_ep, 16);
3694 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3695 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITE_DAP_REG;
3696 h_u16_to_le(&h->cmdbuf[2], dap_port);
3697 h_u16_to_le(&h->cmdbuf[4], addr);
3698 h_u32_to_le(&h->cmdbuf[6], val);
3699 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3700 }
3701
3702 /** */
3703 struct hl_layout_api_s stlink_usb_layout_api = {
3704 /** */
3705 .open = stlink_usb_hl_open,
3706 /** */
3707 .close = stlink_close,
3708 /** */
3709 .idcode = stlink_usb_idcode,
3710 /** */
3711 .state = stlink_usb_state,
3712 /** */
3713 .reset = stlink_usb_reset,
3714 /** */
3715 .assert_srst = stlink_usb_assert_srst,
3716 /** */
3717 .run = stlink_usb_run,
3718 /** */
3719 .halt = stlink_usb_halt,
3720 /** */
3721 .step = stlink_usb_step,
3722 /** */
3723 .read_regs = stlink_usb_read_regs,
3724 /** */
3725 .read_reg = stlink_usb_read_reg,
3726 /** */
3727 .write_reg = stlink_usb_write_reg,
3728 /** */
3729 .read_mem = stlink_usb_read_mem,
3730 /** */
3731 .write_mem = stlink_usb_write_mem,
3732 /** */
3733 .write_debug_reg = stlink_usb_write_debug_reg,
3734 /** */
3735 .override_target = stlink_usb_override_target,
3736 /** */
3737 .speed = stlink_speed,
3738 /** */
3739 .config_trace = stlink_config_trace,
3740 /** */
3741 .poll_trace = stlink_usb_trace_read,
3742 };
3743
3744 /*****************************************************************************
3745 * DAP direct interface
3746 */
3747
3748 static struct stlink_usb_handle_s *stlink_dap_handle;
3749 static struct hl_interface_param_s stlink_dap_param;
3750 static DECLARE_BITMAP(opened_ap, DP_APSEL_MAX + 1);
3751 static int stlink_dap_error = ERROR_OK;
3752
3753 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3754 uint32_t *data);
3755
3756 /** */
3757 static int stlink_dap_record_error(int error)
3758 {
3759 if (stlink_dap_error == ERROR_OK)
3760 stlink_dap_error = error;
3761 return ERROR_OK;
3762 }
3763
3764 /** */
3765 static int stlink_dap_get_and_clear_error(void)
3766 {
3767 int retval = stlink_dap_error;
3768 stlink_dap_error = ERROR_OK;
3769 return retval;
3770 }
3771
3772 static int stlink_usb_open_ap(void *handle, unsigned short apsel)
3773 {
3774 struct stlink_usb_handle_s *h = handle;
3775 int retval;
3776
3777 /* nothing to do on old versions */
3778 if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3779 return ERROR_OK;
3780
3781 if (apsel > DP_APSEL_MAX)
3782 return ERROR_FAIL;
3783
3784 if (test_bit(apsel, opened_ap))
3785 return ERROR_OK;
3786
3787 retval = stlink_usb_init_access_port(h, apsel);
3788 if (retval != ERROR_OK)
3789 return retval;
3790
3791 LOG_DEBUG("AP %d enabled", apsel);
3792 set_bit(apsel, opened_ap);
3793 return ERROR_OK;
3794 }
3795
3796 static int stlink_dap_open_ap(unsigned short apsel)
3797 {
3798 return stlink_usb_open_ap(stlink_dap_handle, apsel);
3799 }
3800
3801 /** */
3802 static int stlink_dap_closeall_ap(void)
3803 {
3804 int retval, apsel;
3805
3806 /* nothing to do on old versions */
3807 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3808 return ERROR_OK;
3809
3810 for (apsel = 0; apsel <= DP_APSEL_MAX; apsel++) {
3811 if (!test_bit(apsel, opened_ap))
3812 continue;
3813 retval = stlink_usb_close_access_port(stlink_dap_handle, apsel);
3814 if (retval != ERROR_OK)
3815 return retval;
3816 clear_bit(apsel, opened_ap);
3817 }
3818 return ERROR_OK;
3819 }
3820
3821 /** */
3822 static int stlink_dap_reinit_interface(void)
3823 {
3824 int retval;
3825
3826 /*
3827 * On JTAG only, it should be enough to call stlink_usb_reset(). But on
3828 * some firmware version it does not work as expected, and there is no
3829 * equivalent for SWD.
3830 * At least for now, to reset the interface quit from JTAG/SWD mode then
3831 * select the mode again.
3832 */
3833
3834 if (!stlink_dap_handle->reconnect_pending) {
3835 stlink_dap_handle->reconnect_pending = true;
3836 stlink_usb_mode_leave(stlink_dap_handle, stlink_dap_handle->st_mode);
3837 }
3838
3839 retval = stlink_usb_mode_enter(stlink_dap_handle, stlink_dap_handle->st_mode);
3840 if (retval != ERROR_OK)
3841 return retval;
3842
3843 stlink_dap_handle->reconnect_pending = false;
3844 /* on new FW, calling mode-leave closes all the opened AP; reopen them! */
3845 if (stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT)
3846 for (int apsel = 0; apsel <= DP_APSEL_MAX; apsel++)
3847 if (test_bit(apsel, opened_ap)) {
3848 clear_bit(apsel, opened_ap);
3849 stlink_dap_open_ap(apsel);
3850 }
3851 return ERROR_OK;
3852 }
3853
3854 /** */
3855 static int stlink_dap_op_connect(struct adiv5_dap *dap)
3856 {
3857 uint32_t idcode;
3858 int retval;
3859
3860 LOG_INFO("stlink_dap_op_connect(%sconnect)", dap->do_reconnect ? "re" : "");
3861
3862 /* Check if we should reset srst already when connecting, but not if reconnecting. */
3863 if (!dap->do_reconnect) {
3864 enum reset_types jtag_reset_config = jtag_get_reset_config();
3865
3866 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3867 if (jtag_reset_config & RESET_SRST_NO_GATING)
3868 adapter_assert_reset();
3869 else
3870 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3871 }
3872 }
3873
3874 dap->do_reconnect = false;
3875 dap_invalidate_cache(dap);
3876
3877 retval = dap_dp_init(dap);
3878 if (retval != ERROR_OK) {
3879 dap->do_reconnect = true;
3880 return retval;
3881 }
3882
3883 retval = stlink_usb_idcode(stlink_dap_handle, &idcode);
3884 if (retval == ERROR_OK)
3885 LOG_INFO("%s %#8.8" PRIx32,
3886 (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) ? "JTAG IDCODE" : "SWD DPIDR",
3887 idcode);
3888 else
3889 dap->do_reconnect = true;
3890
3891 return retval;
3892 }
3893
3894 /** */
3895 static int stlink_dap_check_reconnect(struct adiv5_dap *dap)
3896 {
3897 int retval;
3898
3899 if (!dap->do_reconnect)
3900 return ERROR_OK;
3901
3902 retval = stlink_dap_reinit_interface();
3903 if (retval != ERROR_OK)
3904 return retval;
3905
3906 return stlink_dap_op_connect(dap);
3907 }
3908
3909 /** */
3910 static int stlink_dap_op_send_sequence(struct adiv5_dap *dap, enum swd_special_seq seq)
3911 {
3912 /* Ignore the request */
3913 return ERROR_OK;
3914 }
3915
3916 /** */
3917 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3918 uint32_t *data)
3919 {
3920 uint32_t dummy;
3921 int retval;
3922
3923 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3924 if (reg & 0x000000F0) {
3925 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3926 return ERROR_COMMAND_NOTFOUND;
3927 }
3928
3929 retval = stlink_dap_check_reconnect(dap);
3930 if (retval != ERROR_OK)
3931 return retval;
3932
3933 data = data ? data : &dummy;
3934 if (stlink_dap_handle->version.flags & STLINK_F_QUIRK_JTAG_DP_READ
3935 && stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) {
3936 /* Quirk required in JTAG. Read RDBUFF to get the data */
3937 retval = stlink_read_dap_register(stlink_dap_handle,
3938 STLINK_DEBUG_PORT_ACCESS, reg, &dummy);
3939 if (retval == ERROR_OK)
3940 retval = stlink_read_dap_register(stlink_dap_handle,
3941 STLINK_DEBUG_PORT_ACCESS, DP_RDBUFF, data);
3942 } else {
3943 retval = stlink_read_dap_register(stlink_dap_handle,
3944 STLINK_DEBUG_PORT_ACCESS, reg, data);
3945 }
3946
3947 return stlink_dap_record_error(retval);
3948 }
3949
3950 /** */
3951 static int stlink_dap_op_queue_dp_write(struct adiv5_dap *dap, unsigned reg,
3952 uint32_t data)
3953 {
3954 int retval;
3955
3956 if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3957 if (reg & 0x000000F0) {
3958 LOG_ERROR("Banked DP registers not supported in current STLink FW");
3959 return ERROR_COMMAND_NOTFOUND;
3960 }
3961
3962 if (reg == DP_SELECT && (data & DP_SELECT_DPBANK) != 0) {
3963 /* ignored if STLINK_F_HAS_DPBANKSEL, not properly managed otherwise */
3964 LOG_DEBUG("Ignoring DPBANKSEL while write SELECT");
3965 data &= ~DP_SELECT_DPBANK;
3966 }
3967
3968 retval = stlink_dap_check_reconnect(dap);
3969 if (retval != ERROR_OK)
3970 return retval;
3971
3972 /* ST-Link does not like that we set CORUNDETECT */
3973 if (reg == DP_CTRL_STAT)
3974 data &= ~CORUNDETECT;
3975
3976 retval = stlink_write_dap_register(stlink_dap_handle,
3977 STLINK_DEBUG_PORT_ACCESS, reg, data);
3978 return stlink_dap_record_error(retval);
3979 }
3980
3981 /** */
3982 static int stlink_dap_op_queue_ap_read(struct adiv5_ap *ap, unsigned reg,
3983 uint32_t *data)
3984 {
3985 struct adiv5_dap *dap = ap->dap;
3986 uint32_t dummy;
3987 int retval;
3988
3989 retval = stlink_dap_check_reconnect(dap);
3990 if (retval != ERROR_OK)
3991 return retval;
3992
3993 if (reg != AP_REG_IDR) {
3994 retval = stlink_dap_open_ap(ap->ap_num);
3995 if (retval != ERROR_OK)
3996 return retval;
3997 }
3998 data = data ? data : &dummy;
3999 retval = stlink_read_dap_register(stlink_dap_handle, ap->ap_num, reg,
4000 data);
4001 dap->stlink_flush_ap_write = false;
4002 return stlink_dap_record_error(retval);
4003 }
4004
4005 /** */
4006 static int stlink_dap_op_queue_ap_write(struct adiv5_ap *ap, unsigned reg,
4007 uint32_t data)
4008 {
4009 struct adiv5_dap *dap = ap->dap;
4010 int retval;
4011
4012 retval = stlink_dap_check_reconnect(dap);
4013 if (retval != ERROR_OK)
4014 return retval;
4015
4016 retval = stlink_dap_open_ap(ap->ap_num);
4017 if (retval != ERROR_OK)
4018 return retval;
4019
4020 retval = stlink_write_dap_register(stlink_dap_handle, ap->ap_num, reg,
4021 data);
4022 dap->stlink_flush_ap_write = true;
4023 return stlink_dap_record_error(retval);
4024 }
4025
4026 /** */
4027 static int stlink_dap_op_queue_ap_abort(struct adiv5_dap *dap, uint8_t *ack)
4028 {
4029 LOG_WARNING("stlink_dap_op_queue_ap_abort()");
4030 return ERROR_OK;
4031 }
4032
4033 /** */
4034 static int stlink_dap_op_run(struct adiv5_dap *dap)
4035 {
4036 uint32_t ctrlstat, pwrmask;
4037 int retval, saved_retval;
4038
4039 /* Here no LOG_DEBUG. This is called continuously! */
4040
4041 /*
4042 * ST-Link returns immediately after a DAP write, without waiting for it
4043 * to complete.
4044 * Run a dummy read to DP_RDBUFF, as suggested in
4045 * http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka16363.html
4046 */
4047 if (dap->stlink_flush_ap_write) {
4048 dap->stlink_flush_ap_write = false;
4049 retval = stlink_dap_op_queue_dp_read(dap, DP_RDBUFF, NULL);
4050 if (retval != ERROR_OK) {
4051 dap->do_reconnect = true;
4052 return retval;
4053 }
4054 }
4055
4056 saved_retval = stlink_dap_get_and_clear_error();
4057
4058 retval = stlink_dap_op_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
4059 if (retval != ERROR_OK) {
4060 dap->do_reconnect = true;
4061 return retval;
4062 }
4063 retval = stlink_dap_get_and_clear_error();
4064 if (retval != ERROR_OK) {
4065 LOG_ERROR("Fail reading CTRL/STAT register. Force reconnect");
4066 dap->do_reconnect = true;
4067 return retval;
4068 }
4069
4070 if (ctrlstat & SSTICKYERR) {
4071 if (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG)
4072 retval = stlink_dap_op_queue_dp_write(dap, DP_CTRL_STAT,
4073 ctrlstat & (dap->dp_ctrl_stat | SSTICKYERR));
4074 else
4075 retval = stlink_dap_op_queue_dp_write(dap, DP_ABORT, STKERRCLR);
4076 if (retval != ERROR_OK) {
4077 dap->do_reconnect = true;
4078 return retval;
4079 }
4080 retval = stlink_dap_get_and_clear_error();
4081 if (retval != ERROR_OK) {
4082 dap->do_reconnect = true;
4083 return retval;
4084 }
4085 }
4086
4087 /* check for power lost */
4088 pwrmask = dap->dp_ctrl_stat & (CDBGPWRUPREQ | CSYSPWRUPREQ);
4089 if ((ctrlstat & pwrmask) != pwrmask)
4090 dap->do_reconnect = true;
4091
4092 return saved_retval;
4093 }
4094
4095 /** */
4096 static void stlink_dap_op_quit(struct adiv5_dap *dap)
4097 {
4098 int retval;
4099
4100 retval = stlink_dap_closeall_ap();
4101 if (retval != ERROR_OK)
4102 LOG_ERROR("Error closing APs");
4103 }
4104
4105 static int stlink_swim_op_srst(void)
4106 {
4107 return stlink_swim_generate_rst(stlink_dap_handle);
4108 }
4109
4110 static int stlink_swim_op_read_mem(uint32_t addr, uint32_t size,
4111 uint32_t count, uint8_t *buffer)
4112 {
4113 int retval;
4114 uint32_t bytes_remaining;
4115
4116 LOG_DEBUG_IO("read at 0x%08" PRIx32 " len %" PRIu32 "*0x%08" PRIx32, addr, size, count);
4117 count *= size;
4118
4119 while (count) {
4120 bytes_remaining = (count > STLINK_SWIM_DATA_SIZE) ? STLINK_SWIM_DATA_SIZE : count;
4121 retval = stlink_swim_readbytes(stlink_dap_handle, addr, bytes_remaining, buffer);
4122 if (retval != ERROR_OK)
4123 return retval;
4124
4125 buffer += bytes_remaining;
4126 addr += bytes_remaining;
4127 count -= bytes_remaining;
4128 }
4129
4130 return ERROR_OK;
4131 }
4132
4133 static int stlink_swim_op_write_mem(uint32_t addr, uint32_t size,
4134 uint32_t count, const uint8_t *buffer)
4135 {
4136 int retval;
4137 uint32_t bytes_remaining;
4138
4139 LOG_DEBUG_IO("write at 0x%08" PRIx32 " len %" PRIu32 "*0x%08" PRIx32, addr, size, count);
4140 count *= size;
4141
4142 while (count) {
4143 bytes_remaining = (count > STLINK_SWIM_DATA_SIZE) ? STLINK_SWIM_DATA_SIZE : count;
4144 retval = stlink_swim_writebytes(stlink_dap_handle, addr, bytes_remaining, buffer);
4145 if (retval != ERROR_OK)
4146 return retval;
4147
4148 buffer += bytes_remaining;
4149 addr += bytes_remaining;
4150 count -= bytes_remaining;
4151 }
4152
4153 return ERROR_OK;
4154 }
4155
4156 static int stlink_swim_op_reconnect(void)
4157 {
4158 int retval;
4159
4160 retval = stlink_usb_mode_enter(stlink_dap_handle, STLINK_MODE_DEBUG_SWIM);
4161 if (retval != ERROR_OK)
4162 return retval;
4163
4164 return stlink_swim_resync(stlink_dap_handle);
4165 }
4166
4167 static int stlink_dap_config_trace(bool enabled,
4168 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
4169 unsigned int *trace_freq, unsigned int traceclkin_freq,
4170 uint16_t *prescaler)
4171 {
4172 return stlink_config_trace(stlink_dap_handle, enabled, pin_protocol,
4173 port_size, trace_freq, traceclkin_freq,
4174 prescaler);
4175 }
4176
4177 static int stlink_dap_trace_read(uint8_t *buf, size_t *size)
4178 {
4179 return stlink_usb_trace_read(stlink_dap_handle, buf, size);
4180 }
4181
4182 /** */
4183 COMMAND_HANDLER(stlink_dap_serial_command)
4184 {
4185 LOG_DEBUG("stlink_dap_serial_command");
4186
4187 if (CMD_ARGC != 1) {
4188 LOG_ERROR("Expected exactly one argument for \"st-link serial <serial-number>\".");
4189 return ERROR_COMMAND_SYNTAX_ERROR;
4190 }
4191
4192 if (stlink_dap_param.serial) {
4193 LOG_WARNING("Command \"st-link serial\" already used. Replacing previous value");
4194 free((void *)stlink_dap_param.serial);
4195 }
4196
4197 stlink_dap_param.serial = strdup(CMD_ARGV[0]);
4198 return ERROR_OK;
4199 }
4200
4201 /** */
4202 COMMAND_HANDLER(stlink_dap_vid_pid)
4203 {
4204 unsigned int i, max_usb_ids = HLA_MAX_USB_IDS;
4205
4206 if (CMD_ARGC > max_usb_ids * 2) {
4207 LOG_WARNING("ignoring extra IDs in vid_pid "
4208 "(maximum is %d pairs)", max_usb_ids);
4209 CMD_ARGC = max_usb_ids * 2;
4210 }
4211 if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
4212 LOG_WARNING("incomplete vid_pid configuration directive");
4213 return ERROR_COMMAND_SYNTAX_ERROR;
4214 }
4215 for (i = 0; i < CMD_ARGC; i += 2) {
4216 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], stlink_dap_param.vid[i / 2]);
4217 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], stlink_dap_param.pid[i / 2]);
4218 }
4219
4220 /* null termination */
4221 stlink_dap_param.vid[i / 2] = stlink_dap_param.pid[i / 2] = 0;
4222
4223 return ERROR_OK;
4224 }
4225
4226 /** */
4227 COMMAND_HANDLER(stlink_dap_backend_command)
4228 {
4229 /* default values */
4230 bool use_stlink_tcp = false;
4231 uint16_t stlink_tcp_port = 7184;
4232
4233 if (CMD_ARGC == 0 || CMD_ARGC > 2)
4234 return ERROR_COMMAND_SYNTAX_ERROR;
4235 else if (strcmp(CMD_ARGV[0], "usb") == 0) {
4236 if (CMD_ARGC > 1)
4237 return ERROR_COMMAND_SYNTAX_ERROR;
4238 /* else use_stlink_tcp = false (already the case ) */
4239 } else if (strcmp(CMD_ARGV[0], "tcp") == 0) {
4240 use_stlink_tcp = true;
4241 if (CMD_ARGC == 2)
4242 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], stlink_tcp_port);
4243 } else
4244 return ERROR_COMMAND_SYNTAX_ERROR;
4245
4246 stlink_dap_param.use_stlink_tcp = use_stlink_tcp;
4247 stlink_dap_param.stlink_tcp_port = stlink_tcp_port;
4248
4249 return ERROR_OK;
4250 }
4251
4252 #define BYTES_PER_LINE 16
4253 COMMAND_HANDLER(stlink_dap_cmd_command)
4254 {
4255 unsigned int rx_n, tx_n;
4256 struct stlink_usb_handle_s *h = stlink_dap_handle;
4257
4258 if (CMD_ARGC < 2)
4259 return ERROR_COMMAND_SYNTAX_ERROR;
4260
4261 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], rx_n);
4262 tx_n = CMD_ARGC - 1;
4263 if (tx_n > STLINK_SG_SIZE || rx_n > STLINK_DATA_SIZE) {
4264 LOG_ERROR("max %x byte sent and %d received", STLINK_SG_SIZE, STLINK_DATA_SIZE);
4265 return ERROR_COMMAND_SYNTAX_ERROR;
4266 }
4267
4268 stlink_usb_init_buffer(h, h->rx_ep, rx_n);
4269
4270 for (unsigned int i = 0; i < tx_n; i++) {
4271 uint8_t byte;
4272 COMMAND_PARSE_NUMBER(u8, CMD_ARGV[i + 1], byte);
4273 h->cmdbuf[h->cmdidx++] = byte;
4274 }
4275
4276 int retval = stlink_usb_xfer_noerrcheck(h, h->databuf, rx_n);
4277 if (retval != ERROR_OK) {
4278 LOG_ERROR("Error %d", retval);
4279 return retval;
4280 }
4281
4282 for (unsigned int i = 0; i < rx_n; i++)
4283 command_print_sameline(CMD, "0x%02x%c", h->databuf[i],
4284 ((i == (rx_n - 1)) || ((i % BYTES_PER_LINE) == (BYTES_PER_LINE - 1))) ? '\n' : ' ');
4285
4286 return ERROR_OK;
4287 }
4288
4289 /** */
4290 static const struct command_registration stlink_dap_subcommand_handlers[] = {
4291 {
4292 .name = "serial",
4293 .handler = stlink_dap_serial_command,
4294 .mode = COMMAND_CONFIG,
4295 .help = "set the serial number of the adapter",
4296 .usage = "<serial_number>",
4297 },
4298 {
4299 .name = "vid_pid",
4300 .handler = stlink_dap_vid_pid,
4301 .mode = COMMAND_CONFIG,
4302 .help = "USB VID and PID of the adapter",
4303 .usage = "(vid pid)+",
4304 },
4305 {
4306 .name = "backend",
4307 .handler = &stlink_dap_backend_command,
4308 .mode = COMMAND_CONFIG,
4309 .help = "select which ST-Link backend to use",
4310 .usage = "usb | tcp [port]",
4311 },
4312 {
4313 .name = "cmd",
4314 .handler = stlink_dap_cmd_command,
4315 .mode = COMMAND_EXEC,
4316 .help = "send arbitrary command",
4317 .usage = "rx_n (tx_byte)+",
4318 },
4319 COMMAND_REGISTRATION_DONE
4320 };
4321
4322 /** */
4323 static const struct command_registration stlink_dap_command_handlers[] = {
4324 {
4325 .name = "st-link",
4326 .mode = COMMAND_ANY,
4327 .help = "perform st-link management",
4328 .chain = stlink_dap_subcommand_handlers,
4329 .usage = "",
4330 },
4331 COMMAND_REGISTRATION_DONE
4332 };
4333
4334 /** */
4335 static int stlink_dap_init(void)
4336 {
4337 enum reset_types jtag_reset_config = jtag_get_reset_config();
4338 enum stlink_mode mode;
4339 int retval;
4340
4341 LOG_DEBUG("stlink_dap_init()");
4342
4343 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
4344 if (jtag_reset_config & RESET_SRST_NO_GATING)
4345 stlink_dap_param.connect_under_reset = true;
4346 else
4347 LOG_WARNING("\'srst_nogate\' reset_config option is required");
4348 }
4349
4350 if (transport_is_dapdirect_swd())
4351 mode = STLINK_MODE_DEBUG_SWD;
4352 else if (transport_is_dapdirect_jtag())
4353 mode = STLINK_MODE_DEBUG_JTAG;
4354 else if (transport_is_swim())
4355 mode = STLINK_MODE_DEBUG_SWIM;
4356 else {
4357 LOG_ERROR("Unsupported transport");
4358 return ERROR_FAIL;
4359 }
4360
4361 retval = stlink_open(&stlink_dap_param, mode, (void **)&stlink_dap_handle);
4362 if (retval != ERROR_OK)
4363 return retval;
4364
4365 if ((mode != STLINK_MODE_DEBUG_SWIM) &&
4366 !(stlink_dap_handle->version.flags & STLINK_F_HAS_DAP_REG)) {
4367 LOG_ERROR("ST-Link version does not support DAP direct transport");
4368 return ERROR_FAIL;
4369 }
4370 return ERROR_OK;
4371 }
4372
4373 /** */
4374 static int stlink_dap_quit(void)
4375 {
4376 LOG_DEBUG("stlink_dap_quit()");
4377
4378 free((void *)stlink_dap_param.serial);
4379 stlink_dap_param.serial = NULL;
4380
4381 return stlink_close(stlink_dap_handle);
4382 }
4383
4384 /** */
4385 static int stlink_dap_reset(int req_trst, int req_srst)
4386 {
4387 LOG_DEBUG("stlink_dap_reset(%d)", req_srst);
4388 return stlink_usb_assert_srst(stlink_dap_handle,
4389 req_srst ? STLINK_DEBUG_APIV2_DRIVE_NRST_LOW
4390 : STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH);
4391 }
4392
4393 /** */
4394 static int stlink_dap_speed(int speed)
4395 {
4396 if (speed == 0) {
4397 LOG_ERROR("RTCK not supported. Set nonzero adapter_khz.");
4398 return ERROR_JTAG_NOT_IMPLEMENTED;
4399 }
4400
4401 stlink_dap_param.initial_interface_speed = speed;
4402 stlink_speed(stlink_dap_handle, speed, false);
4403 return ERROR_OK;
4404 }
4405
4406 /** */
4407 static int stlink_dap_khz(int khz, int *jtag_speed)
4408 {
4409 if (khz == 0) {
4410 LOG_ERROR("RCLK not supported");
4411 return ERROR_FAIL;
4412 }
4413
4414 *jtag_speed = stlink_speed(stlink_dap_handle, khz, true);
4415 return ERROR_OK;
4416 }
4417
4418 /** */
4419 static int stlink_dap_speed_div(int speed, int *khz)
4420 {
4421 *khz = speed;
4422 return ERROR_OK;
4423 }
4424
4425 static const struct dap_ops stlink_dap_ops = {
4426 .connect = stlink_dap_op_connect,
4427 .send_sequence = stlink_dap_op_send_sequence,
4428 .queue_dp_read = stlink_dap_op_queue_dp_read,
4429 .queue_dp_write = stlink_dap_op_queue_dp_write,
4430 .queue_ap_read = stlink_dap_op_queue_ap_read,
4431 .queue_ap_write = stlink_dap_op_queue_ap_write,
4432 .queue_ap_abort = stlink_dap_op_queue_ap_abort,
4433 .run = stlink_dap_op_run,
4434 .sync = NULL, /* optional */
4435 .quit = stlink_dap_op_quit, /* optional */
4436 };
4437
4438 static const struct swim_driver stlink_swim_ops = {
4439 .srst = stlink_swim_op_srst,
4440 .read_mem = stlink_swim_op_read_mem,
4441 .write_mem = stlink_swim_op_write_mem,
4442 .reconnect = stlink_swim_op_reconnect,
4443 };
4444
4445 static const char *const stlink_dap_transport[] = { "dapdirect_swd", "dapdirect_jtag", "swim", NULL };
4446
4447 struct adapter_driver stlink_dap_adapter_driver = {
4448 .name = "st-link",
4449 .transports = stlink_dap_transport,
4450 .commands = stlink_dap_command_handlers,
4451
4452 .init = stlink_dap_init,
4453 .quit = stlink_dap_quit,
4454 .reset = stlink_dap_reset,
4455 .speed = stlink_dap_speed,
4456 .khz = stlink_dap_khz,
4457 .speed_div = stlink_dap_speed_div,
4458 .config_trace = stlink_dap_config_trace,
4459 .poll_trace = stlink_dap_trace_read,
4460
4461 .dap_jtag_ops = &stlink_dap_ops,
4462 .dap_swd_ops = &stlink_dap_ops,
4463 .swim_ops = &stlink_swim_ops,
4464 };

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)