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