You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

4390 lines
115 KiB

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