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.
 
 
 
 
 
 

2168 lines
59 KiB

  1. /***************************************************************************
  2. * Copyright (C) 2021 by Adrian Negreanu *
  3. * groleo@gmail.com *
  4. * *
  5. * Copyright (C) 2018 by Mickaël Thomas *
  6. * mickael9@gmail.com *
  7. * *
  8. * Copyright (C) 2016 by Maksym Hilliaka *
  9. * oter@frozen-team.com *
  10. * *
  11. * Copyright (C) 2016 by Phillip Pearson *
  12. * pp@myelin.co.nz *
  13. * *
  14. * Copyright (C) 2014 by Paul Fertser *
  15. * fercerpav@gmail.com *
  16. * *
  17. * Copyright (C) 2013 by mike brown *
  18. * mike@theshedworks.org.uk *
  19. * *
  20. * Copyright (C) 2013 by Spencer Oliver *
  21. * spen@spen-soft.co.uk *
  22. * *
  23. * This program is free software; you can redistribute it and/or modify *
  24. * it under the terms of the GNU General Public License as published by *
  25. * the Free Software Foundation; either version 2 of the License, or *
  26. * (at your option) any later version. *
  27. * *
  28. * This program is distributed in the hope that it will be useful, *
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of *
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
  31. * GNU General Public License for more details. *
  32. * *
  33. * You should have received a copy of the GNU General Public License *
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>. *
  35. ***************************************************************************/
  36. #ifdef HAVE_CONFIG_H
  37. #include "config.h"
  38. #endif
  39. #include <transport/transport.h>
  40. #include "helper/replacements.h"
  41. #include <jtag/swd.h>
  42. #include <jtag/interface.h>
  43. #include <jtag/commands.h>
  44. #include <jtag/tcl.h>
  45. #include <target/cortex_m.h>
  46. #include "cmsis_dap.h"
  47. static const struct cmsis_dap_backend *const cmsis_dap_backends[] = {
  48. #if BUILD_CMSIS_DAP_USB == 1
  49. &cmsis_dap_usb_backend,
  50. #endif
  51. #if BUILD_CMSIS_DAP_HID == 1
  52. &cmsis_dap_hid_backend,
  53. #endif
  54. };
  55. /* USB Config */
  56. /* Known vid/pid pairs:
  57. * VID 0xc251: Keil Software
  58. * PID 0xf001: LPC-Link-II CMSIS_DAP
  59. * PID 0xf002: OPEN-SDA CMSIS_DAP (Freedom Board)
  60. * PID 0x2722: Keil ULINK2 CMSIS-DAP
  61. * PID 0x2750: Keil ULINKplus CMSIS-DAP
  62. *
  63. * VID 0x0d28: mbed Software
  64. * PID 0x0204: MBED CMSIS-DAP
  65. */
  66. #define MAX_USB_IDS 8
  67. /* vid = pid = 0 marks the end of the list */
  68. static uint16_t cmsis_dap_vid[MAX_USB_IDS + 1] = { 0 };
  69. static uint16_t cmsis_dap_pid[MAX_USB_IDS + 1] = { 0 };
  70. static char *cmsis_dap_serial;
  71. static int cmsis_dap_backend = -1;
  72. static bool swd_mode;
  73. #define USB_TIMEOUT 1000
  74. /* CMSIS-DAP General Commands */
  75. #define CMD_DAP_INFO 0x00
  76. #define CMD_DAP_LED 0x01
  77. #define CMD_DAP_CONNECT 0x02
  78. #define CMD_DAP_DISCONNECT 0x03
  79. #define CMD_DAP_WRITE_ABORT 0x08
  80. #define CMD_DAP_DELAY 0x09
  81. #define CMD_DAP_RESET_TARGET 0x0A
  82. /* CMD_INFO */
  83. #define INFO_ID_VENDOR 0x01 /* string */
  84. #define INFO_ID_PRODUCT 0x02 /* string */
  85. #define INFO_ID_SERNUM 0x03 /* string */
  86. #define INFO_ID_FW_VER 0x04 /* string */
  87. #define INFO_ID_TD_VEND 0x05 /* string */
  88. #define INFO_ID_TD_NAME 0x06 /* string */
  89. #define INFO_ID_CAPS 0xf0 /* byte */
  90. #define INFO_ID_PKT_CNT 0xfe /* byte */
  91. #define INFO_ID_PKT_SZ 0xff /* short */
  92. #define INFO_ID_SWO_BUF_SZ 0xfd /* word */
  93. #define INFO_CAPS_SWD BIT(0)
  94. #define INFO_CAPS_JTAG BIT(1)
  95. #define INFO_CAPS_SWO_UART BIT(2)
  96. #define INFO_CAPS_SWO_MANCHESTER BIT(3)
  97. /* CMD_LED */
  98. #define LED_ID_CONNECT 0x00
  99. #define LED_ID_RUN 0x01
  100. #define LED_OFF 0x00
  101. #define LED_ON 0x01
  102. /* CMD_CONNECT */
  103. #define CONNECT_DEFAULT 0x00
  104. #define CONNECT_SWD 0x01
  105. #define CONNECT_JTAG 0x02
  106. /* CMSIS-DAP Common SWD/JTAG Commands */
  107. #define CMD_DAP_DELAY 0x09
  108. #define CMD_DAP_SWJ_PINS 0x10
  109. #define CMD_DAP_SWJ_CLOCK 0x11
  110. #define CMD_DAP_SWJ_SEQ 0x12
  111. /*
  112. * PINS
  113. * Bit 0: SWCLK/TCK
  114. * Bit 1: SWDIO/TMS
  115. * Bit 2: TDI
  116. * Bit 3: TDO
  117. * Bit 5: nTRST
  118. * Bit 7: nRESET
  119. */
  120. #define SWJ_PIN_TCK (1<<0)
  121. #define SWJ_PIN_TMS (1<<1)
  122. #define SWJ_PIN_TDI (1<<2)
  123. #define SWJ_PIN_TDO (1<<3)
  124. #define SWJ_PIN_TRST (1<<5)
  125. #define SWJ_PIN_SRST (1<<7)
  126. /* CMSIS-DAP SWD Commands */
  127. #define CMD_DAP_SWD_CONFIGURE 0x13
  128. #define CMD_DAP_SWD_SEQUENCE 0x1D
  129. /* CMSIS-DAP JTAG Commands */
  130. #define CMD_DAP_JTAG_SEQ 0x14
  131. #define CMD_DAP_JTAG_CONFIGURE 0x15
  132. #define CMD_DAP_JTAG_IDCODE 0x16
  133. /* CMSIS-DAP JTAG sequence info masks */
  134. /* Number of bits to clock through (0 means 64) */
  135. #define DAP_JTAG_SEQ_TCK 0x3F
  136. /* TMS will be set during the sequence if this bit is set */
  137. #define DAP_JTAG_SEQ_TMS 0x40
  138. /* TDO output will be captured if this bit is set */
  139. #define DAP_JTAG_SEQ_TDO 0x80
  140. /* CMSIS-DAP Transfer Commands */
  141. #define CMD_DAP_TFER_CONFIGURE 0x04
  142. #define CMD_DAP_TFER 0x05
  143. #define CMD_DAP_TFER_BLOCK 0x06
  144. #define CMD_DAP_TFER_ABORT 0x07
  145. /* DAP Status Code */
  146. #define DAP_OK 0
  147. #define DAP_ERROR 0xFF
  148. /* CMSIS-DAP SWO Commands */
  149. #define CMD_DAP_SWO_TRANSPORT 0x17
  150. #define CMD_DAP_SWO_MODE 0x18
  151. #define CMD_DAP_SWO_BAUDRATE 0x19
  152. #define CMD_DAP_SWO_CONTROL 0x1A
  153. #define CMD_DAP_SWO_STATUS 0x1B
  154. #define CMD_DAP_SWO_DATA 0x1C
  155. #define CMD_DAP_SWO_EX_STATUS 0x1E
  156. /* SWO transport mode for reading trace data */
  157. #define DAP_SWO_TRANSPORT_NONE 0
  158. #define DAP_SWO_TRANSPORT_DATA 1
  159. #define DAP_SWO_TRANSPORT_WINUSB 2
  160. /* SWO trace capture mode */
  161. #define DAP_SWO_MODE_OFF 0
  162. #define DAP_SWO_MODE_UART 1
  163. #define DAP_SWO_MODE_MANCHESTER 2
  164. /* SWO trace data capture */
  165. #define DAP_SWO_CONTROL_STOP 0
  166. #define DAP_SWO_CONTROL_START 1
  167. /* SWO trace status */
  168. #define DAP_SWO_STATUS_CAPTURE_INACTIVE 0
  169. #define DAP_SWO_STATUS_CAPTURE_ACTIVE 1
  170. #define DAP_SWO_STATUS_CAPTURE_MASK BIT(0)
  171. #define DAP_SWO_STATUS_STREAM_ERROR_MASK BIT(6)
  172. #define DAP_SWO_STATUS_BUFFER_OVERRUN_MASK BIT(7)
  173. /* CMSIS-DAP Vendor Commands
  174. * None as yet... */
  175. static const char * const info_caps_str[] = {
  176. "SWD Supported",
  177. "JTAG Supported",
  178. "SWO-UART Supported",
  179. "SWO-MANCHESTER Supported"
  180. };
  181. struct pending_transfer_result {
  182. uint8_t cmd;
  183. uint32_t data;
  184. void *buffer;
  185. };
  186. struct pending_request_block {
  187. struct pending_transfer_result *transfers;
  188. int transfer_count;
  189. };
  190. struct pending_scan_result {
  191. /** Offset in bytes in the CMD_DAP_JTAG_SEQ response buffer. */
  192. unsigned first;
  193. /** Number of bits to read. */
  194. unsigned length;
  195. /** Location to store the result */
  196. uint8_t *buffer;
  197. /** Offset in the destination buffer */
  198. unsigned buffer_offset;
  199. };
  200. /* Up to MIN(packet_count, MAX_PENDING_REQUESTS) requests may be issued
  201. * until the first response arrives */
  202. #define MAX_PENDING_REQUESTS 3
  203. /* Pending requests are organized as a FIFO - circular buffer */
  204. /* Each block in FIFO can contain up to pending_queue_len transfers */
  205. static int pending_queue_len;
  206. static struct pending_request_block pending_fifo[MAX_PENDING_REQUESTS];
  207. static int pending_fifo_put_idx, pending_fifo_get_idx;
  208. static int pending_fifo_block_count;
  209. /* pointers to buffers that will receive jtag scan results on the next flush */
  210. #define MAX_PENDING_SCAN_RESULTS 256
  211. static int pending_scan_result_count;
  212. static struct pending_scan_result pending_scan_results[MAX_PENDING_SCAN_RESULTS];
  213. /* queued JTAG sequences that will be executed on the next flush */
  214. #define QUEUED_SEQ_BUF_LEN (cmsis_dap_handle->packet_size - 3)
  215. static int queued_seq_count;
  216. static int queued_seq_buf_end;
  217. static int queued_seq_tdo_ptr;
  218. static uint8_t queued_seq_buf[1024]; /* TODO: make dynamic / move into cmsis object */
  219. static int queued_retval;
  220. static uint8_t output_pins = SWJ_PIN_SRST | SWJ_PIN_TRST;
  221. static struct cmsis_dap *cmsis_dap_handle;
  222. static int cmsis_dap_quit(void);
  223. static int cmsis_dap_open(void)
  224. {
  225. const struct cmsis_dap_backend *backend = NULL;
  226. struct cmsis_dap *dap = calloc(1, sizeof(struct cmsis_dap));
  227. if (!dap) {
  228. LOG_ERROR("unable to allocate memory");
  229. return ERROR_FAIL;
  230. }
  231. if (cmsis_dap_backend >= 0) {
  232. /* Use forced backend */
  233. backend = cmsis_dap_backends[cmsis_dap_backend];
  234. if (backend->open(dap, cmsis_dap_vid, cmsis_dap_pid, cmsis_dap_serial) != ERROR_OK)
  235. backend = NULL;
  236. } else {
  237. /* Try all backends */
  238. for (unsigned int i = 0; i < ARRAY_SIZE(cmsis_dap_backends); i++) {
  239. backend = cmsis_dap_backends[i];
  240. if (backend->open(dap, cmsis_dap_vid, cmsis_dap_pid, cmsis_dap_serial) == ERROR_OK)
  241. break;
  242. else
  243. backend = NULL;
  244. }
  245. }
  246. if (!backend) {
  247. LOG_ERROR("unable to find a matching CMSIS-DAP device");
  248. free(dap);
  249. return ERROR_FAIL;
  250. }
  251. dap->backend = backend;
  252. cmsis_dap_handle = dap;
  253. return ERROR_OK;
  254. }
  255. static void cmsis_dap_close(struct cmsis_dap *dap)
  256. {
  257. if (dap->backend) {
  258. dap->backend->close(dap);
  259. dap->backend = NULL;
  260. }
  261. free(cmsis_dap_handle->packet_buffer);
  262. free(cmsis_dap_handle);
  263. cmsis_dap_handle = NULL;
  264. free(cmsis_dap_serial);
  265. cmsis_dap_serial = NULL;
  266. for (int i = 0; i < MAX_PENDING_REQUESTS; i++) {
  267. free(pending_fifo[i].transfers);
  268. pending_fifo[i].transfers = NULL;
  269. }
  270. }
  271. static void cmsis_dap_flush_read(struct cmsis_dap *dap)
  272. {
  273. unsigned int i;
  274. /* Some CMSIS-DAP adapters keep buffered packets over
  275. * USB close/open so we need to flush up to 64 old packets
  276. * to be sure all buffers are empty */
  277. for (i = 0; i < 64; i++) {
  278. int retval = dap->backend->read(dap, 10);
  279. if (retval == ERROR_TIMEOUT_REACHED)
  280. break;
  281. }
  282. if (i)
  283. LOG_DEBUG("Flushed %u packets", i);
  284. }
  285. /* Send a message and receive the reply */
  286. static int cmsis_dap_xfer(struct cmsis_dap *dap, int txlen)
  287. {
  288. if (pending_fifo_block_count) {
  289. LOG_ERROR("pending %d blocks, flushing", pending_fifo_block_count);
  290. while (pending_fifo_block_count) {
  291. dap->backend->read(dap, 10);
  292. pending_fifo_block_count--;
  293. }
  294. pending_fifo_put_idx = 0;
  295. pending_fifo_get_idx = 0;
  296. }
  297. uint8_t current_cmd = cmsis_dap_handle->command[0];
  298. int retval = dap->backend->write(dap, txlen, USB_TIMEOUT);
  299. if (retval < 0)
  300. return retval;
  301. /* get reply */
  302. retval = dap->backend->read(dap, USB_TIMEOUT);
  303. if (retval < 0)
  304. return retval;
  305. uint8_t *resp = cmsis_dap_handle->response;
  306. if (resp[0] == DAP_ERROR) {
  307. LOG_ERROR("CMSIS-DAP command 0x%" PRIx8 " not implemented", current_cmd);
  308. return ERROR_NOT_IMPLEMENTED;
  309. }
  310. if (resp[0] != current_cmd) {
  311. LOG_ERROR("CMSIS-DAP command mismatch. Sent 0x%" PRIx8
  312. " received 0x%" PRIx8, current_cmd, resp[0]);
  313. cmsis_dap_flush_read(dap);
  314. return ERROR_FAIL;
  315. }
  316. return ERROR_OK;
  317. }
  318. static int cmsis_dap_cmd_dap_swj_pins(uint8_t pins, uint8_t mask, uint32_t delay, uint8_t *input)
  319. {
  320. uint8_t *command = cmsis_dap_handle->command;
  321. command[0] = CMD_DAP_SWJ_PINS;
  322. command[1] = pins;
  323. command[2] = mask;
  324. h_u32_to_le(&command[3], delay);
  325. int retval = cmsis_dap_xfer(cmsis_dap_handle, 7);
  326. if (retval != ERROR_OK) {
  327. LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_PINS failed.");
  328. return ERROR_JTAG_DEVICE_ERROR;
  329. }
  330. if (input)
  331. *input = cmsis_dap_handle->response[1];
  332. return ERROR_OK;
  333. }
  334. static int cmsis_dap_cmd_dap_swj_clock(uint32_t swj_clock)
  335. {
  336. uint8_t *command = cmsis_dap_handle->command;
  337. /* set clock in Hz */
  338. swj_clock *= 1000;
  339. command[0] = CMD_DAP_SWJ_CLOCK;
  340. h_u32_to_le(&command[1], swj_clock);
  341. int retval = cmsis_dap_xfer(cmsis_dap_handle, 5);
  342. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  343. LOG_ERROR("CMSIS-DAP command CMD_DAP_SWJ_CLOCK failed.");
  344. return ERROR_JTAG_DEVICE_ERROR;
  345. }
  346. return ERROR_OK;
  347. }
  348. /* clock a sequence of bits out on TMS, to change JTAG states */
  349. static int cmsis_dap_cmd_dap_swj_sequence(uint8_t s_len, const uint8_t *sequence)
  350. {
  351. uint8_t *command = cmsis_dap_handle->command;
  352. #ifdef CMSIS_DAP_JTAG_DEBUG
  353. LOG_DEBUG("cmsis-dap TMS sequence: len=%d", s_len);
  354. for (int i = 0; i < DIV_ROUND_UP(s_len, 8); ++i)
  355. printf("%02X ", sequence[i]);
  356. printf("\n");
  357. #endif
  358. command[0] = CMD_DAP_SWJ_SEQ;
  359. command[1] = s_len;
  360. bit_copy(&command[2], 0, sequence, 0, s_len);
  361. int retval = cmsis_dap_xfer(cmsis_dap_handle, 2 + DIV_ROUND_UP(s_len, 8));
  362. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK)
  363. return ERROR_FAIL;
  364. return ERROR_OK;
  365. }
  366. static int cmsis_dap_cmd_dap_info(uint8_t info, uint8_t **data)
  367. {
  368. uint8_t *command = cmsis_dap_handle->command;
  369. command[0] = CMD_DAP_INFO;
  370. command[1] = info;
  371. int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
  372. if (retval != ERROR_OK) {
  373. LOG_ERROR("CMSIS-DAP command CMD_INFO failed.");
  374. return ERROR_JTAG_DEVICE_ERROR;
  375. }
  376. *data = &cmsis_dap_handle->response[1];
  377. return ERROR_OK;
  378. }
  379. static int cmsis_dap_cmd_dap_led(uint8_t led, uint8_t state)
  380. {
  381. uint8_t *command = cmsis_dap_handle->command;
  382. command[0] = CMD_DAP_LED;
  383. command[1] = led;
  384. command[2] = state;
  385. int retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
  386. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  387. LOG_ERROR("CMSIS-DAP command CMD_LED failed.");
  388. return ERROR_JTAG_DEVICE_ERROR;
  389. }
  390. return ERROR_OK;
  391. }
  392. static int cmsis_dap_cmd_dap_connect(uint8_t mode)
  393. {
  394. uint8_t *command = cmsis_dap_handle->command;
  395. command[0] = CMD_DAP_CONNECT;
  396. command[1] = mode;
  397. int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
  398. if (retval != ERROR_OK) {
  399. LOG_ERROR("CMSIS-DAP command CMD_CONNECT failed.");
  400. return ERROR_JTAG_DEVICE_ERROR;
  401. }
  402. if (cmsis_dap_handle->response[1] != mode) {
  403. LOG_ERROR("CMSIS-DAP failed to connect in mode (%d)", mode);
  404. return ERROR_JTAG_DEVICE_ERROR;
  405. }
  406. return ERROR_OK;
  407. }
  408. static int cmsis_dap_cmd_dap_disconnect(void)
  409. {
  410. uint8_t *command = cmsis_dap_handle->command;
  411. command[0] = CMD_DAP_DISCONNECT;
  412. int retval = cmsis_dap_xfer(cmsis_dap_handle, 1);
  413. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  414. LOG_ERROR("CMSIS-DAP command CMD_DISCONNECT failed.");
  415. return ERROR_JTAG_DEVICE_ERROR;
  416. }
  417. return ERROR_OK;
  418. }
  419. static int cmsis_dap_cmd_dap_tfer_configure(uint8_t idle, uint16_t retry_count, uint16_t match_retry)
  420. {
  421. uint8_t *command = cmsis_dap_handle->command;
  422. command[0] = CMD_DAP_TFER_CONFIGURE;
  423. command[1] = idle;
  424. h_u16_to_le(&command[2], retry_count);
  425. h_u16_to_le(&command[4], match_retry);
  426. int retval = cmsis_dap_xfer(cmsis_dap_handle, 6);
  427. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  428. LOG_ERROR("CMSIS-DAP command CMD_TFER_Configure failed.");
  429. return ERROR_JTAG_DEVICE_ERROR;
  430. }
  431. return ERROR_OK;
  432. }
  433. static int cmsis_dap_cmd_dap_swd_configure(uint8_t cfg)
  434. {
  435. uint8_t *command = cmsis_dap_handle->command;
  436. command[0] = CMD_DAP_SWD_CONFIGURE;
  437. command[1] = cfg;
  438. int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
  439. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  440. LOG_ERROR("CMSIS-DAP command CMD_SWD_Configure failed.");
  441. return ERROR_JTAG_DEVICE_ERROR;
  442. }
  443. return ERROR_OK;
  444. }
  445. #if 0
  446. static int cmsis_dap_cmd_dap_delay(uint16_t delay_us)
  447. {
  448. uint8_t *command = cmsis_dap_handle->command;
  449. command[0] = CMD_DAP_DELAY;
  450. h_u16_to_le(&command[1], delay_us);
  451. int retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
  452. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  453. LOG_ERROR("CMSIS-DAP command CMD_Delay failed.");
  454. return ERROR_JTAG_DEVICE_ERROR;
  455. }
  456. return ERROR_OK;
  457. }
  458. #endif
  459. static int cmsis_dap_metacmd_targetsel(uint32_t instance_id)
  460. {
  461. uint8_t *command = cmsis_dap_handle->command;
  462. const uint32_t SEQ_RD = 0x80, SEQ_WR = 0x00;
  463. /* SWD multi-drop requires a transfer ala CMD_DAP_TFER,
  464. but with no expectation of an SWD ACK response. In
  465. CMSIS-DAP v1.20 and v2.00, CMD_DAP_SWD_SEQUENCE was
  466. added to allow this special sequence to be generated.
  467. The purpose of this operation is to select the target
  468. corresponding to the instance_id that is written */
  469. size_t idx = 0;
  470. command[idx++] = CMD_DAP_SWD_SEQUENCE;
  471. command[idx++] = 3; /* sequence count */
  472. /* sequence 0: packet request for TARGETSEL */
  473. command[idx++] = SEQ_WR | 8;
  474. command[idx++] = SWD_CMD_START | swd_cmd(false, false, DP_TARGETSEL) | SWD_CMD_STOP | SWD_CMD_PARK;
  475. /* sequence 1: read Trn ACK Trn, no expectation for target to ACK */
  476. command[idx++] = SEQ_RD | 5;
  477. /* sequence 2: WDATA plus parity */
  478. command[idx++] = SEQ_WR | (32 + 1);
  479. h_u32_to_le(command + idx, instance_id);
  480. idx += 4;
  481. command[idx++] = parity_u32(instance_id);
  482. int retval = cmsis_dap_xfer(cmsis_dap_handle, idx);
  483. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  484. LOG_ERROR("CMSIS-DAP command SWD_Sequence failed.");
  485. return ERROR_JTAG_DEVICE_ERROR;
  486. }
  487. return ERROR_OK;
  488. }
  489. /**
  490. * Sets the SWO transport mode.
  491. * @param[in] transport The transport mode. Can be None, SWO_Data or
  492. * WinUSB (requires CMSIS-DAP v2).
  493. */
  494. static int cmsis_dap_cmd_dap_swo_transport(uint8_t transport)
  495. {
  496. uint8_t *command = cmsis_dap_handle->command;
  497. command[0] = CMD_DAP_SWO_TRANSPORT;
  498. command[1] = transport;
  499. int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
  500. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  501. LOG_ERROR("CMSIS-DAP: command CMD_SWO_Transport(%d) failed.", transport);
  502. return ERROR_JTAG_DEVICE_ERROR;
  503. }
  504. return ERROR_OK;
  505. }
  506. /**
  507. * Sets the SWO trace capture mode.
  508. * @param[in] mode Trace capture mode. Can be UART or MANCHESTER.
  509. */
  510. static int cmsis_dap_cmd_dap_swo_mode(uint8_t mode)
  511. {
  512. uint8_t *command = cmsis_dap_handle->command;
  513. command[0] = CMD_DAP_SWO_MODE;
  514. command[1] = mode;
  515. int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
  516. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  517. LOG_ERROR("CMSIS-DAP: command CMD_SWO_Mode(%d) failed.", mode);
  518. return ERROR_JTAG_DEVICE_ERROR;
  519. }
  520. return ERROR_OK;
  521. }
  522. /**
  523. * Sets the baudrate for capturing SWO trace data.
  524. * Can be called iteratively to determine supported baudrates.
  525. * @param[in] in_baudrate Requested baudrate.
  526. * @param[out] dev_baudrate Actual baudrate or 0 (baudrate not configured).
  527. * When requested baudrate is not achievable the
  528. * closest configured baudrate can be returned or
  529. * 0 which indicates that baudrate was not configured.
  530. */
  531. static int cmsis_dap_cmd_dap_swo_baudrate(
  532. uint32_t in_baudrate,
  533. uint32_t *dev_baudrate)
  534. {
  535. uint8_t *command = cmsis_dap_handle->command;
  536. command[0] = CMD_DAP_SWO_BAUDRATE;
  537. h_u32_to_le(&command[1], in_baudrate);
  538. int retval = cmsis_dap_xfer(cmsis_dap_handle, 4);
  539. uint32_t rvbr = le_to_h_u32(&cmsis_dap_handle->response[1]);
  540. if (retval != ERROR_OK || rvbr == 0) {
  541. LOG_ERROR("CMSIS-DAP: command CMD_SWO_Baudrate(%u) -> %u failed.", in_baudrate, rvbr);
  542. if (dev_baudrate)
  543. *dev_baudrate = 0;
  544. return ERROR_JTAG_DEVICE_ERROR;
  545. }
  546. if (dev_baudrate)
  547. *dev_baudrate = rvbr;
  548. return ERROR_OK;
  549. }
  550. /**
  551. * Controls the SWO trace data capture.
  552. * @param[in] control Start or stop a trace. Starting capture automatically
  553. * flushes any existing trace data in buffers which has
  554. * not yet been read.
  555. */
  556. static int cmsis_dap_cmd_dap_swo_control(uint8_t control)
  557. {
  558. uint8_t *command = cmsis_dap_handle->command;
  559. command[0] = CMD_DAP_SWO_CONTROL;
  560. command[1] = control;
  561. int retval = cmsis_dap_xfer(cmsis_dap_handle, 2);
  562. if (retval != ERROR_OK || cmsis_dap_handle->response[1] != DAP_OK) {
  563. LOG_ERROR("CMSIS-DAP: command CMD_SWO_Control(%d) failed.", control);
  564. return ERROR_JTAG_DEVICE_ERROR;
  565. }
  566. return ERROR_OK;
  567. }
  568. /**
  569. * Reads the SWO trace status.
  570. * @param[out] trace_status The trace's status.
  571. * Bit0: Trace Capture (1 - active, 0 - inactive).
  572. * Bit6: Trace Stream Error.
  573. * Bit7: Trace Buffer Overrun.
  574. * @param[out] trace_count Number of bytes in Trace Buffer (not yet read).
  575. */
  576. static int cmsis_dap_cmd_dap_swo_status(
  577. uint8_t *trace_status,
  578. size_t *trace_count)
  579. {
  580. uint8_t *command = cmsis_dap_handle->command;
  581. command[0] = CMD_DAP_SWO_STATUS;
  582. int retval = cmsis_dap_xfer(cmsis_dap_handle, 1);
  583. if (retval != ERROR_OK) {
  584. LOG_ERROR("CMSIS-DAP: command CMD_SWO_Status failed.");
  585. return ERROR_JTAG_DEVICE_ERROR;
  586. }
  587. if (trace_status)
  588. *trace_status = cmsis_dap_handle->response[1];
  589. if (trace_count)
  590. *trace_count = le_to_h_u32(&cmsis_dap_handle->response[2]);
  591. return ERROR_OK;
  592. }
  593. /**
  594. * Reads the captured SWO trace data from Trace Buffer.
  595. * @param[in] max_trace_count Maximum number of Trace Data bytes to read.
  596. * @param[out] trace_status The trace's status.
  597. * @param[out] trace_count Number of Trace Data bytes read.
  598. * @param[out] data Trace Data bytes read.
  599. */
  600. static int cmsis_dap_cmd_dap_swo_data(
  601. size_t max_trace_count,
  602. uint8_t *trace_status,
  603. size_t *trace_count,
  604. uint8_t *data)
  605. {
  606. uint8_t *command = cmsis_dap_handle->command;
  607. command[0] = CMD_DAP_SWO_DATA;
  608. h_u16_to_le(&command[1], max_trace_count);
  609. int retval = cmsis_dap_xfer(cmsis_dap_handle, 3);
  610. if (retval != ERROR_OK) {
  611. LOG_ERROR("CMSIS-DAP: command CMD_SWO_Data failed.");
  612. return ERROR_JTAG_DEVICE_ERROR;
  613. }
  614. *trace_status = cmsis_dap_handle->response[1];
  615. *trace_count = le_to_h_u16(&cmsis_dap_handle->response[2]);
  616. if (*trace_count > 0)
  617. memcpy(data, &cmsis_dap_handle->response[4], *trace_count);
  618. return ERROR_OK;
  619. }
  620. static void cmsis_dap_swd_write_from_queue(struct cmsis_dap *dap)
  621. {
  622. uint8_t *command = cmsis_dap_handle->command;
  623. struct pending_request_block *block = &pending_fifo[pending_fifo_put_idx];
  624. LOG_DEBUG_IO("Executing %d queued transactions from FIFO index %d", block->transfer_count, pending_fifo_put_idx);
  625. if (queued_retval != ERROR_OK) {
  626. LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
  627. goto skip;
  628. }
  629. if (block->transfer_count == 0)
  630. goto skip;
  631. command[0] = CMD_DAP_TFER;
  632. command[1] = 0x00; /* DAP Index */
  633. command[2] = block->transfer_count;
  634. size_t idx = 3;
  635. for (int i = 0; i < block->transfer_count; i++) {
  636. struct pending_transfer_result *transfer = &(block->transfers[i]);
  637. uint8_t cmd = transfer->cmd;
  638. uint32_t data = transfer->data;
  639. LOG_DEBUG_IO("%s %s reg %x %"PRIx32,
  640. cmd & SWD_CMD_APNDP ? "AP" : "DP",
  641. cmd & SWD_CMD_RNW ? "read" : "write",
  642. (cmd & SWD_CMD_A32) >> 1, data);
  643. /* When proper WAIT handling is implemented in the
  644. * common SWD framework, this kludge can be
  645. * removed. However, this might lead to minor
  646. * performance degradation as the adapter wouldn't be
  647. * able to automatically retry anything (because ARM
  648. * has forgotten to implement sticky error flags
  649. * clearing). See also comments regarding
  650. * cmsis_dap_cmd_dap_tfer_configure() and
  651. * cmsis_dap_cmd_dap_swd_configure() in
  652. * cmsis_dap_init().
  653. */
  654. if (!(cmd & SWD_CMD_RNW) &&
  655. !(cmd & SWD_CMD_APNDP) &&
  656. (cmd & SWD_CMD_A32) >> 1 == DP_CTRL_STAT &&
  657. (data & CORUNDETECT)) {
  658. LOG_DEBUG("refusing to enable sticky overrun detection");
  659. data &= ~CORUNDETECT;
  660. }
  661. command[idx++] = (cmd >> 1) & 0x0f;
  662. if (!(cmd & SWD_CMD_RNW)) {
  663. h_u32_to_le(&command[idx], data);
  664. idx += 4;
  665. }
  666. }
  667. int retval = dap->backend->write(dap, idx, USB_TIMEOUT);
  668. if (retval < 0) {
  669. queued_retval = retval;
  670. goto skip;
  671. } else {
  672. queued_retval = ERROR_OK;
  673. }
  674. pending_fifo_put_idx = (pending_fifo_put_idx + 1) % dap->packet_count;
  675. pending_fifo_block_count++;
  676. if (pending_fifo_block_count > dap->packet_count)
  677. LOG_ERROR("too much pending writes %d", pending_fifo_block_count);
  678. return;
  679. skip:
  680. block->transfer_count = 0;
  681. }
  682. static void cmsis_dap_swd_read_process(struct cmsis_dap *dap, int timeout_ms)
  683. {
  684. struct pending_request_block *block = &pending_fifo[pending_fifo_get_idx];
  685. if (pending_fifo_block_count == 0)
  686. LOG_ERROR("no pending write");
  687. /* get reply */
  688. int retval = dap->backend->read(dap, timeout_ms);
  689. if (retval == ERROR_TIMEOUT_REACHED && timeout_ms < USB_TIMEOUT)
  690. return;
  691. if (retval <= 0) {
  692. LOG_DEBUG("error reading data");
  693. queued_retval = ERROR_FAIL;
  694. goto skip;
  695. }
  696. uint8_t *resp = dap->response;
  697. if (resp[0] != CMD_DAP_TFER) {
  698. LOG_ERROR("CMSIS-DAP command mismatch. Expected 0x%x received 0x%" PRIx8,
  699. CMD_DAP_TFER, resp[0]);
  700. queued_retval = ERROR_FAIL;
  701. goto skip;
  702. }
  703. uint8_t transfer_count = resp[1];
  704. uint8_t ack = resp[2] & 0x07;
  705. if (resp[2] & 0x08) {
  706. LOG_DEBUG("CMSIS-DAP Protocol Error @ %d (wrong parity)", transfer_count);
  707. queued_retval = ERROR_FAIL;
  708. goto skip;
  709. }
  710. if (ack != SWD_ACK_OK) {
  711. LOG_DEBUG("SWD ack not OK @ %d %s", transfer_count,
  712. ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
  713. queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
  714. /* TODO: use results of transfers completed before the error occurred? */
  715. goto skip;
  716. }
  717. if (block->transfer_count != transfer_count)
  718. LOG_ERROR("CMSIS-DAP transfer count mismatch: expected %d, got %d",
  719. block->transfer_count, transfer_count);
  720. LOG_DEBUG_IO("Received results of %d queued transactions FIFO index %d",
  721. transfer_count, pending_fifo_get_idx);
  722. size_t idx = 3;
  723. for (int i = 0; i < transfer_count; i++) {
  724. struct pending_transfer_result *transfer = &(block->transfers[i]);
  725. if (transfer->cmd & SWD_CMD_RNW) {
  726. static uint32_t last_read;
  727. uint32_t data = le_to_h_u32(&resp[idx]);
  728. uint32_t tmp = data;
  729. idx += 4;
  730. LOG_DEBUG_IO("Read result: %"PRIx32, data);
  731. /* Imitate posted AP reads */
  732. if ((transfer->cmd & SWD_CMD_APNDP) ||
  733. ((transfer->cmd & SWD_CMD_A32) >> 1 == DP_RDBUFF)) {
  734. tmp = last_read;
  735. last_read = data;
  736. }
  737. if (transfer->buffer)
  738. *(uint32_t *)(transfer->buffer) = tmp;
  739. }
  740. }
  741. skip:
  742. block->transfer_count = 0;
  743. pending_fifo_get_idx = (pending_fifo_get_idx + 1) % dap->packet_count;
  744. pending_fifo_block_count--;
  745. }
  746. static int cmsis_dap_swd_run_queue(void)
  747. {
  748. if (pending_fifo_block_count)
  749. cmsis_dap_swd_read_process(cmsis_dap_handle, 0);
  750. cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
  751. while (pending_fifo_block_count)
  752. cmsis_dap_swd_read_process(cmsis_dap_handle, USB_TIMEOUT);
  753. pending_fifo_put_idx = 0;
  754. pending_fifo_get_idx = 0;
  755. int retval = queued_retval;
  756. queued_retval = ERROR_OK;
  757. return retval;
  758. }
  759. static void cmsis_dap_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data)
  760. {
  761. bool targetsel_cmd = swd_cmd(false, false, DP_TARGETSEL) == cmd;
  762. if (pending_fifo[pending_fifo_put_idx].transfer_count == pending_queue_len
  763. || targetsel_cmd) {
  764. if (pending_fifo_block_count)
  765. cmsis_dap_swd_read_process(cmsis_dap_handle, 0);
  766. /* Not enough room in the queue. Run the queue. */
  767. cmsis_dap_swd_write_from_queue(cmsis_dap_handle);
  768. if (pending_fifo_block_count >= cmsis_dap_handle->packet_count)
  769. cmsis_dap_swd_read_process(cmsis_dap_handle, USB_TIMEOUT);
  770. }
  771. if (queued_retval != ERROR_OK)
  772. return;
  773. if (targetsel_cmd) {
  774. cmsis_dap_metacmd_targetsel(data);
  775. return;
  776. }
  777. struct pending_request_block *block = &pending_fifo[pending_fifo_put_idx];
  778. struct pending_transfer_result *transfer = &(block->transfers[block->transfer_count]);
  779. transfer->data = data;
  780. transfer->cmd = cmd;
  781. if (cmd & SWD_CMD_RNW) {
  782. /* Queue a read transaction */
  783. transfer->buffer = dst;
  784. }
  785. block->transfer_count++;
  786. }
  787. static void cmsis_dap_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
  788. {
  789. assert(!(cmd & SWD_CMD_RNW));
  790. cmsis_dap_swd_queue_cmd(cmd, NULL, value);
  791. }
  792. static void cmsis_dap_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
  793. {
  794. assert(cmd & SWD_CMD_RNW);
  795. cmsis_dap_swd_queue_cmd(cmd, value, 0);
  796. }
  797. static int cmsis_dap_get_serial_info(void)
  798. {
  799. uint8_t *data;
  800. int retval = cmsis_dap_cmd_dap_info(INFO_ID_SERNUM, &data);
  801. if (retval != ERROR_OK)
  802. return retval;
  803. if (data[0]) /* strlen */
  804. LOG_INFO("CMSIS-DAP: Serial# = %s", &data[1]);
  805. return ERROR_OK;
  806. }
  807. static int cmsis_dap_get_version_info(void)
  808. {
  809. uint8_t *data;
  810. /* INFO_ID_FW_VER - string */
  811. int retval = cmsis_dap_cmd_dap_info(INFO_ID_FW_VER, &data);
  812. if (retval != ERROR_OK)
  813. return retval;
  814. if (data[0]) /* strlen */
  815. LOG_INFO("CMSIS-DAP: FW Version = %s", &data[1]);
  816. return ERROR_OK;
  817. }
  818. static int cmsis_dap_get_caps_info(void)
  819. {
  820. uint8_t *data;
  821. /* INFO_ID_CAPS - byte */
  822. int retval = cmsis_dap_cmd_dap_info(INFO_ID_CAPS, &data);
  823. if (retval != ERROR_OK)
  824. return retval;
  825. if (data[0] == 1) {
  826. uint8_t caps = data[1];
  827. cmsis_dap_handle->caps = caps;
  828. if (caps & INFO_CAPS_SWD)
  829. LOG_INFO("CMSIS-DAP: %s", info_caps_str[0]);
  830. if (caps & INFO_CAPS_JTAG)
  831. LOG_INFO("CMSIS-DAP: %s", info_caps_str[1]);
  832. if (caps & INFO_CAPS_SWO_UART)
  833. LOG_INFO("CMSIS-DAP: %s", info_caps_str[2]);
  834. if (caps & INFO_CAPS_SWO_MANCHESTER)
  835. LOG_INFO("CMSIS-DAP: %s", info_caps_str[3]);
  836. }
  837. return ERROR_OK;
  838. }
  839. static int cmsis_dap_get_swo_buf_sz(uint32_t *swo_buf_sz)
  840. {
  841. uint8_t *data;
  842. /* INFO_ID_SWO_BUF_SZ - word */
  843. int retval = cmsis_dap_cmd_dap_info(INFO_ID_SWO_BUF_SZ, &data);
  844. if (retval != ERROR_OK)
  845. return retval;
  846. if (data[0] != 4)
  847. return ERROR_FAIL;
  848. *swo_buf_sz = le_to_h_u32(&data[1]);
  849. LOG_INFO("CMSIS-DAP: SWO Trace Buffer Size = %u bytes", *swo_buf_sz);
  850. return ERROR_OK;
  851. }
  852. static int cmsis_dap_get_status(void)
  853. {
  854. uint8_t d;
  855. int retval = cmsis_dap_cmd_dap_swj_pins(0, 0, 0, &d);
  856. if (retval == ERROR_OK) {
  857. LOG_INFO("SWCLK/TCK = %d SWDIO/TMS = %d TDI = %d TDO = %d nTRST = %d nRESET = %d",
  858. (d & SWJ_PIN_TCK) ? 1 : 0,
  859. (d & SWJ_PIN_TMS) ? 1 : 0,
  860. (d & SWJ_PIN_TDI) ? 1 : 0,
  861. (d & SWJ_PIN_TDO) ? 1 : 0,
  862. (d & SWJ_PIN_TRST) ? 1 : 0,
  863. (d & SWJ_PIN_SRST) ? 1 : 0);
  864. }
  865. return retval;
  866. }
  867. static int cmsis_dap_swd_switch_seq(enum swd_special_seq seq)
  868. {
  869. const uint8_t *s;
  870. unsigned int s_len;
  871. int retval;
  872. if ((output_pins & (SWJ_PIN_SRST | SWJ_PIN_TRST)) == (SWJ_PIN_SRST | SWJ_PIN_TRST)) {
  873. /* Following workaround deasserts reset on most adapters.
  874. * Do not reconnect if a reset line is active!
  875. * Reconnecting would break connecting under reset. */
  876. /* First disconnect before connecting, Atmel EDBG needs it for SAMD/R/L/C */
  877. cmsis_dap_cmd_dap_disconnect();
  878. /* When we are reconnecting, DAP_Connect needs to be rerun, at
  879. * least on Keil ULINK-ME */
  880. retval = cmsis_dap_cmd_dap_connect(CONNECT_SWD);
  881. if (retval != ERROR_OK)
  882. return retval;
  883. }
  884. switch (seq) {
  885. case LINE_RESET:
  886. LOG_DEBUG_IO("SWD line reset");
  887. s = swd_seq_line_reset;
  888. s_len = swd_seq_line_reset_len;
  889. break;
  890. case JTAG_TO_SWD:
  891. LOG_DEBUG("JTAG-to-SWD");
  892. s = swd_seq_jtag_to_swd;
  893. s_len = swd_seq_jtag_to_swd_len;
  894. break;
  895. case JTAG_TO_DORMANT:
  896. LOG_DEBUG("JTAG-to-DORMANT");
  897. s = swd_seq_jtag_to_dormant;
  898. s_len = swd_seq_jtag_to_dormant_len;
  899. break;
  900. case SWD_TO_JTAG:
  901. LOG_DEBUG("SWD-to-JTAG");
  902. s = swd_seq_swd_to_jtag;
  903. s_len = swd_seq_swd_to_jtag_len;
  904. break;
  905. case SWD_TO_DORMANT:
  906. LOG_DEBUG("SWD-to-DORMANT");
  907. s = swd_seq_swd_to_dormant;
  908. s_len = swd_seq_swd_to_dormant_len;
  909. break;
  910. case DORMANT_TO_SWD:
  911. LOG_DEBUG("DORMANT-to-SWD");
  912. s = swd_seq_dormant_to_swd;
  913. s_len = swd_seq_dormant_to_swd_len;
  914. break;
  915. default:
  916. LOG_ERROR("Sequence %d not supported", seq);
  917. return ERROR_FAIL;
  918. }
  919. retval = cmsis_dap_cmd_dap_swj_sequence(s_len, s);
  920. if (retval != ERROR_OK)
  921. return retval;
  922. /* Atmel EDBG needs renew clock setting after SWJ_Sequence
  923. * otherwise default frequency is used */
  924. return cmsis_dap_cmd_dap_swj_clock(jtag_get_speed_khz());
  925. }
  926. static int cmsis_dap_swd_open(void)
  927. {
  928. if (!(cmsis_dap_handle->caps & INFO_CAPS_SWD)) {
  929. LOG_ERROR("CMSIS-DAP: SWD not supported");
  930. return ERROR_JTAG_DEVICE_ERROR;
  931. }
  932. int retval = cmsis_dap_cmd_dap_connect(CONNECT_SWD);
  933. if (retval != ERROR_OK)
  934. return retval;
  935. /* Add more setup here.??... */
  936. LOG_INFO("CMSIS-DAP: Interface Initialised (SWD)");
  937. return ERROR_OK;
  938. }
  939. static int cmsis_dap_init(void)
  940. {
  941. uint8_t *data;
  942. int retval = cmsis_dap_open();
  943. if (retval != ERROR_OK)
  944. return retval;
  945. cmsis_dap_flush_read(cmsis_dap_handle);
  946. retval = cmsis_dap_get_caps_info();
  947. if (retval != ERROR_OK)
  948. return retval;
  949. retval = cmsis_dap_get_version_info();
  950. if (retval != ERROR_OK)
  951. return retval;
  952. retval = cmsis_dap_get_serial_info();
  953. if (retval != ERROR_OK)
  954. return retval;
  955. if (swd_mode) {
  956. retval = cmsis_dap_swd_open();
  957. if (retval != ERROR_OK)
  958. return retval;
  959. } else {
  960. /* Connect in JTAG mode */
  961. if (!(cmsis_dap_handle->caps & INFO_CAPS_JTAG)) {
  962. LOG_ERROR("CMSIS-DAP: JTAG not supported");
  963. return ERROR_JTAG_DEVICE_ERROR;
  964. }
  965. retval = cmsis_dap_cmd_dap_connect(CONNECT_JTAG);
  966. if (retval != ERROR_OK)
  967. return retval;
  968. LOG_INFO("CMSIS-DAP: Interface Initialised (JTAG)");
  969. }
  970. /* Be conservative and suppress submitting multiple HID requests
  971. * until we get packet count info from the adaptor */
  972. cmsis_dap_handle->packet_count = 1;
  973. pending_queue_len = 12;
  974. /* INFO_ID_PKT_SZ - short */
  975. retval = cmsis_dap_cmd_dap_info(INFO_ID_PKT_SZ, &data);
  976. if (retval != ERROR_OK)
  977. goto init_err;
  978. if (data[0] == 2) { /* short */
  979. uint16_t pkt_sz = data[1] + (data[2] << 8);
  980. if (pkt_sz != cmsis_dap_handle->packet_size) {
  981. /* 4 bytes of command header + 5 bytes per register
  982. * write. For bulk read sequences just 4 bytes are
  983. * needed per transfer, so this is suboptimal. */
  984. pending_queue_len = (pkt_sz - 4) / 5;
  985. free(cmsis_dap_handle->packet_buffer);
  986. retval = cmsis_dap_handle->backend->packet_buffer_alloc(cmsis_dap_handle, pkt_sz);
  987. if (retval != ERROR_OK)
  988. goto init_err;
  989. LOG_DEBUG("CMSIS-DAP: Packet Size = %" PRIu16, pkt_sz);
  990. }
  991. }
  992. /* INFO_ID_PKT_CNT - byte */
  993. retval = cmsis_dap_cmd_dap_info(INFO_ID_PKT_CNT, &data);
  994. if (retval != ERROR_OK)
  995. goto init_err;
  996. if (data[0] == 1) { /* byte */
  997. int pkt_cnt = data[1];
  998. if (pkt_cnt > 1)
  999. cmsis_dap_handle->packet_count = MIN(MAX_PENDING_REQUESTS, pkt_cnt);
  1000. LOG_DEBUG("CMSIS-DAP: Packet Count = %d", pkt_cnt);
  1001. }
  1002. LOG_DEBUG("Allocating FIFO for %d pending packets", cmsis_dap_handle->packet_count);
  1003. for (int i = 0; i < cmsis_dap_handle->packet_count; i++) {
  1004. pending_fifo[i].transfers = malloc(pending_queue_len * sizeof(struct pending_transfer_result));
  1005. if (!pending_fifo[i].transfers) {
  1006. LOG_ERROR("Unable to allocate memory for CMSIS-DAP queue");
  1007. retval = ERROR_FAIL;
  1008. goto init_err;
  1009. }
  1010. }
  1011. /* Intentionally not checked for error, just logs an info message
  1012. * not vital for further debugging */
  1013. (void)cmsis_dap_get_status();
  1014. /* Now try to connect to the target
  1015. * TODO: This is all SWD only @ present */
  1016. retval = cmsis_dap_cmd_dap_swj_clock(jtag_get_speed_khz());
  1017. if (retval != ERROR_OK)
  1018. goto init_err;
  1019. /* Ask CMSIS-DAP to automatically retry on receiving WAIT for
  1020. * up to 64 times. This must be changed to 0 if sticky
  1021. * overrun detection is enabled. */
  1022. retval = cmsis_dap_cmd_dap_tfer_configure(0, 64, 0);
  1023. if (retval != ERROR_OK)
  1024. goto init_err;
  1025. if (swd_mode) {
  1026. /* Data Phase (bit 2) must be set to 1 if sticky overrun
  1027. * detection is enabled */
  1028. retval = cmsis_dap_cmd_dap_swd_configure(0); /* 1 TRN, no Data Phase */
  1029. if (retval != ERROR_OK)
  1030. goto init_err;
  1031. }
  1032. /* Both LEDs on */
  1033. /* Intentionally not checked for error, debugging will work
  1034. * without LEDs */
  1035. (void)cmsis_dap_cmd_dap_led(LED_ID_CONNECT, LED_ON);
  1036. (void)cmsis_dap_cmd_dap_led(LED_ID_RUN, LED_ON);
  1037. /* support connecting with srst asserted */
  1038. enum reset_types jtag_reset_config = jtag_get_reset_config();
  1039. if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
  1040. if (jtag_reset_config & RESET_SRST_NO_GATING) {
  1041. retval = cmsis_dap_cmd_dap_swj_pins(0, SWJ_PIN_SRST, 0, NULL);
  1042. if (retval != ERROR_OK)
  1043. goto init_err;
  1044. LOG_INFO("Connecting under reset");
  1045. }
  1046. }
  1047. LOG_INFO("CMSIS-DAP: Interface ready");
  1048. return ERROR_OK;
  1049. init_err:
  1050. cmsis_dap_quit();
  1051. return retval;
  1052. }
  1053. static int cmsis_dap_swd_init(void)
  1054. {
  1055. swd_mode = true;
  1056. return ERROR_OK;
  1057. }
  1058. static int cmsis_dap_quit(void)
  1059. {
  1060. cmsis_dap_cmd_dap_disconnect();
  1061. /* Both LEDs off */
  1062. cmsis_dap_cmd_dap_led(LED_ID_RUN, LED_OFF);
  1063. cmsis_dap_cmd_dap_led(LED_ID_CONNECT, LED_OFF);
  1064. cmsis_dap_close(cmsis_dap_handle);
  1065. return ERROR_OK;
  1066. }
  1067. static int cmsis_dap_reset(int trst, int srst)
  1068. {
  1069. /* Set both TRST and SRST even if they're not enabled as
  1070. * there's no way to tristate them */
  1071. output_pins = 0;
  1072. if (!srst)
  1073. output_pins |= SWJ_PIN_SRST;
  1074. if (!trst)
  1075. output_pins |= SWJ_PIN_TRST;
  1076. int retval = cmsis_dap_cmd_dap_swj_pins(output_pins,
  1077. SWJ_PIN_TRST | SWJ_PIN_SRST, 0, NULL);
  1078. if (retval != ERROR_OK)
  1079. LOG_ERROR("CMSIS-DAP: Interface reset failed");
  1080. return retval;
  1081. }
  1082. static void cmsis_dap_execute_sleep(struct jtag_command *cmd)
  1083. {
  1084. #if 0
  1085. int retval = cmsis_dap_cmd_dap_delay(cmd->cmd.sleep->us);
  1086. if (retval != ERROR_OK)
  1087. #endif
  1088. jtag_sleep(cmd->cmd.sleep->us);
  1089. }
  1090. /* Set TMS high for five TCK clocks, to move the TAP to the Test-Logic-Reset state */
  1091. static int cmsis_dap_execute_tlr_reset(struct jtag_command *cmd)
  1092. {
  1093. LOG_INFO("cmsis-dap JTAG TLR_RESET");
  1094. uint8_t seq = 0xff;
  1095. int retval = cmsis_dap_cmd_dap_swj_sequence(8, &seq);
  1096. if (retval == ERROR_OK)
  1097. tap_set_state(TAP_RESET);
  1098. return retval;
  1099. }
  1100. /* Set new end state */
  1101. static void cmsis_dap_end_state(tap_state_t state)
  1102. {
  1103. if (tap_is_state_stable(state))
  1104. tap_set_end_state(state);
  1105. else {
  1106. LOG_ERROR("BUG: %i is not a valid end state", state);
  1107. exit(-1);
  1108. }
  1109. }
  1110. #ifdef SPRINT_BINARY
  1111. static void sprint_binary(char *s, const uint8_t *buf, int offset, int len)
  1112. {
  1113. if (!len)
  1114. return;
  1115. /*
  1116. buf = { 0x18 } len=5 should result in: 11000
  1117. buf = { 0xff 0x18 } len=13 should result in: 11111111 11000
  1118. buf = { 0xc0 0x18 } offset=3 len=10 should result in: 11000 11000
  1119. i=3 there means i/8 = 0 so c = 0xFF, and
  1120. */
  1121. for (int i = offset; i < offset + len; ++i) {
  1122. uint8_t c = buf[i / 8], mask = 1 << (i % 8);
  1123. if ((i != offset) && !(i % 8))
  1124. putchar(' ');
  1125. *s++ = (c & mask) ? '1' : '0';
  1126. }
  1127. *s = 0;
  1128. }
  1129. #endif
  1130. #ifdef CMSIS_DAP_JTAG_DEBUG
  1131. static void debug_parse_cmsis_buf(const uint8_t *cmd, int cmdlen)
  1132. {
  1133. /* cmd is a usb packet to go to the cmsis-dap interface */
  1134. printf("cmsis-dap buffer (%d b): ", cmdlen);
  1135. for (int i = 0; i < cmdlen; ++i)
  1136. printf(" %02x", cmd[i]);
  1137. printf("\n");
  1138. switch (cmd[1]) {
  1139. case CMD_DAP_JTAG_SEQ: {
  1140. printf("cmsis-dap jtag sequence command %02x (n=%d)\n", cmd[1], cmd[2]);
  1141. /*
  1142. * #2 = number of sequences
  1143. * #3 = sequence info 1
  1144. * #4...4+n_bytes-1 = sequence 1
  1145. * #4+n_bytes = sequence info 2
  1146. * #5+n_bytes = sequence 2 (single bit)
  1147. */
  1148. int pos = 3;
  1149. for (int seq = 0; seq < cmd[2]; ++seq) {
  1150. uint8_t info = cmd[pos++];
  1151. int len = info & DAP_JTAG_SEQ_TCK;
  1152. if (len == 0)
  1153. len = 64;
  1154. printf(" sequence %d starting %d: info %02x (len=%d tms=%d read_tdo=%d): ",
  1155. seq, pos, info, len, info & DAP_JTAG_SEQ_TMS, info & DAP_JTAG_SEQ_TDO);
  1156. for (int i = 0; i < DIV_ROUND_UP(len, 8); ++i)
  1157. printf(" %02x", cmd[pos+i]);
  1158. pos += DIV_ROUND_UP(len, 8);
  1159. printf("\n");
  1160. }
  1161. if (pos != cmdlen) {
  1162. printf("BUFFER LENGTH MISMATCH looks like %d but %d specified", pos, cmdlen);
  1163. exit(-1);
  1164. }
  1165. break;
  1166. }
  1167. default:
  1168. LOG_DEBUG("unknown cmsis-dap command %02x", cmd[1]);
  1169. break;
  1170. }
  1171. }
  1172. #endif
  1173. static void cmsis_dap_flush(void)
  1174. {
  1175. if (!queued_seq_count)
  1176. return;
  1177. LOG_DEBUG_IO("Flushing %d queued sequences (%d bytes) with %d pending scan results to capture",
  1178. queued_seq_count, queued_seq_buf_end, pending_scan_result_count);
  1179. /* prepare CMSIS-DAP packet */
  1180. uint8_t *command = cmsis_dap_handle->command;
  1181. command[0] = CMD_DAP_JTAG_SEQ;
  1182. command[1] = queued_seq_count;
  1183. memcpy(&command[2], queued_seq_buf, queued_seq_buf_end);
  1184. #ifdef CMSIS_DAP_JTAG_DEBUG
  1185. debug_parse_cmsis_buf(command, queued_seq_buf_end + 2);
  1186. #endif
  1187. /* send command to USB device */
  1188. int retval = cmsis_dap_xfer(cmsis_dap_handle, queued_seq_buf_end + 2);
  1189. uint8_t *resp = cmsis_dap_handle->response;
  1190. if (retval != ERROR_OK || resp[1] != DAP_OK) {
  1191. LOG_ERROR("CMSIS-DAP command CMD_DAP_JTAG_SEQ failed.");
  1192. exit(-1);
  1193. }
  1194. #ifdef CMSIS_DAP_JTAG_DEBUG
  1195. LOG_DEBUG_IO("USB response buf:");
  1196. for (int c = 0; c < queued_seq_buf_end + 3; ++c)
  1197. printf("%02X ", resp[c]);
  1198. printf("\n");
  1199. #endif
  1200. /* copy scan results into client buffers */
  1201. for (int i = 0; i < pending_scan_result_count; ++i) {
  1202. struct pending_scan_result *scan = &pending_scan_results[i];
  1203. LOG_DEBUG_IO("Copying pending_scan_result %d/%d: %d bits from byte %d -> buffer + %d bits",
  1204. i, pending_scan_result_count, scan->length, scan->first + 2, scan->buffer_offset);
  1205. #ifdef CMSIS_DAP_JTAG_DEBUG
  1206. for (uint32_t b = 0; b < DIV_ROUND_UP(scan->length, 8); ++b)
  1207. printf("%02X ", resp[2+scan->first+b]);
  1208. printf("\n");
  1209. #endif
  1210. bit_copy(scan->buffer, scan->buffer_offset, &resp[2 + scan->first], 0, scan->length);
  1211. }
  1212. /* reset */
  1213. queued_seq_count = 0;
  1214. queued_seq_buf_end = 0;
  1215. queued_seq_tdo_ptr = 0;
  1216. pending_scan_result_count = 0;
  1217. }
  1218. /* queue a sequence of bits to clock out TDI / in TDO, executing if the buffer is full.
  1219. *
  1220. * sequence=NULL means clock out zeros on TDI
  1221. * tdo_buffer=NULL means don't capture TDO
  1222. */
  1223. static void cmsis_dap_add_jtag_sequence(int s_len, const uint8_t *sequence, int s_offset,
  1224. bool tms, uint8_t *tdo_buffer, int tdo_buffer_offset)
  1225. {
  1226. LOG_DEBUG_IO("[at %d] %d bits, tms %s, seq offset %d, tdo buf %p, tdo offset %d",
  1227. queued_seq_buf_end,
  1228. s_len, tms ? "HIGH" : "LOW", s_offset, tdo_buffer, tdo_buffer_offset);
  1229. if (s_len == 0)
  1230. return;
  1231. if (s_len > 64) {
  1232. LOG_DEBUG_IO("START JTAG SEQ SPLIT");
  1233. for (int offset = 0; offset < s_len; offset += 64) {
  1234. int len = s_len - offset;
  1235. if (len > 64)
  1236. len = 64;
  1237. LOG_DEBUG_IO("Splitting long jtag sequence: %d-bit chunk starting at offset %d", len, offset);
  1238. cmsis_dap_add_jtag_sequence(
  1239. len,
  1240. sequence,
  1241. s_offset + offset,
  1242. tms,
  1243. tdo_buffer,
  1244. !tdo_buffer ? 0 : (tdo_buffer_offset + offset)
  1245. );
  1246. }
  1247. LOG_DEBUG_IO("END JTAG SEQ SPLIT");
  1248. return;
  1249. }
  1250. int cmd_len = 1 + DIV_ROUND_UP(s_len, 8);
  1251. if (queued_seq_count >= 255 || queued_seq_buf_end + cmd_len > QUEUED_SEQ_BUF_LEN)
  1252. /* empty out the buffer */
  1253. cmsis_dap_flush();
  1254. ++queued_seq_count;
  1255. /* control byte */
  1256. queued_seq_buf[queued_seq_buf_end] =
  1257. (tms ? DAP_JTAG_SEQ_TMS : 0) |
  1258. (tdo_buffer ? DAP_JTAG_SEQ_TDO : 0) |
  1259. (s_len == 64 ? 0 : s_len);
  1260. if (sequence)
  1261. bit_copy(&queued_seq_buf[queued_seq_buf_end + 1], 0, sequence, s_offset, s_len);
  1262. else
  1263. memset(&queued_seq_buf[queued_seq_buf_end + 1], 0, DIV_ROUND_UP(s_len, 8));
  1264. queued_seq_buf_end += cmd_len;
  1265. if (tdo_buffer) {
  1266. struct pending_scan_result *scan = &pending_scan_results[pending_scan_result_count++];
  1267. scan->first = queued_seq_tdo_ptr;
  1268. queued_seq_tdo_ptr += DIV_ROUND_UP(s_len, 8);
  1269. scan->length = s_len;
  1270. scan->buffer = tdo_buffer;
  1271. scan->buffer_offset = tdo_buffer_offset;
  1272. }
  1273. }
  1274. /* queue a sequence of bits to clock out TMS, executing if the buffer is full */
  1275. static void cmsis_dap_add_tms_sequence(const uint8_t *sequence, int s_len)
  1276. {
  1277. LOG_DEBUG_IO("%d bits: %02X", s_len, *sequence);
  1278. /* we use a series of CMD_DAP_JTAG_SEQ commands to toggle TMS,
  1279. because even though it seems ridiculously inefficient, it
  1280. allows us to combine TMS and scan sequences into the same
  1281. USB packet. */
  1282. /* TODO: combine runs of the same tms value */
  1283. for (int i = 0; i < s_len; ++i) {
  1284. bool bit = (sequence[i / 8] & (1 << (i % 8))) != 0;
  1285. cmsis_dap_add_jtag_sequence(1, NULL, 0, bit, NULL, 0);
  1286. }
  1287. }
  1288. /* Move to the end state by queuing a sequence to clock into TMS */
  1289. static void cmsis_dap_state_move(void)
  1290. {
  1291. uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
  1292. uint8_t tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
  1293. LOG_DEBUG_IO("state move from %s to %s: %d clocks, %02X on tms",
  1294. tap_state_name(tap_get_state()), tap_state_name(tap_get_end_state()),
  1295. tms_scan_bits, tms_scan);
  1296. cmsis_dap_add_tms_sequence(&tms_scan, tms_scan_bits);
  1297. tap_set_state(tap_get_end_state());
  1298. }
  1299. /* Execute a JTAG scan operation by queueing TMS and TDI/TDO sequences */
  1300. static void cmsis_dap_execute_scan(struct jtag_command *cmd)
  1301. {
  1302. LOG_DEBUG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
  1303. jtag_scan_type(cmd->cmd.scan));
  1304. /* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
  1305. while (cmd->cmd.scan->num_fields > 0
  1306. && cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
  1307. cmd->cmd.scan->num_fields--;
  1308. LOG_DEBUG("discarding trailing empty field");
  1309. }
  1310. if (cmd->cmd.scan->num_fields == 0) {
  1311. LOG_DEBUG("empty scan, doing nothing");
  1312. return;
  1313. }
  1314. if (cmd->cmd.scan->ir_scan) {
  1315. if (tap_get_state() != TAP_IRSHIFT) {
  1316. cmsis_dap_end_state(TAP_IRSHIFT);
  1317. cmsis_dap_state_move();
  1318. }
  1319. } else {
  1320. if (tap_get_state() != TAP_DRSHIFT) {
  1321. cmsis_dap_end_state(TAP_DRSHIFT);
  1322. cmsis_dap_state_move();
  1323. }
  1324. }
  1325. cmsis_dap_end_state(cmd->cmd.scan->end_state);
  1326. struct scan_field *field = cmd->cmd.scan->fields;
  1327. unsigned scan_size = 0;
  1328. for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
  1329. scan_size += field->num_bits;
  1330. LOG_DEBUG_IO("%s%s field %d/%d %d bits",
  1331. field->in_value ? "in" : "",
  1332. field->out_value ? "out" : "",
  1333. i,
  1334. cmd->cmd.scan->num_fields,
  1335. field->num_bits);
  1336. if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
  1337. LOG_DEBUG_IO("Last field and have to move out of SHIFT state");
  1338. /* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
  1339. * movement. This last field can't have length zero, it was checked above. */
  1340. cmsis_dap_add_jtag_sequence(
  1341. field->num_bits - 1, /* number of bits to clock */
  1342. field->out_value, /* output sequence */
  1343. 0, /* output offset */
  1344. false, /* TMS low */
  1345. field->in_value,
  1346. 0);
  1347. /* Clock the last bit out, with TMS high */
  1348. uint8_t last_bit = 0;
  1349. if (field->out_value)
  1350. bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
  1351. cmsis_dap_add_jtag_sequence(
  1352. 1,
  1353. &last_bit,
  1354. 0,
  1355. true,
  1356. field->in_value,
  1357. field->num_bits - 1);
  1358. tap_set_state(tap_state_transition(tap_get_state(), 1));
  1359. /* Now clock one more cycle, with TMS low, to get us into a PAUSE state */
  1360. cmsis_dap_add_jtag_sequence(
  1361. 1,
  1362. &last_bit,
  1363. 0,
  1364. false,
  1365. NULL,
  1366. 0);
  1367. tap_set_state(tap_state_transition(tap_get_state(), 0));
  1368. } else {
  1369. LOG_DEBUG_IO("Internal field, staying in SHIFT state afterwards");
  1370. /* Clocking part of a sequence into DR or IR with TMS=0,
  1371. leaving TMS=0 at the end so we can continue later */
  1372. cmsis_dap_add_jtag_sequence(
  1373. field->num_bits,
  1374. field->out_value,
  1375. 0,
  1376. false,
  1377. field->in_value,
  1378. 0);
  1379. }
  1380. }
  1381. if (tap_get_state() != tap_get_end_state()) {
  1382. cmsis_dap_end_state(tap_get_end_state());
  1383. cmsis_dap_state_move();
  1384. }
  1385. LOG_DEBUG_IO("%s scan, %i bits, end in %s",
  1386. (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
  1387. tap_state_name(tap_get_end_state()));
  1388. }
  1389. static void cmsis_dap_pathmove(int num_states, tap_state_t *path)
  1390. {
  1391. uint8_t tms0 = 0x00;
  1392. uint8_t tms1 = 0xff;
  1393. for (int i = 0; i < num_states; i++) {
  1394. if (path[i] == tap_state_transition(tap_get_state(), false))
  1395. cmsis_dap_add_tms_sequence(&tms0, 1);
  1396. else if (path[i] == tap_state_transition(tap_get_state(), true))
  1397. cmsis_dap_add_tms_sequence(&tms1, 1);
  1398. else {
  1399. LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
  1400. tap_state_name(tap_get_state()), tap_state_name(path[i]));
  1401. exit(-1);
  1402. }
  1403. tap_set_state(path[i]);
  1404. }
  1405. cmsis_dap_end_state(tap_get_state());
  1406. }
  1407. static void cmsis_dap_execute_pathmove(struct jtag_command *cmd)
  1408. {
  1409. LOG_DEBUG_IO("pathmove: %i states, end in %i",
  1410. cmd->cmd.pathmove->num_states,
  1411. cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
  1412. cmsis_dap_pathmove(cmd->cmd.pathmove->num_states, cmd->cmd.pathmove->path);
  1413. }
  1414. static void cmsis_dap_stableclocks(int num_cycles)
  1415. {
  1416. uint8_t tms = tap_get_state() == TAP_RESET;
  1417. /* TODO: Perform optimizations? */
  1418. /* Execute num_cycles. */
  1419. for (int i = 0; i < num_cycles; i++)
  1420. cmsis_dap_add_tms_sequence(&tms, 1);
  1421. }
  1422. static void cmsis_dap_runtest(int num_cycles)
  1423. {
  1424. tap_state_t saved_end_state = tap_get_end_state();
  1425. /* Only do a state_move when we're not already in IDLE. */
  1426. if (tap_get_state() != TAP_IDLE) {
  1427. cmsis_dap_end_state(TAP_IDLE);
  1428. cmsis_dap_state_move();
  1429. }
  1430. cmsis_dap_stableclocks(num_cycles);
  1431. /* Finish in end_state. */
  1432. cmsis_dap_end_state(saved_end_state);
  1433. if (tap_get_state() != tap_get_end_state())
  1434. cmsis_dap_state_move();
  1435. }
  1436. static void cmsis_dap_execute_runtest(struct jtag_command *cmd)
  1437. {
  1438. LOG_DEBUG_IO("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles,
  1439. cmd->cmd.runtest->end_state);
  1440. cmsis_dap_end_state(cmd->cmd.runtest->end_state);
  1441. cmsis_dap_runtest(cmd->cmd.runtest->num_cycles);
  1442. }
  1443. static void cmsis_dap_execute_stableclocks(struct jtag_command *cmd)
  1444. {
  1445. LOG_DEBUG_IO("stableclocks %i cycles", cmd->cmd.runtest->num_cycles);
  1446. cmsis_dap_stableclocks(cmd->cmd.runtest->num_cycles);
  1447. }
  1448. static void cmsis_dap_execute_tms(struct jtag_command *cmd)
  1449. {
  1450. LOG_DEBUG_IO("TMS: %d bits", cmd->cmd.tms->num_bits);
  1451. cmsis_dap_cmd_dap_swj_sequence(cmd->cmd.tms->num_bits, cmd->cmd.tms->bits);
  1452. }
  1453. /* TODO: Is there need to call cmsis_dap_flush() for the JTAG_PATHMOVE,
  1454. * JTAG_RUNTEST, JTAG_STABLECLOCKS? */
  1455. static void cmsis_dap_execute_command(struct jtag_command *cmd)
  1456. {
  1457. switch (cmd->type) {
  1458. case JTAG_SLEEP:
  1459. cmsis_dap_flush();
  1460. cmsis_dap_execute_sleep(cmd);
  1461. break;
  1462. case JTAG_TLR_RESET:
  1463. cmsis_dap_flush();
  1464. cmsis_dap_execute_tlr_reset(cmd);
  1465. break;
  1466. case JTAG_SCAN:
  1467. cmsis_dap_execute_scan(cmd);
  1468. break;
  1469. case JTAG_PATHMOVE:
  1470. cmsis_dap_execute_pathmove(cmd);
  1471. break;
  1472. case JTAG_RUNTEST:
  1473. cmsis_dap_execute_runtest(cmd);
  1474. break;
  1475. case JTAG_STABLECLOCKS:
  1476. cmsis_dap_execute_stableclocks(cmd);
  1477. break;
  1478. case JTAG_TMS:
  1479. cmsis_dap_execute_tms(cmd);
  1480. break;
  1481. default:
  1482. LOG_ERROR("BUG: unknown JTAG command type 0x%X encountered", cmd->type);
  1483. exit(-1);
  1484. }
  1485. }
  1486. static int cmsis_dap_execute_queue(void)
  1487. {
  1488. struct jtag_command *cmd = jtag_command_queue;
  1489. while (cmd) {
  1490. cmsis_dap_execute_command(cmd);
  1491. cmd = cmd->next;
  1492. }
  1493. cmsis_dap_flush();
  1494. return ERROR_OK;
  1495. }
  1496. static int cmsis_dap_speed(int speed)
  1497. {
  1498. if (speed == 0) {
  1499. LOG_ERROR("RTCK not supported. Set nonzero \"adapter speed\".");
  1500. return ERROR_JTAG_NOT_IMPLEMENTED;
  1501. }
  1502. return cmsis_dap_cmd_dap_swj_clock(speed);
  1503. }
  1504. static int cmsis_dap_speed_div(int speed, int *khz)
  1505. {
  1506. *khz = speed;
  1507. return ERROR_OK;
  1508. }
  1509. static int cmsis_dap_khz(int khz, int *jtag_speed)
  1510. {
  1511. *jtag_speed = khz;
  1512. return ERROR_OK;
  1513. }
  1514. static bool calculate_swo_prescaler(unsigned int traceclkin_freq,
  1515. uint32_t trace_freq, uint16_t *prescaler)
  1516. {
  1517. unsigned int presc = (traceclkin_freq + trace_freq / 2) / trace_freq;
  1518. if (presc == 0 || presc > TPIU_ACPR_MAX_SWOSCALER + 1)
  1519. return false;
  1520. /* Probe's UART speed must be within 3% of the TPIU's SWO baud rate. */
  1521. unsigned int max_deviation = (traceclkin_freq * 3) / 100;
  1522. if (presc * trace_freq < traceclkin_freq - max_deviation ||
  1523. presc * trace_freq > traceclkin_freq + max_deviation)
  1524. return false;
  1525. *prescaler = presc;
  1526. return true;
  1527. }
  1528. /**
  1529. * @see adapter_driver::config_trace
  1530. */
  1531. static int cmsis_dap_config_trace(
  1532. bool trace_enabled,
  1533. enum tpiu_pin_protocol pin_protocol,
  1534. uint32_t port_size,
  1535. unsigned int *swo_freq,
  1536. unsigned int traceclkin_hz,
  1537. uint16_t *swo_prescaler)
  1538. {
  1539. int retval;
  1540. if (!trace_enabled) {
  1541. if (cmsis_dap_handle->trace_enabled) {
  1542. retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_STOP);
  1543. if (retval != ERROR_OK) {
  1544. LOG_ERROR("Failed to disable the SWO-trace.");
  1545. return retval;
  1546. }
  1547. }
  1548. cmsis_dap_handle->trace_enabled = false;
  1549. LOG_INFO("SWO-trace disabled.");
  1550. return ERROR_OK;
  1551. }
  1552. if (!(cmsis_dap_handle->caps & INFO_CAPS_SWO_UART) &&
  1553. !(cmsis_dap_handle->caps & INFO_CAPS_SWO_MANCHESTER)) {
  1554. LOG_ERROR("SWO-trace is not supported by the device.");
  1555. return ERROR_FAIL;
  1556. }
  1557. uint8_t swo_mode;
  1558. if (pin_protocol == TPIU_PIN_PROTOCOL_ASYNC_UART &&
  1559. (cmsis_dap_handle->caps & INFO_CAPS_SWO_UART)) {
  1560. swo_mode = DAP_SWO_MODE_UART;
  1561. } else if (pin_protocol == TPIU_PIN_PROTOCOL_ASYNC_MANCHESTER &&
  1562. (cmsis_dap_handle->caps & INFO_CAPS_SWO_MANCHESTER)) {
  1563. swo_mode = DAP_SWO_MODE_MANCHESTER;
  1564. } else {
  1565. LOG_ERROR("Selected pin protocol is not supported.");
  1566. return ERROR_FAIL;
  1567. }
  1568. if (*swo_freq == 0) {
  1569. LOG_INFO("SWO-trace frequency autodetection not implemented.");
  1570. return ERROR_FAIL;
  1571. }
  1572. retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_STOP);
  1573. if (retval != ERROR_OK)
  1574. return retval;
  1575. cmsis_dap_handle->trace_enabled = false;
  1576. retval = cmsis_dap_get_swo_buf_sz(&cmsis_dap_handle->swo_buf_sz);
  1577. if (retval != ERROR_OK)
  1578. return retval;
  1579. retval = cmsis_dap_cmd_dap_swo_transport(DAP_SWO_TRANSPORT_DATA);
  1580. if (retval != ERROR_OK)
  1581. return retval;
  1582. retval = cmsis_dap_cmd_dap_swo_mode(swo_mode);
  1583. if (retval != ERROR_OK)
  1584. return retval;
  1585. retval = cmsis_dap_cmd_dap_swo_baudrate(*swo_freq, swo_freq);
  1586. if (retval != ERROR_OK)
  1587. return retval;
  1588. if (!calculate_swo_prescaler(traceclkin_hz, *swo_freq,
  1589. swo_prescaler)) {
  1590. LOG_ERROR("SWO frequency is not suitable. Please choose a "
  1591. "different frequency or use auto-detection.");
  1592. return ERROR_FAIL;
  1593. }
  1594. LOG_INFO("SWO frequency: %u Hz.", *swo_freq);
  1595. LOG_INFO("SWO prescaler: %u.", *swo_prescaler);
  1596. retval = cmsis_dap_cmd_dap_swo_control(DAP_SWO_CONTROL_START);
  1597. if (retval != ERROR_OK)
  1598. return retval;
  1599. cmsis_dap_handle->trace_enabled = true;
  1600. return ERROR_OK;
  1601. }
  1602. /**
  1603. * @see adapter_driver::poll_trace
  1604. */
  1605. static int cmsis_dap_poll_trace(uint8_t *buf, size_t *size)
  1606. {
  1607. uint8_t trace_status;
  1608. size_t trace_count;
  1609. if (!cmsis_dap_handle->trace_enabled) {
  1610. *size = 0;
  1611. return ERROR_OK;
  1612. }
  1613. int retval = cmsis_dap_cmd_dap_swo_status(&trace_status, &trace_count);
  1614. if (retval != ERROR_OK)
  1615. return retval;
  1616. if ((trace_status & DAP_SWO_STATUS_CAPTURE_MASK) != DAP_SWO_STATUS_CAPTURE_ACTIVE)
  1617. return ERROR_FAIL;
  1618. *size = trace_count < *size ? trace_count : *size;
  1619. size_t read_so_far = 0;
  1620. do {
  1621. size_t rb = 0;
  1622. uint32_t packet_size = cmsis_dap_handle->packet_size - 4 /*data-reply*/;
  1623. uint32_t remaining = *size - read_so_far;
  1624. if (remaining < packet_size)
  1625. packet_size = remaining;
  1626. retval = cmsis_dap_cmd_dap_swo_data(
  1627. packet_size,
  1628. &trace_status,
  1629. &rb,
  1630. &buf[read_so_far]);
  1631. if (retval != ERROR_OK)
  1632. return retval;
  1633. if ((trace_status & DAP_SWO_STATUS_CAPTURE_MASK) != DAP_SWO_STATUS_CAPTURE_ACTIVE)
  1634. return ERROR_FAIL;
  1635. read_so_far += rb;
  1636. } while (read_so_far < *size);
  1637. return ERROR_OK;
  1638. }
  1639. COMMAND_HANDLER(cmsis_dap_handle_info_command)
  1640. {
  1641. if (cmsis_dap_get_version_info() == ERROR_OK)
  1642. cmsis_dap_get_status();
  1643. return ERROR_OK;
  1644. }
  1645. COMMAND_HANDLER(cmsis_dap_handle_cmd_command)
  1646. {
  1647. uint8_t *command = cmsis_dap_handle->command;
  1648. for (unsigned i = 0; i < CMD_ARGC; i++)
  1649. command[i] = strtoul(CMD_ARGV[i], NULL, 16);
  1650. int retval = cmsis_dap_xfer(cmsis_dap_handle, CMD_ARGC);
  1651. if (retval != ERROR_OK) {
  1652. LOG_ERROR("CMSIS-DAP command failed.");
  1653. return ERROR_JTAG_DEVICE_ERROR;
  1654. }
  1655. uint8_t *resp = cmsis_dap_handle->response;
  1656. LOG_INFO("Returned data %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8,
  1657. resp[1], resp[2], resp[3], resp[4]);
  1658. return ERROR_OK;
  1659. }
  1660. COMMAND_HANDLER(cmsis_dap_handle_vid_pid_command)
  1661. {
  1662. if (CMD_ARGC > MAX_USB_IDS * 2) {
  1663. LOG_WARNING("ignoring extra IDs in cmsis_dap_vid_pid "
  1664. "(maximum is %d pairs)", MAX_USB_IDS);
  1665. CMD_ARGC = MAX_USB_IDS * 2;
  1666. }
  1667. if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
  1668. LOG_WARNING("incomplete cmsis_dap_vid_pid configuration directive");
  1669. if (CMD_ARGC < 2)
  1670. return ERROR_COMMAND_SYNTAX_ERROR;
  1671. /* remove the incomplete trailing id */
  1672. CMD_ARGC -= 1;
  1673. }
  1674. unsigned i;
  1675. for (i = 0; i < CMD_ARGC; i += 2) {
  1676. COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], cmsis_dap_vid[i >> 1]);
  1677. COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], cmsis_dap_pid[i >> 1]);
  1678. }
  1679. /*
  1680. * Explicitly terminate, in case there are multiples instances of
  1681. * cmsis_dap_vid_pid.
  1682. */
  1683. cmsis_dap_vid[i >> 1] = cmsis_dap_pid[i >> 1] = 0;
  1684. return ERROR_OK;
  1685. }
  1686. COMMAND_HANDLER(cmsis_dap_handle_serial_command)
  1687. {
  1688. if (CMD_ARGC == 1)
  1689. cmsis_dap_serial = strdup(CMD_ARGV[0]);
  1690. else
  1691. LOG_ERROR("expected exactly one argument to cmsis_dap_serial <serial-number>");
  1692. return ERROR_OK;
  1693. }
  1694. COMMAND_HANDLER(cmsis_dap_handle_backend_command)
  1695. {
  1696. if (CMD_ARGC == 1) {
  1697. if (strcmp(CMD_ARGV[0], "auto") == 0) {
  1698. cmsis_dap_backend = -1; /* autoselect */
  1699. } else {
  1700. for (unsigned int i = 0; i < ARRAY_SIZE(cmsis_dap_backends); i++) {
  1701. if (strcasecmp(cmsis_dap_backends[i]->name, CMD_ARGV[0]) == 0) {
  1702. cmsis_dap_backend = i;
  1703. return ERROR_OK;
  1704. }
  1705. }
  1706. LOG_ERROR("invalid backend argument to cmsis_dap_backend <backend>");
  1707. }
  1708. } else {
  1709. LOG_ERROR("expected exactly one argument to cmsis_dap_backend <backend>");
  1710. }
  1711. return ERROR_OK;
  1712. }
  1713. static const struct command_registration cmsis_dap_subcommand_handlers[] = {
  1714. {
  1715. .name = "info",
  1716. .handler = &cmsis_dap_handle_info_command,
  1717. .mode = COMMAND_EXEC,
  1718. .usage = "",
  1719. .help = "show cmsis-dap info",
  1720. },
  1721. {
  1722. .name = "cmd",
  1723. .handler = &cmsis_dap_handle_cmd_command,
  1724. .mode = COMMAND_EXEC,
  1725. .usage = "",
  1726. .help = "issue cmsis-dap command",
  1727. },
  1728. COMMAND_REGISTRATION_DONE
  1729. };
  1730. static const struct command_registration cmsis_dap_command_handlers[] = {
  1731. {
  1732. .name = "cmsis-dap",
  1733. .mode = COMMAND_ANY,
  1734. .help = "perform CMSIS-DAP management",
  1735. .usage = "<cmd>",
  1736. .chain = cmsis_dap_subcommand_handlers,
  1737. },
  1738. {
  1739. .name = "cmsis_dap_vid_pid",
  1740. .handler = &cmsis_dap_handle_vid_pid_command,
  1741. .mode = COMMAND_CONFIG,
  1742. .help = "the vendor ID and product ID of the CMSIS-DAP device",
  1743. .usage = "(vid pid)*",
  1744. },
  1745. {
  1746. .name = "cmsis_dap_serial",
  1747. .handler = &cmsis_dap_handle_serial_command,
  1748. .mode = COMMAND_CONFIG,
  1749. .help = "set the serial number of the adapter",
  1750. .usage = "serial_string",
  1751. },
  1752. {
  1753. .name = "cmsis_dap_backend",
  1754. .handler = &cmsis_dap_handle_backend_command,
  1755. .mode = COMMAND_CONFIG,
  1756. .help = "set the communication backend to use (USB bulk or HID).",
  1757. .usage = "(auto | usb_bulk | hid)",
  1758. },
  1759. #if BUILD_CMSIS_DAP_USB
  1760. {
  1761. .name = "cmsis_dap_usb",
  1762. .chain = cmsis_dap_usb_subcommand_handlers,
  1763. .mode = COMMAND_ANY,
  1764. .help = "USB bulk backend-specific commands",
  1765. .usage = "<cmd>",
  1766. },
  1767. #endif
  1768. COMMAND_REGISTRATION_DONE
  1769. };
  1770. static const struct swd_driver cmsis_dap_swd_driver = {
  1771. .init = cmsis_dap_swd_init,
  1772. .switch_seq = cmsis_dap_swd_switch_seq,
  1773. .read_reg = cmsis_dap_swd_read_reg,
  1774. .write_reg = cmsis_dap_swd_write_reg,
  1775. .run = cmsis_dap_swd_run_queue,
  1776. };
  1777. static const char * const cmsis_dap_transport[] = { "swd", "jtag", NULL };
  1778. static struct jtag_interface cmsis_dap_interface = {
  1779. .supported = DEBUG_CAP_TMS_SEQ,
  1780. .execute_queue = cmsis_dap_execute_queue,
  1781. };
  1782. struct adapter_driver cmsis_dap_adapter_driver = {
  1783. .name = "cmsis-dap",
  1784. .transports = cmsis_dap_transport,
  1785. .commands = cmsis_dap_command_handlers,
  1786. .init = cmsis_dap_init,
  1787. .quit = cmsis_dap_quit,
  1788. .reset = cmsis_dap_reset,
  1789. .speed = cmsis_dap_speed,
  1790. .khz = cmsis_dap_khz,
  1791. .speed_div = cmsis_dap_speed_div,
  1792. .config_trace = cmsis_dap_config_trace,
  1793. .poll_trace = cmsis_dap_poll_trace,
  1794. .jtag_ops = &cmsis_dap_interface,
  1795. .swd_ops = &cmsis_dap_swd_driver,
  1796. };