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