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

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)