stlink: fix open AP for v2j37 and v3j7
[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 <jtag/swim.h>
40 #include <target/target.h>
41 #include <transport/transport.h>
42
43 #include <target/cortex_m.h>
44
45 #include "libusb_helper.h"
46
47 #ifdef HAVE_LIBUSB1
48 #define USE_LIBUSB_ASYNCIO
49 #endif
50
51 #define STLINK_SERIAL_LEN 24
52
53 #define ENDPOINT_IN  0x80
54 #define ENDPOINT_OUT 0x00
55
56 #define STLINK_WRITE_TIMEOUT 1000
57 #define STLINK_READ_TIMEOUT 1000
58
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 enum stlink_mode {
100         STLINK_MODE_UNKNOWN = 0,
101         STLINK_MODE_DFU,
102         STLINK_MODE_MASS,
103         STLINK_MODE_DEBUG_JTAG,
104         STLINK_MODE_DEBUG_SWD,
105         STLINK_MODE_DEBUG_SWIM
106 };
107
108 /** */
109 struct stlink_usb_version {
110         /** */
111         int stlink;
112         /** */
113         int jtag;
114         /** */
115         int swim;
116         /** jtag api version supported */
117         enum stlink_jtag_api_version jtag_api;
118         /** one bit for each feature supported. See macros STLINK_F_* */
119         uint32_t flags;
120 };
121
122 /** */
123 struct stlink_usb_handle_s {
124         /** */
125         struct libusb_device_handle *fd;
126         /** */
127         struct libusb_transfer *trans;
128         /** */
129         uint8_t rx_ep;
130         /** */
131         uint8_t tx_ep;
132         /** */
133         uint8_t trace_ep;
134         /** */
135         uint8_t cmdbuf[STLINK_SG_SIZE];
136         /** */
137         uint8_t cmdidx;
138         /** */
139         uint8_t direction;
140         /** */
141         uint8_t databuf[STLINK_DATA_SIZE];
142         /** */
143         uint32_t max_mem_packet;
144         /** */
145         enum stlink_mode st_mode;
146         /** */
147         struct stlink_usb_version version;
148         /** */
149         uint16_t vid;
150         /** */
151         uint16_t pid;
152         /** */
153         struct {
154                 /** whether SWO tracing is enabled or not */
155                 bool enabled;
156                 /** trace module source clock */
157                 uint32_t source_hz;
158         } trace;
159         /** reconnect is needed next time we try to query the
160          * status */
161         bool reconnect_pending;
162 };
163
164 #define STLINK_SWIM_ERR_OK             0x00
165 #define STLINK_SWIM_BUSY               0x01
166 #define STLINK_DEBUG_ERR_OK            0x80
167 #define STLINK_DEBUG_ERR_FAULT         0x81
168 #define STLINK_SWD_AP_WAIT             0x10
169 #define STLINK_SWD_AP_FAULT            0x11
170 #define STLINK_SWD_AP_ERROR            0x12
171 #define STLINK_SWD_AP_PARITY_ERROR     0x13
172 #define STLINK_JTAG_GET_IDCODE_ERROR   0x09
173 #define STLINK_JTAG_WRITE_ERROR        0x0c
174 #define STLINK_JTAG_WRITE_VERIF_ERROR  0x0d
175 #define STLINK_SWD_DP_WAIT             0x14
176 #define STLINK_SWD_DP_FAULT            0x15
177 #define STLINK_SWD_DP_ERROR            0x16
178 #define STLINK_SWD_DP_PARITY_ERROR     0x17
179
180 #define STLINK_SWD_AP_WDATA_ERROR      0x18
181 #define STLINK_SWD_AP_STICKY_ERROR     0x19
182 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
183
184 #define STLINK_BAD_AP_ERROR            0x1d
185
186 #define STLINK_CORE_RUNNING            0x80
187 #define STLINK_CORE_HALTED             0x81
188 #define STLINK_CORE_STAT_UNKNOWN       -1
189
190 #define STLINK_GET_VERSION             0xF1
191 #define STLINK_DEBUG_COMMAND           0xF2
192 #define STLINK_DFU_COMMAND             0xF3
193 #define STLINK_SWIM_COMMAND            0xF4
194 #define STLINK_GET_CURRENT_MODE        0xF5
195 #define STLINK_GET_TARGET_VOLTAGE      0xF7
196
197 #define STLINK_DEV_DFU_MODE            0x00
198 #define STLINK_DEV_MASS_MODE           0x01
199 #define STLINK_DEV_DEBUG_MODE          0x02
200 #define STLINK_DEV_SWIM_MODE           0x03
201 #define STLINK_DEV_BOOTLOADER_MODE     0x04
202 #define STLINK_DEV_UNKNOWN_MODE        -1
203
204 #define STLINK_DFU_EXIT                0x07
205
206 /*
207         STLINK_SWIM_ENTER_SEQ
208         1.3ms low then 750Hz then 1.5kHz
209
210         STLINK_SWIM_GEN_RST
211         STM8 DM pulls reset pin low 50us
212
213         STLINK_SWIM_SPEED
214         uint8_t (0=low|1=high)
215
216         STLINK_SWIM_WRITEMEM
217         uint16_t length
218         uint32_t address
219
220         STLINK_SWIM_RESET
221         send syncronization seq (16us low, response 64 clocks low)
222 */
223 #define STLINK_SWIM_ENTER                  0x00
224 #define STLINK_SWIM_EXIT                   0x01
225 #define STLINK_SWIM_READ_CAP               0x02
226 #define STLINK_SWIM_SPEED                  0x03
227 #define STLINK_SWIM_ENTER_SEQ              0x04
228 #define STLINK_SWIM_GEN_RST                0x05
229 #define STLINK_SWIM_RESET                  0x06
230 #define STLINK_SWIM_ASSERT_RESET           0x07
231 #define STLINK_SWIM_DEASSERT_RESET         0x08
232 #define STLINK_SWIM_READSTATUS             0x09
233 #define STLINK_SWIM_WRITEMEM               0x0a
234 #define STLINK_SWIM_READMEM                0x0b
235 #define STLINK_SWIM_READBUF                0x0c
236
237 #define STLINK_DEBUG_GETSTATUS             0x01
238 #define STLINK_DEBUG_FORCEDEBUG            0x02
239 #define STLINK_DEBUG_APIV1_RESETSYS        0x03
240 #define STLINK_DEBUG_APIV1_READALLREGS     0x04
241 #define STLINK_DEBUG_APIV1_READREG         0x05
242 #define STLINK_DEBUG_APIV1_WRITEREG        0x06
243 #define STLINK_DEBUG_READMEM_32BIT         0x07
244 #define STLINK_DEBUG_WRITEMEM_32BIT        0x08
245 #define STLINK_DEBUG_RUNCORE               0x09
246 #define STLINK_DEBUG_STEPCORE              0x0a
247 #define STLINK_DEBUG_APIV1_SETFP           0x0b
248 #define STLINK_DEBUG_READMEM_8BIT          0x0c
249 #define STLINK_DEBUG_WRITEMEM_8BIT         0x0d
250 #define STLINK_DEBUG_APIV1_CLEARFP         0x0e
251 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG   0x0f
252 #define STLINK_DEBUG_APIV1_SETWATCHPOINT   0x10
253
254 #define STLINK_DEBUG_ENTER_JTAG_RESET      0x00
255 #define STLINK_DEBUG_ENTER_SWD_NO_RESET    0xa3
256 #define STLINK_DEBUG_ENTER_JTAG_NO_RESET   0xa4
257
258 #define STLINK_DEBUG_APIV1_ENTER           0x20
259 #define STLINK_DEBUG_EXIT                  0x21
260 #define STLINK_DEBUG_READCOREID            0x22
261
262 #define STLINK_DEBUG_APIV2_ENTER           0x30
263 #define STLINK_DEBUG_APIV2_READ_IDCODES    0x31
264 #define STLINK_DEBUG_APIV2_RESETSYS        0x32
265 #define STLINK_DEBUG_APIV2_READREG         0x33
266 #define STLINK_DEBUG_APIV2_WRITEREG        0x34
267 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG   0x35
268 #define STLINK_DEBUG_APIV2_READDEBUGREG    0x36
269
270 #define STLINK_DEBUG_APIV2_READALLREGS     0x3A
271 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
272 #define STLINK_DEBUG_APIV2_DRIVE_NRST      0x3C
273
274 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS2 0x3E
275
276 #define STLINK_DEBUG_APIV2_START_TRACE_RX  0x40
277 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX   0x41
278 #define STLINK_DEBUG_APIV2_GET_TRACE_NB    0x42
279 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ    0x43
280 #define STLINK_DEBUG_APIV2_JTAG_SET_FREQ   0x44
281 #define STLINK_DEBUG_APIV2_READ_DAP_REG    0x45
282 #define STLINK_DEBUG_APIV2_WRITE_DAP_REG   0x46
283 #define STLINK_DEBUG_APIV2_READMEM_16BIT   0x47
284 #define STLINK_DEBUG_APIV2_WRITEMEM_16BIT  0x48
285
286 #define STLINK_DEBUG_APIV2_INIT_AP         0x4B
287 #define STLINK_DEBUG_APIV2_CLOSE_AP_DBG    0x4C
288
289 #define STLINK_APIV3_SET_COM_FREQ           0x61
290 #define STLINK_APIV3_GET_COM_FREQ           0x62
291
292 #define STLINK_APIV3_GET_VERSION_EX         0xFB
293
294 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW   0x00
295 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH  0x01
296 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
297
298 #define STLINK_DEBUG_PORT_ACCESS            0xffff
299
300 #define STLINK_TRACE_SIZE               4096
301 #define STLINK_TRACE_MAX_HZ             2000000
302
303 #define STLINK_V3_MAX_FREQ_NB               10
304
305 #define REQUEST_SENSE        0x03
306 #define REQUEST_SENSE_LENGTH 18
307
308 /*
309  * Map the relevant features, quirks and workaround for specific firmware
310  * version of stlink
311  */
312 #define STLINK_F_HAS_TRACE              BIT(0)
313 #define STLINK_F_HAS_SWD_SET_FREQ       BIT(1)
314 #define STLINK_F_HAS_JTAG_SET_FREQ      BIT(2)
315 #define STLINK_F_HAS_MEM_16BIT          BIT(3)
316 #define STLINK_F_HAS_GETLASTRWSTATUS2   BIT(4)
317 #define STLINK_F_HAS_DAP_REG            BIT(5)
318 #define STLINK_F_QUIRK_JTAG_DP_READ     BIT(6)
319 #define STLINK_F_HAS_AP_INIT            BIT(7)
320 #define STLINK_F_HAS_DPBANKSEL          BIT(8)
321 #define STLINK_F_HAS_RW8_512BYTES       BIT(9)
322 #define STLINK_F_FIX_CLOSE_AP           BIT(10)
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         {9000,  4},
351         {4500,  8},
352         {2250, 16},
353         {1125, 32}, /* default */
354         {562,  64},
355         {281, 128},
356         {140, 256}
357 };
358
359 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
360 static int stlink_swim_status(void *handle);
361 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size);
362 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map);
363 static int stlink_speed(void *handle, int khz, bool query);
364 static int stlink_usb_open_ap(void *handle, unsigned short apsel);
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->st_mode == STLINK_MODE_DEBUG_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->st_mode != STLINK_MODE_DEBUG_SWIM) || !retries) {
825                         res = stlink_usb_xfer_noerrcheck(handle, buf, size);
826                         if (res != ERROR_OK)
827                                 return res;
828                 }
829
830                 if (h->st_mode == STLINK_MODE_DEBUG_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                         unsigned int 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                 /* API required to return proper error code on close AP from J29 */
1036                 if (h->version.jtag >= 29)
1037                         flags |= STLINK_F_FIX_CLOSE_AP;
1038
1039                 /* Banked regs (DPv1 & DPv2) support from V2J32 */
1040                 if (h->version.jtag >= 32)
1041                         flags |= STLINK_F_HAS_DPBANKSEL;
1042
1043                 break;
1044         case 3:
1045                 /* all STLINK-V3 use api-v3 */
1046                 h->version.jtag_api = STLINK_JTAG_API_V3;
1047
1048                 /* STLINK-V3 is a superset of ST-LINK/V2 */
1049
1050                 /* API for trace */
1051                 /* API for target voltage */
1052                 flags |= STLINK_F_HAS_TRACE;
1053
1054                 /* preferred API to get last R/W status */
1055                 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1056
1057                 /* API to access DAP registers */
1058                 flags |= STLINK_F_HAS_DAP_REG;
1059
1060                 /* API to read/write memory at 16 bit */
1061                 flags |= STLINK_F_HAS_MEM_16BIT;
1062
1063                 /* API required to init AP before any AP access */
1064                 flags |= STLINK_F_HAS_AP_INIT;
1065
1066                 /* API required to return proper error code on close AP */
1067                 flags |= STLINK_F_FIX_CLOSE_AP;
1068
1069                 /* Banked regs (DPv1 & DPv2) support from V3J2 */
1070                 if (h->version.jtag >= 2)
1071                         flags |= STLINK_F_HAS_DPBANKSEL;
1072
1073                 /* 8bit read/write max packet size 512 bytes from V3J6 */
1074                 if (h->version.jtag >= 6)
1075                         flags |= STLINK_F_HAS_RW8_512BYTES;
1076
1077                 break;
1078         default:
1079                 break;
1080         }
1081         h->version.flags = flags;
1082
1083         p = v_str;
1084         p += sprintf(p, "V%d", v);
1085         if (jtag || !msd)
1086                 p += sprintf(p, "J%d", jtag);
1087         if (msd)
1088                 p += sprintf(p, "M%d", msd);
1089         if (bridge)
1090                 p += sprintf(p, "B%d", bridge);
1091         if (swim || !msd)
1092                 sprintf(p, "S%d", swim);
1093
1094         LOG_INFO("STLINK %s (API v%d) VID:PID %04X:%04X",
1095                 v_str,
1096                 h->version.jtag_api,
1097                 h->vid,
1098                 h->pid);
1099
1100         return ERROR_OK;
1101 }
1102
1103 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
1104 {
1105         struct stlink_usb_handle_s *h = handle;
1106         uint32_t adc_results[2];
1107
1108         /* no error message, simply quit with error */
1109         if (!(h->version.flags & STLINK_F_HAS_TARGET_VOLT))
1110                 return ERROR_COMMAND_NOTFOUND;
1111
1112         stlink_usb_init_buffer(handle, h->rx_ep, 8);
1113
1114         h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
1115
1116         int result = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1117
1118         if (result != ERROR_OK)
1119                 return result;
1120
1121         /* convert result */
1122         adc_results[0] = le_to_h_u32(h->databuf);
1123         adc_results[1] = le_to_h_u32(h->databuf + 4);
1124
1125         *target_voltage = 0;
1126
1127         if (adc_results[0])
1128                 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
1129
1130         LOG_INFO("Target voltage: %f", (double)*target_voltage);
1131
1132         return ERROR_OK;
1133 }
1134
1135 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
1136 {
1137         struct stlink_usb_handle_s *h = handle;
1138
1139         assert(handle != NULL);
1140
1141         if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
1142                 return ERROR_COMMAND_NOTFOUND;
1143
1144         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1145
1146         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1147         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
1148         h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1149         h->cmdidx += 2;
1150
1151         int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1152
1153         if (result != ERROR_OK)
1154                 return result;
1155
1156         return ERROR_OK;
1157 }
1158
1159 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
1160 {
1161         struct stlink_usb_handle_s *h = handle;
1162
1163         assert(handle != NULL);
1164
1165         if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
1166                 return ERROR_COMMAND_NOTFOUND;
1167
1168         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1169
1170         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1171         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
1172         h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1173         h->cmdidx += 2;
1174
1175         int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1176
1177         if (result != ERROR_OK)
1178                 return result;
1179
1180         return ERROR_OK;
1181 }
1182
1183 /** */
1184 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
1185 {
1186         int res;
1187         struct stlink_usb_handle_s *h = handle;
1188
1189         assert(handle != NULL);
1190
1191         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1192
1193         h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
1194
1195         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1196
1197         if (res != ERROR_OK)
1198                 return res;
1199
1200         *mode = h->databuf[0];
1201
1202         return ERROR_OK;
1203 }
1204
1205 /** */
1206 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
1207 {
1208         int rx_size = 0;
1209         struct stlink_usb_handle_s *h = handle;
1210
1211         assert(handle != NULL);
1212
1213         /* on api V2 we are able the read the latest command
1214          * status
1215          * TODO: we need the test on api V1 too
1216          */
1217         if (h->version.jtag_api != STLINK_JTAG_API_V1)
1218                 rx_size = 2;
1219
1220         stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
1221
1222         switch (type) {
1223                 case STLINK_MODE_DEBUG_JTAG:
1224                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1225                         if (h->version.jtag_api == STLINK_JTAG_API_V1)
1226                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1227                         else
1228                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1229                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG_NO_RESET;
1230                         break;
1231                 case STLINK_MODE_DEBUG_SWD:
1232                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1233                         if (h->version.jtag_api == STLINK_JTAG_API_V1)
1234                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1235                         else
1236                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1237                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD_NO_RESET;
1238                         break;
1239                 case STLINK_MODE_DEBUG_SWIM:
1240                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1241                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
1242                         /* swim enter does not return any response or status */
1243                         return stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1244                 case STLINK_MODE_DFU:
1245                 case STLINK_MODE_MASS:
1246                 default:
1247                         return ERROR_FAIL;
1248         }
1249
1250         return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
1251 }
1252
1253 /** */
1254 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
1255 {
1256         int res;
1257         struct stlink_usb_handle_s *h = handle;
1258
1259         assert(handle != NULL);
1260
1261         /* command with no reply, use a valid endpoint but zero size */
1262         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1263
1264         switch (type) {
1265                 case STLINK_MODE_DEBUG_JTAG:
1266                 case STLINK_MODE_DEBUG_SWD:
1267                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1268                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
1269                         break;
1270                 case STLINK_MODE_DEBUG_SWIM:
1271                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1272                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
1273                         break;
1274                 case STLINK_MODE_DFU:
1275                         h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
1276                         h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
1277                         break;
1278                 case STLINK_MODE_MASS:
1279                 default:
1280                         return ERROR_FAIL;
1281         }
1282
1283         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 0);
1284
1285         if (res != ERROR_OK)
1286                 return res;
1287
1288         return ERROR_OK;
1289 }
1290
1291 static int stlink_usb_assert_srst(void *handle, int srst);
1292
1293 static enum stlink_mode stlink_get_mode(enum hl_transports t)
1294 {
1295         switch (t) {
1296         case HL_TRANSPORT_SWD:
1297                 return STLINK_MODE_DEBUG_SWD;
1298         case HL_TRANSPORT_JTAG:
1299                 return STLINK_MODE_DEBUG_JTAG;
1300         default:
1301                 return STLINK_MODE_UNKNOWN;
1302         }
1303 }
1304
1305 /** */
1306 static int stlink_usb_init_mode(void *handle, bool connect_under_reset, int initial_interface_speed)
1307 {
1308         int res;
1309         uint8_t mode;
1310         enum stlink_mode emode;
1311         struct stlink_usb_handle_s *h = handle;
1312
1313         assert(handle != NULL);
1314
1315         res = stlink_usb_current_mode(handle, &mode);
1316
1317         if (res != ERROR_OK)
1318                 return res;
1319
1320         LOG_DEBUG("MODE: 0x%02X", mode);
1321
1322         /* try to exit current mode */
1323         switch (mode) {
1324                 case STLINK_DEV_DFU_MODE:
1325                         emode = STLINK_MODE_DFU;
1326                         break;
1327                 case STLINK_DEV_DEBUG_MODE:
1328                         emode = STLINK_MODE_DEBUG_SWD;
1329                         break;
1330                 case STLINK_DEV_SWIM_MODE:
1331                         emode = STLINK_MODE_DEBUG_SWIM;
1332                         break;
1333                 case STLINK_DEV_BOOTLOADER_MODE:
1334                 case STLINK_DEV_MASS_MODE:
1335                 default:
1336                         emode = STLINK_MODE_UNKNOWN;
1337                         break;
1338         }
1339
1340         if (emode != STLINK_MODE_UNKNOWN) {
1341                 res = stlink_usb_mode_leave(handle, emode);
1342
1343                 if (res != ERROR_OK)
1344                         return res;
1345         }
1346
1347         res = stlink_usb_current_mode(handle, &mode);
1348
1349         if (res != ERROR_OK)
1350                 return res;
1351
1352         /* we check the target voltage here as an aid to debugging connection problems.
1353          * the stlink requires the target Vdd to be connected for reliable debugging.
1354          * this cmd is supported in all modes except DFU
1355          */
1356         if (mode != STLINK_DEV_DFU_MODE) {
1357
1358                 float target_voltage;
1359
1360                 /* check target voltage (if supported) */
1361                 res = stlink_usb_check_voltage(h, &target_voltage);
1362
1363                 if (res != ERROR_OK) {
1364                         if (res != ERROR_COMMAND_NOTFOUND)
1365                                 LOG_ERROR("voltage check failed");
1366                         /* attempt to continue as it is not a catastrophic failure */
1367                 } else {
1368                         /* check for a sensible target voltage, operating range is 1.65-5.5v
1369                          * according to datasheet */
1370                         if (target_voltage < 1.5)
1371                                 LOG_ERROR("target voltage may be too low for reliable debugging");
1372                 }
1373         }
1374
1375         LOG_DEBUG("MODE: 0x%02X", mode);
1376
1377         /* set selected mode */
1378         emode = h->st_mode;
1379
1380         if (emode == STLINK_MODE_UNKNOWN) {
1381                 LOG_ERROR("selected mode (transport) not supported");
1382                 return ERROR_FAIL;
1383         }
1384
1385         /* set the speed before entering the mode, as the chip discovery phase should be done at this speed too */
1386         if (emode == STLINK_MODE_DEBUG_JTAG) {
1387                 if (h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ) {
1388                         stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
1389                         stlink_speed(h, initial_interface_speed, false);
1390                 }
1391         } else if (emode == STLINK_MODE_DEBUG_SWD) {
1392                 if (h->version.flags & STLINK_F_HAS_SWD_SET_FREQ) {
1393                         stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
1394                         stlink_speed(h, initial_interface_speed, false);
1395                 }
1396         }
1397
1398         if (h->version.jtag_api == STLINK_JTAG_API_V3) {
1399                 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
1400
1401                 stlink_get_com_freq(h, (emode == STLINK_MODE_DEBUG_JTAG), map);
1402                 stlink_dump_speed_map(map, ARRAY_SIZE(map));
1403                 stlink_speed(h, initial_interface_speed, false);
1404         }
1405
1406         /* preliminary SRST assert:
1407          * We want SRST is asserted before activating debug signals (mode_enter).
1408          * As the required mode has not been set, the adapter may not know what pin to use.
1409          * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
1410          * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
1411          * after power on, SWIM_RST stays unchanged */
1412         if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
1413                 stlink_usb_assert_srst(handle, 0);
1414                 /* do not check the return status here, we will
1415                    proceed and enter the desired mode below
1416                    and try asserting srst again. */
1417
1418         res = stlink_usb_mode_enter(handle, emode);
1419         if (res != ERROR_OK)
1420                 return res;
1421
1422         /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
1423         if (connect_under_reset) {
1424                 res = stlink_usb_assert_srst(handle, 0);
1425                 if (res != ERROR_OK)
1426                         return res;
1427         }
1428
1429         res = stlink_usb_current_mode(handle, &mode);
1430
1431         if (res != ERROR_OK)
1432                 return res;
1433
1434         LOG_DEBUG("MODE: 0x%02X", mode);
1435
1436         return ERROR_OK;
1437 }
1438
1439 /* request status from last swim request */
1440 static int stlink_swim_status(void *handle)
1441 {
1442         struct stlink_usb_handle_s *h = handle;
1443         int res;
1444
1445         stlink_usb_init_buffer(handle, h->rx_ep, 4);
1446         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1447         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
1448         /* error is checked by the caller */
1449         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1450         if (res != ERROR_OK)
1451                 return res;
1452         return ERROR_OK;
1453 }
1454 /*
1455         the purpose of this function is unknown...
1456         capabilites? anyway for swim v6 it returns
1457         0001020600000000
1458 */
1459 __attribute__((unused))
1460 static int stlink_swim_cap(void *handle, uint8_t *cap)
1461 {
1462         struct stlink_usb_handle_s *h = handle;
1463         int res;
1464
1465         stlink_usb_init_buffer(handle, h->rx_ep, 8);
1466         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1467         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1468         h->cmdbuf[h->cmdidx++] = 0x01;
1469         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1470         if (res != ERROR_OK)
1471                 return res;
1472         memcpy(cap, h->databuf, 8);
1473         return ERROR_OK;
1474 }
1475
1476 /*      debug dongle assert/deassert sreset line */
1477 static int stlink_swim_assert_reset(void *handle, int reset)
1478 {
1479         struct stlink_usb_handle_s *h = handle;
1480         int res;
1481
1482         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1483         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1484         if (!reset)
1485                 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1486         else
1487                 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1488         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1489         if (res != ERROR_OK)
1490                 return res;
1491         return ERROR_OK;
1492 }
1493
1494 /*
1495         send swim enter seq
1496         1.3ms low then 750Hz then 1.5kHz
1497 */
1498 static int stlink_swim_enter(void *handle)
1499 {
1500         struct stlink_usb_handle_s *h = handle;
1501         int res;
1502
1503         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1504         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1505         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1506         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1507         if (res != ERROR_OK)
1508                 return res;
1509         return ERROR_OK;
1510 }
1511
1512 /*      switch high/low speed swim */
1513 static int stlink_swim_speed(void *handle, int speed)
1514 {
1515         struct stlink_usb_handle_s *h = handle;
1516         int res;
1517
1518         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1519         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1520         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1521         if (speed)
1522                 h->cmdbuf[h->cmdidx++] = 1;
1523         else
1524                 h->cmdbuf[h->cmdidx++] = 0;
1525         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1526         if (res != ERROR_OK)
1527                 return res;
1528         return ERROR_OK;
1529 }
1530
1531 /*
1532         initiate srst from swim.
1533         nrst is pulled low for 50us.
1534 */
1535 static int stlink_swim_generate_rst(void *handle)
1536 {
1537         struct stlink_usb_handle_s *h = handle;
1538         int res;
1539
1540         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1541         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1542         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1543         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1544         if (res != ERROR_OK)
1545                 return res;
1546         return ERROR_OK;
1547 }
1548
1549 /*
1550         send resyncronize sequence
1551         swim is pulled low for 16us
1552         reply is 64 clks low
1553 */
1554 static int stlink_swim_resync(void *handle)
1555 {
1556         struct stlink_usb_handle_s *h = handle;
1557         int res;
1558
1559         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1560         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1561         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_RESET;
1562         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1563         if (res != ERROR_OK)
1564                 return res;
1565         return ERROR_OK;
1566 }
1567
1568 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1569 {
1570         struct stlink_usb_handle_s *h = handle;
1571         int res;
1572         unsigned int i;
1573         unsigned int datalen = 0;
1574         int cmdsize = STLINK_CMD_SIZE_V2;
1575
1576         if (len > STLINK_DATA_SIZE)
1577                 return ERROR_FAIL;
1578
1579         if (h->version.stlink == 1)
1580                 cmdsize = STLINK_SG_SIZE;
1581
1582         stlink_usb_init_buffer(handle, h->tx_ep, 0);
1583         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1584         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1585         h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1586         h->cmdidx += 2;
1587         h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1588         h->cmdidx += 4;
1589         for (i = 0; i < len; i++) {
1590                 if (h->cmdidx == cmdsize)
1591                         h->databuf[datalen++] = *(data++);
1592                 else
1593                         h->cmdbuf[h->cmdidx++] = *(data++);
1594         }
1595         if (h->version.stlink == 1)
1596                 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1597
1598         res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1599         if (res != ERROR_OK)
1600                 return res;
1601         return ERROR_OK;
1602 }
1603
1604 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1605 {
1606         struct stlink_usb_handle_s *h = handle;
1607         int res;
1608
1609         if (len > STLINK_DATA_SIZE)
1610                 return ERROR_FAIL;
1611
1612         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1613         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1614         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1615         h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1616         h->cmdidx += 2;
1617         h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1618         h->cmdidx += 4;
1619         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1620         if (res != ERROR_OK)
1621                 return res;
1622
1623         stlink_usb_init_buffer(handle, h->rx_ep, len);
1624         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1625         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1626         res = stlink_usb_xfer_noerrcheck(handle, data, len);
1627         if (res != ERROR_OK)
1628                 return res;
1629
1630         return ERROR_OK;
1631 }
1632
1633 /** */
1634 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1635 {
1636         int res, offset;
1637         struct stlink_usb_handle_s *h = handle;
1638
1639         assert(handle != NULL);
1640
1641         /* there is no swim read core id cmd */
1642         if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
1643                 *idcode = 0;
1644                 return ERROR_OK;
1645         }
1646
1647         stlink_usb_init_buffer(handle, h->rx_ep, 12);
1648
1649         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1650         if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1651                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1652
1653                 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1654                 offset = 0;
1655         } else {
1656                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_IDCODES;
1657
1658                 res = stlink_usb_xfer_errcheck(handle, h->databuf, 12);
1659                 offset = 4;
1660         }
1661
1662         if (res != ERROR_OK)
1663                 return res;
1664
1665         *idcode = le_to_h_u32(h->databuf + offset);
1666
1667         LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1668
1669         return ERROR_OK;
1670 }
1671
1672 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1673 {
1674         struct stlink_usb_handle_s *h = handle;
1675         int res;
1676
1677         assert(handle != NULL);
1678
1679         stlink_usb_init_buffer(handle, h->rx_ep, 8);
1680
1681         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1682         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1683         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1684         h->cmdidx += 4;
1685
1686         res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1687         if (res != ERROR_OK)
1688                 return res;
1689
1690         *val = le_to_h_u32(h->databuf + 4);
1691         return ERROR_OK;
1692 }
1693
1694 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1695 {
1696         struct stlink_usb_handle_s *h = handle;
1697
1698         assert(handle != NULL);
1699
1700         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1701
1702         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1703         if (h->version.jtag_api == STLINK_JTAG_API_V1)
1704                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1705         else
1706                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1707         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1708         h->cmdidx += 4;
1709         h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1710         h->cmdidx += 4;
1711
1712         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1713 }
1714
1715 /** */
1716 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1717 {
1718         struct stlink_usb_handle_s *h = handle;
1719
1720         assert(handle != NULL);
1721
1722         if (h->trace.enabled && (h->version.flags & STLINK_F_HAS_TRACE)) {
1723                 int res;
1724
1725                 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1726
1727                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1728                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1729
1730                 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1731                 if (res != ERROR_OK)
1732                         return res;
1733
1734                 size_t bytes_avail = le_to_h_u16(h->databuf);
1735                 *size = bytes_avail < *size ? bytes_avail : *size - 1;
1736
1737                 if (*size > 0) {
1738                         res = stlink_usb_read_trace(handle, buf, *size);
1739                         if (res != ERROR_OK)
1740                                 return res;
1741                         return ERROR_OK;
1742                 }
1743         }
1744         *size = 0;
1745         return ERROR_OK;
1746 }
1747
1748 static enum target_state stlink_usb_v2_get_status(void *handle)
1749 {
1750         int result;
1751         uint32_t status;
1752
1753         result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1754         if  (result != ERROR_OK)
1755                 return TARGET_UNKNOWN;
1756
1757         if (status & S_HALT)
1758                 return TARGET_HALTED;
1759         else if (status & S_RESET_ST)
1760                 return TARGET_RESET;
1761
1762         return TARGET_RUNNING;
1763 }
1764
1765 /** */
1766 static enum target_state stlink_usb_state(void *handle)
1767 {
1768         int res;
1769         struct stlink_usb_handle_s *h = handle;
1770
1771         assert(handle != NULL);
1772
1773         if (h->reconnect_pending) {
1774                 LOG_INFO("Previous state query failed, trying to reconnect");
1775                 res = stlink_usb_mode_enter(handle, h->st_mode);
1776                 if (res != ERROR_OK)
1777                         return TARGET_UNKNOWN;
1778
1779                 h->reconnect_pending = false;
1780         }
1781
1782         if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1783                 res = stlink_usb_v2_get_status(handle);
1784                 if (res == TARGET_UNKNOWN)
1785                         h->reconnect_pending = true;
1786                 return res;
1787         }
1788
1789         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1790
1791         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1792         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
1793
1794         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1795
1796         if (res != ERROR_OK)
1797                 return TARGET_UNKNOWN;
1798
1799         if (h->databuf[0] == STLINK_CORE_RUNNING)
1800                 return TARGET_RUNNING;
1801         if (h->databuf[0] == STLINK_CORE_HALTED)
1802                 return TARGET_HALTED;
1803
1804         h->reconnect_pending = true;
1805
1806         return TARGET_UNKNOWN;
1807 }
1808
1809 static int stlink_usb_assert_srst(void *handle, int srst)
1810 {
1811         struct stlink_usb_handle_s *h = handle;
1812
1813         assert(handle != NULL);
1814
1815         if (h->st_mode == STLINK_MODE_DEBUG_SWIM)
1816                 return stlink_swim_assert_reset(handle, srst);
1817
1818         if (h->version.stlink == 1)
1819                 return ERROR_COMMAND_NOTFOUND;
1820
1821         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1822
1823         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1824         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
1825         h->cmdbuf[h->cmdidx++] = srst;
1826
1827         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1828 }
1829
1830 /** */
1831 static void stlink_usb_trace_disable(void *handle)
1832 {
1833         int res = ERROR_OK;
1834         struct stlink_usb_handle_s *h = handle;
1835
1836         assert(handle != NULL);
1837
1838         assert(h->version.flags & STLINK_F_HAS_TRACE);
1839
1840         LOG_DEBUG("Tracing: disable");
1841
1842         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1843         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1844         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
1845         res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1846
1847         if (res == ERROR_OK)
1848                 h->trace.enabled = false;
1849 }
1850
1851
1852 /** */
1853 static int stlink_usb_trace_enable(void *handle)
1854 {
1855         int res;
1856         struct stlink_usb_handle_s *h = handle;
1857
1858         assert(handle != NULL);
1859
1860         if (h->version.flags & STLINK_F_HAS_TRACE) {
1861                 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1862
1863                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1864                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
1865                 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
1866                 h->cmdidx += 2;
1867                 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
1868                 h->cmdidx += 4;
1869
1870                 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1871
1872                 if (res == ERROR_OK)  {
1873                         h->trace.enabled = true;
1874                         LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
1875                 }
1876         } else {
1877                 LOG_ERROR("Tracing is not supported by this version.");
1878                 res = ERROR_FAIL;
1879         }
1880
1881         return res;
1882 }
1883
1884 /** */
1885 static int stlink_usb_reset(void *handle)
1886 {
1887         struct stlink_usb_handle_s *h = handle;
1888         int retval;
1889
1890         assert(handle != NULL);
1891
1892         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1893
1894         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1895
1896         if (h->version.jtag_api == STLINK_JTAG_API_V1)
1897                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
1898         else
1899                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
1900
1901         retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
1902         if (retval != ERROR_OK)
1903                 return retval;
1904
1905         if (h->trace.enabled) {
1906                 stlink_usb_trace_disable(h);
1907                 return stlink_usb_trace_enable(h);
1908         }
1909
1910         return ERROR_OK;
1911 }
1912
1913 /** */
1914 static int stlink_usb_run(void *handle)
1915 {
1916         int res;
1917         struct stlink_usb_handle_s *h = handle;
1918
1919         assert(handle != NULL);
1920
1921         if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1922                 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
1923
1924                 return res;
1925         }
1926
1927         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1928
1929         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1930         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
1931
1932         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1933 }
1934
1935 /** */
1936 static int stlink_usb_halt(void *handle)
1937 {
1938         int res;
1939         struct stlink_usb_handle_s *h = handle;
1940
1941         assert(handle != NULL);
1942
1943         if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1944                 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1945
1946                 return res;
1947         }
1948
1949         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1950
1951         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1952         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
1953
1954         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1955 }
1956
1957 /** */
1958 static int stlink_usb_step(void *handle)
1959 {
1960         struct stlink_usb_handle_s *h = handle;
1961
1962         assert(handle != NULL);
1963
1964         if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1965                 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
1966                  * that the Cortex-M3 currently does. */
1967                 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
1968                 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
1969                 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1970         }
1971
1972         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1973
1974         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1975         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
1976
1977         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1978 }
1979
1980 /** */
1981 static int stlink_usb_read_regs(void *handle)
1982 {
1983         int res;
1984         struct stlink_usb_handle_s *h = handle;
1985
1986         assert(handle != NULL);
1987
1988         stlink_usb_init_buffer(handle, h->rx_ep, 88);
1989
1990         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1991         if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1992
1993                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
1994                 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 84);
1995                 /* regs data from offset 0 */
1996         } else {
1997                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
1998                 res = stlink_usb_xfer_errcheck(handle, h->databuf, 88);
1999                 /* status at offset 0, regs data from offset 4 */
2000         }
2001
2002         return res;
2003 }
2004
2005 /** */
2006 static int stlink_usb_read_reg(void *handle, int num, uint32_t *val)
2007 {
2008         int res;
2009         struct stlink_usb_handle_s *h = handle;
2010
2011         assert(handle != NULL);
2012
2013         stlink_usb_init_buffer(handle, h->rx_ep, h->version.jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
2014
2015         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2016         if (h->version.jtag_api == STLINK_JTAG_API_V1)
2017                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
2018         else
2019                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
2020         h->cmdbuf[h->cmdidx++] = num;
2021
2022         if (h->version.jtag_api == STLINK_JTAG_API_V1) {
2023                 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
2024                 if (res != ERROR_OK)
2025                         return res;
2026                 *val = le_to_h_u32(h->databuf);
2027                 return ERROR_OK;
2028         } else {
2029                 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
2030                 if (res != ERROR_OK)
2031                         return res;
2032                 *val = le_to_h_u32(h->databuf + 4);
2033                 return ERROR_OK;
2034         }
2035 }
2036
2037 /** */
2038 static int stlink_usb_write_reg(void *handle, int num, uint32_t val)
2039 {
2040         struct stlink_usb_handle_s *h = handle;
2041
2042         assert(handle != NULL);
2043
2044         stlink_usb_init_buffer(handle, h->rx_ep, 2);
2045
2046         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2047         if (h->version.jtag_api == STLINK_JTAG_API_V1)
2048                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
2049         else
2050                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
2051         h->cmdbuf[h->cmdidx++] = num;
2052         h_u32_to_le(h->cmdbuf+h->cmdidx, val);
2053         h->cmdidx += 4;
2054
2055         return stlink_cmd_allow_retry(handle, h->databuf, 2);
2056 }
2057
2058 static int stlink_usb_get_rw_status(void *handle)
2059 {
2060         struct stlink_usb_handle_s *h = handle;
2061
2062         assert(handle != NULL);
2063
2064         if (h->version.jtag_api == STLINK_JTAG_API_V1)
2065                 return ERROR_OK;
2066
2067         stlink_usb_init_buffer(handle, h->rx_ep, 2);
2068
2069         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2070         if (h->version.flags & STLINK_F_HAS_GETLASTRWSTATUS2) {
2071                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS2;
2072                 return stlink_usb_xfer_errcheck(handle, h->databuf, 12);
2073         } else {
2074                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
2075                 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2076         }
2077 }
2078
2079 /** */
2080 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
2081                           uint8_t *buffer)
2082 {
2083         int res;
2084         uint16_t read_len = len;
2085         struct stlink_usb_handle_s *h = handle;
2086
2087         assert(handle != NULL);
2088
2089         /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2090         if (len > stlink_usb_block(h)) {
2091                 LOG_DEBUG("max buffer (%d) length exceeded", stlink_usb_block(h));
2092                 return ERROR_FAIL;
2093         }
2094
2095         stlink_usb_init_buffer(handle, h->rx_ep, read_len);
2096
2097         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2098         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
2099         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2100         h->cmdidx += 4;
2101         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2102         h->cmdidx += 2;
2103
2104         /* we need to fix read length for single bytes */
2105         if (read_len == 1)
2106                 read_len++;
2107
2108         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, read_len);
2109
2110         if (res != ERROR_OK)
2111                 return res;
2112
2113         memcpy(buffer, h->databuf, len);
2114
2115         return stlink_usb_get_rw_status(handle);
2116 }
2117
2118 /** */
2119 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
2120                            const uint8_t *buffer)
2121 {
2122         int res;
2123         struct stlink_usb_handle_s *h = handle;
2124
2125         assert(handle != NULL);
2126
2127         /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2128         if (len > stlink_usb_block(h)) {
2129                 LOG_DEBUG("max buffer length (%d) exceeded", stlink_usb_block(h));
2130                 return ERROR_FAIL;
2131         }
2132
2133         stlink_usb_init_buffer(handle, h->tx_ep, len);
2134
2135         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2136         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
2137         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2138         h->cmdidx += 4;
2139         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2140         h->cmdidx += 2;
2141
2142         res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2143
2144         if (res != ERROR_OK)
2145                 return res;
2146
2147         return stlink_usb_get_rw_status(handle);
2148 }
2149
2150 /** */
2151 static int stlink_usb_read_mem16(void *handle, uint32_t addr, uint16_t len,
2152                           uint8_t *buffer)
2153 {
2154         int res;
2155         struct stlink_usb_handle_s *h = handle;
2156
2157         assert(handle != NULL);
2158
2159         if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2160                 return ERROR_COMMAND_NOTFOUND;
2161
2162         /* data must be a multiple of 2 and half-word aligned */
2163         if (len % 2 || addr % 2) {
2164                 LOG_DEBUG("Invalid data alignment");
2165                 return ERROR_TARGET_UNALIGNED_ACCESS;
2166         }
2167
2168         stlink_usb_init_buffer(handle, h->rx_ep, len);
2169
2170         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2171         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READMEM_16BIT;
2172         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2173         h->cmdidx += 4;
2174         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2175         h->cmdidx += 2;
2176
2177         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2178
2179         if (res != ERROR_OK)
2180                 return res;
2181
2182         memcpy(buffer, h->databuf, len);
2183
2184         return stlink_usb_get_rw_status(handle);
2185 }
2186
2187 /** */
2188 static int stlink_usb_write_mem16(void *handle, uint32_t addr, uint16_t len,
2189                            const uint8_t *buffer)
2190 {
2191         int res;
2192         struct stlink_usb_handle_s *h = handle;
2193
2194         assert(handle != NULL);
2195
2196         if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2197                 return ERROR_COMMAND_NOTFOUND;
2198
2199         /* data must be a multiple of 2 and half-word aligned */
2200         if (len % 2 || addr % 2) {
2201                 LOG_DEBUG("Invalid data alignment");
2202                 return ERROR_TARGET_UNALIGNED_ACCESS;
2203         }
2204
2205         stlink_usb_init_buffer(handle, h->tx_ep, len);
2206
2207         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2208         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEMEM_16BIT;
2209         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2210         h->cmdidx += 4;
2211         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2212         h->cmdidx += 2;
2213
2214         res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2215
2216         if (res != ERROR_OK)
2217                 return res;
2218
2219         return stlink_usb_get_rw_status(handle);
2220 }
2221
2222 /** */
2223 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
2224                           uint8_t *buffer)
2225 {
2226         int res;
2227         struct stlink_usb_handle_s *h = handle;
2228
2229         assert(handle != NULL);
2230
2231         /* data must be a multiple of 4 and word aligned */
2232         if (len % 4 || addr % 4) {
2233                 LOG_DEBUG("Invalid data alignment");
2234                 return ERROR_TARGET_UNALIGNED_ACCESS;
2235         }
2236
2237         stlink_usb_init_buffer(handle, h->rx_ep, len);
2238
2239         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2240         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
2241         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2242         h->cmdidx += 4;
2243         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2244         h->cmdidx += 2;
2245
2246         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2247
2248         if (res != ERROR_OK)
2249                 return res;
2250
2251         memcpy(buffer, h->databuf, len);
2252
2253         return stlink_usb_get_rw_status(handle);
2254 }
2255
2256 /** */
2257 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
2258                            const uint8_t *buffer)
2259 {
2260         int res;
2261         struct stlink_usb_handle_s *h = handle;
2262
2263         assert(handle != NULL);
2264
2265         /* data must be a multiple of 4 and word aligned */
2266         if (len % 4 || addr % 4) {
2267                 LOG_DEBUG("Invalid data alignment");
2268                 return ERROR_TARGET_UNALIGNED_ACCESS;
2269         }
2270
2271         stlink_usb_init_buffer(handle, h->tx_ep, len);
2272
2273         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2274         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
2275         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2276         h->cmdidx += 4;
2277         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2278         h->cmdidx += 2;
2279
2280         res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2281
2282         if (res != ERROR_OK)
2283                 return res;
2284
2285         return stlink_usb_get_rw_status(handle);
2286 }
2287
2288 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
2289 {
2290         uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
2291         if (max_tar_block == 0)
2292                 max_tar_block = 4;
2293         return max_tar_block;
2294 }
2295
2296 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
2297                 uint32_t count, uint8_t *buffer)
2298 {
2299         int retval = ERROR_OK;
2300         uint32_t bytes_remaining;
2301         int retries = 0;
2302         struct stlink_usb_handle_s *h = handle;
2303
2304         /* calculate byte count */
2305         count *= size;
2306
2307         /* switch to 8 bit if stlink does not support 16 bit memory read */
2308         if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2309                 size = 1;
2310
2311         while (count) {
2312
2313                 bytes_remaining = (size != 1) ?
2314                                 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2315
2316                 if (count < bytes_remaining)
2317                         bytes_remaining = count;
2318
2319                 /*
2320                  * all stlink support 8/32bit memory read/writes and only from
2321                  * stlink V2J26 there is support for 16 bit memory read/write.
2322                  * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2323                  * as 8bit access.
2324                  */
2325                 if (size != 1) {
2326
2327                         /* When in jtag mode the stlink uses the auto-increment functionality.
2328                          * However it expects us to pass the data correctly, this includes
2329                          * alignment and any page boundaries. We already do this as part of the
2330                          * adi_v5 implementation, but the stlink is a hla adapter and so this
2331                          * needs implementing manually.
2332                          * currently this only affects jtag mode, according to ST they do single
2333                          * access in SWD mode - but this may change and so we do it for both modes */
2334
2335                         /* we first need to check for any unaligned bytes */
2336                         if (addr & (size - 1)) {
2337
2338                                 uint32_t head_bytes = size - (addr & (size - 1));
2339                                 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
2340                                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2341                                         usleep((1<<retries++) * 1000);
2342                                         continue;
2343                                 }
2344                                 if (retval != ERROR_OK)
2345                                         return retval;
2346                                 buffer += head_bytes;
2347                                 addr += head_bytes;
2348                                 count -= head_bytes;
2349                                 bytes_remaining -= head_bytes;
2350                         }
2351
2352                         if (bytes_remaining & (size - 1))
2353                                 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
2354                         else if (size == 2)
2355                                 retval = stlink_usb_read_mem16(handle, addr, bytes_remaining, buffer);
2356                         else
2357                                 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
2358                 } else
2359                         retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
2360
2361                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2362                         usleep((1<<retries++) * 1000);
2363                         continue;
2364                 }
2365                 if (retval != ERROR_OK)
2366                         return retval;
2367
2368                 buffer += bytes_remaining;
2369                 addr += bytes_remaining;
2370                 count -= bytes_remaining;
2371         }
2372
2373         return retval;
2374 }
2375
2376 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
2377                 uint32_t count, const uint8_t *buffer)
2378 {
2379         int retval = ERROR_OK;
2380         uint32_t bytes_remaining;
2381         int retries = 0;
2382         struct stlink_usb_handle_s *h = handle;
2383
2384         /* calculate byte count */
2385         count *= size;
2386
2387         /* switch to 8 bit if stlink does not support 16 bit memory read */
2388         if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2389                 size = 1;
2390
2391         while (count) {
2392
2393                 bytes_remaining = (size != 1) ?
2394                                 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2395
2396                 if (count < bytes_remaining)
2397                         bytes_remaining = count;
2398
2399                 /*
2400                  * all stlink support 8/32bit memory read/writes and only from
2401                  * stlink V2J26 there is support for 16 bit memory read/write.
2402                  * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2403                  * as 8bit access.
2404                  */
2405                 if (size != 1) {
2406
2407                         /* When in jtag mode the stlink uses the auto-increment functionality.
2408                          * However it expects us to pass the data correctly, this includes
2409                          * alignment and any page boundaries. We already do this as part of the
2410                          * adi_v5 implementation, but the stlink is a hla adapter and so this
2411                          * needs implementing manually.
2412                          * currently this only affects jtag mode, according to ST they do single
2413                          * access in SWD mode - but this may change and so we do it for both modes */
2414
2415                         /* we first need to check for any unaligned bytes */
2416                         if (addr & (size - 1)) {
2417
2418                                 uint32_t head_bytes = size - (addr & (size - 1));
2419                                 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
2420                                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2421                                         usleep((1<<retries++) * 1000);
2422                                         continue;
2423                                 }
2424                                 if (retval != ERROR_OK)
2425                                         return retval;
2426                                 buffer += head_bytes;
2427                                 addr += head_bytes;
2428                                 count -= head_bytes;
2429                                 bytes_remaining -= head_bytes;
2430                         }
2431
2432                         if (bytes_remaining & (size - 1))
2433                                 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
2434                         else if (size == 2)
2435                                 retval = stlink_usb_write_mem16(handle, addr, bytes_remaining, buffer);
2436                         else
2437                                 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
2438
2439                 } else
2440                         retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, 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
2448                 buffer += bytes_remaining;
2449                 addr += bytes_remaining;
2450                 count -= bytes_remaining;
2451         }
2452
2453         return retval;
2454 }
2455
2456 /** */
2457 static int stlink_usb_override_target(const char *targetname)
2458 {
2459         return !strcmp(targetname, "cortex_m");
2460 }
2461
2462 static int stlink_speed_swim(void *handle, int khz, bool query)
2463 {
2464         int retval;
2465
2466         /*
2467                         we only have low and high speed...
2468                         before changing speed the SWIM_CSR HS bit
2469                         must be updated
2470          */
2471         if (!query) {
2472                 retval = stlink_swim_speed(handle, (khz < SWIM_FREQ_HIGH) ? 0 : 1);
2473                 if (retval != ERROR_OK)
2474                         LOG_ERROR("Unable to set adapter speed");
2475         }
2476
2477         return (khz < SWIM_FREQ_HIGH) ? SWIM_FREQ_LOW : SWIM_FREQ_HIGH;
2478 }
2479
2480 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
2481 {
2482         unsigned int i;
2483         int speed_index = -1;
2484         int speed_diff = INT_MAX;
2485         int last_valid_speed = -1;
2486         bool match = true;
2487
2488         for (i = 0; i < map_size; i++) {
2489                 if (!map[i].speed)
2490                         continue;
2491                 last_valid_speed = i;
2492                 if (khz == map[i].speed) {
2493                         speed_index = i;
2494                         break;
2495                 } else {
2496                         int current_diff = khz - map[i].speed;
2497                         /* get abs value for comparison */
2498                         current_diff = (current_diff > 0) ? current_diff : -current_diff;
2499                         if ((current_diff < speed_diff) && khz >= map[i].speed) {
2500                                 speed_diff = current_diff;
2501                                 speed_index = i;
2502                         }
2503                 }
2504         }
2505
2506         if (speed_index == -1) {
2507                 /* this will only be here if we cannot match the slow speed.
2508                  * use the slowest speed we support.*/
2509                 speed_index = last_valid_speed;
2510                 match = false;
2511         } else if (i == map_size)
2512                 match = false;
2513
2514         if (!match && query) {
2515                 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz",
2516                                 khz, map[speed_index].speed);
2517         }
2518
2519         return speed_index;
2520 }
2521
2522 static int stlink_speed_swd(void *handle, int khz, bool query)
2523 {
2524         int speed_index;
2525         struct stlink_usb_handle_s *h = handle;
2526
2527         /* old firmware cannot change it */
2528         if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
2529                 return khz;
2530
2531         speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
2532                 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
2533
2534         if (!query) {
2535                 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
2536                 if (result != ERROR_OK) {
2537                         LOG_ERROR("Unable to set adapter speed");
2538                         return khz;
2539                 }
2540         }
2541
2542         return stlink_khz_to_speed_map_swd[speed_index].speed;
2543 }
2544
2545 static int stlink_speed_jtag(void *handle, int khz, bool query)
2546 {
2547         int speed_index;
2548         struct stlink_usb_handle_s *h = handle;
2549
2550         /* old firmware cannot change it */
2551         if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
2552                 return khz;
2553
2554         speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2555                 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2556
2557         if (!query) {
2558                 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2559                 if (result != ERROR_OK) {
2560                         LOG_ERROR("Unable to set adapter speed");
2561                         return khz;
2562                 }
2563         }
2564
2565         return stlink_khz_to_speed_map_jtag[speed_index].speed;
2566 }
2567
2568 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2569 {
2570         unsigned int i;
2571
2572         LOG_DEBUG("Supported clock speeds are:");
2573         for (i = 0; i < map_size; i++)
2574                 if (map[i].speed)
2575                         LOG_DEBUG("%d kHz", map[i].speed);
2576 }
2577
2578 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map)
2579 {
2580         struct stlink_usb_handle_s *h = handle;
2581         int i;
2582
2583         if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2584                 LOG_ERROR("Unknown command");
2585                 return 0;
2586         }
2587
2588         stlink_usb_init_buffer(handle, h->rx_ep, 16);
2589
2590         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2591         h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_COM_FREQ;
2592         h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2593
2594         int res = stlink_usb_xfer_errcheck(handle, h->databuf, 52);
2595
2596         int size = h->databuf[8];
2597
2598         if (size > STLINK_V3_MAX_FREQ_NB)
2599                 size = STLINK_V3_MAX_FREQ_NB;
2600
2601         for (i = 0; i < size; i++) {
2602                 map[i].speed = le_to_h_u32(&h->databuf[12 + 4 * i]);
2603                 map[i].speed_divisor = i;
2604         }
2605
2606         /* set to zero all the next entries */
2607         for (i = size; i < STLINK_V3_MAX_FREQ_NB; i++)
2608                 map[i].speed = 0;
2609
2610         return res;
2611 }
2612
2613 static int stlink_set_com_freq(void *handle, bool is_jtag, unsigned int frequency)
2614 {
2615         struct stlink_usb_handle_s *h = handle;
2616
2617         if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2618                 LOG_ERROR("Unknown command");
2619                 return 0;
2620         }
2621
2622         stlink_usb_init_buffer(handle, h->rx_ep, 16);
2623
2624         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2625         h->cmdbuf[h->cmdidx++] = STLINK_APIV3_SET_COM_FREQ;
2626         h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2627         h->cmdbuf[h->cmdidx++] = 0;
2628
2629         h_u32_to_le(&h->cmdbuf[4], frequency);
2630
2631         return stlink_usb_xfer_errcheck(handle, h->databuf, 8);
2632 }
2633
2634 static int stlink_speed_v3(void *handle, bool is_jtag, int khz, bool query)
2635 {
2636         struct stlink_usb_handle_s *h = handle;
2637         int speed_index;
2638         struct speed_map map[STLINK_V3_MAX_FREQ_NB];
2639
2640         stlink_get_com_freq(h, is_jtag, map);
2641
2642         speed_index = stlink_match_speed_map(map, ARRAY_SIZE(map), khz, query);
2643
2644         if (!query) {
2645                 int result = stlink_set_com_freq(h, is_jtag, map[speed_index].speed);
2646                 if (result != ERROR_OK) {
2647                         LOG_ERROR("Unable to set adapter speed");
2648                         return khz;
2649                 }
2650         }
2651         return map[speed_index].speed;
2652 }
2653
2654 static int stlink_speed(void *handle, int khz, bool query)
2655 {
2656         struct stlink_usb_handle_s *h = handle;
2657
2658         if (!handle)
2659                 return khz;
2660
2661         switch (h->st_mode) {
2662         case STLINK_MODE_DEBUG_SWIM:
2663                 return stlink_speed_swim(handle, khz, query);
2664         case STLINK_MODE_DEBUG_SWD:
2665                 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2666                         return stlink_speed_v3(handle, false, khz, query);
2667                 else
2668                         return stlink_speed_swd(handle, khz, query);
2669                 break;
2670         case STLINK_MODE_DEBUG_JTAG:
2671                 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2672                         return stlink_speed_v3(handle, true, khz, query);
2673                 else
2674                         return stlink_speed_jtag(handle, khz, query);
2675                 break;
2676         default:
2677                 break;
2678         }
2679
2680         return khz;
2681 }
2682
2683 /** */
2684 static int stlink_usb_close(void *handle)
2685 {
2686         int res;
2687         uint8_t mode;
2688         enum stlink_mode emode;
2689         struct stlink_usb_handle_s *h = handle;
2690
2691         if (h && h->fd)
2692                 res = stlink_usb_current_mode(handle, &mode);
2693         else
2694                 res = ERROR_FAIL;
2695         /* do not exit if return code != ERROR_OK,
2696            it prevents us from closing jtag_libusb */
2697
2698         if (res == ERROR_OK) {
2699                 /* try to exit current mode */
2700                 switch (mode) {
2701                         case STLINK_DEV_DFU_MODE:
2702                                 emode = STLINK_MODE_DFU;
2703                                 break;
2704                         case STLINK_DEV_DEBUG_MODE:
2705                                 emode = STLINK_MODE_DEBUG_SWD;
2706                                 break;
2707                         case STLINK_DEV_SWIM_MODE:
2708                                 emode = STLINK_MODE_DEBUG_SWIM;
2709                                 break;
2710                         case STLINK_DEV_BOOTLOADER_MODE:
2711                         case STLINK_DEV_MASS_MODE:
2712                         default:
2713                                 emode = STLINK_MODE_UNKNOWN;
2714                                 break;
2715                 }
2716
2717                 if (emode != STLINK_MODE_UNKNOWN)
2718                         stlink_usb_mode_leave(handle, emode);
2719                         /* do not check return code, it prevent
2720                         us from closing jtag_libusb */
2721         }
2722
2723         if (h && h->fd)
2724                 jtag_libusb_close(h->fd);
2725
2726         free(h);
2727
2728         return ERROR_OK;
2729 }
2730
2731 /* Compute ST-Link serial number from the device descriptor
2732  * this function will help to work-around a bug in old ST-Link/V2 DFU
2733  * the buggy DFU returns an incorrect serial in the USB descriptor
2734  * example for the following serial "57FF72067265575742132067"
2735  *  - the correct descriptor serial is:
2736  *    0x32, 0x03, 0x35, 0x00, 0x37, 0x00, 0x46, 0x00, 0x46, 0x00, 0x37, 0x00, 0x32, 0x00 ...
2737  *    this contains the length (0x32 = 50), the type (0x3 = DT_STRING) and the serial in unicode format
2738  *    the serial part is: 0x0035, 0x0037, 0x0046, 0x0046, 0x0037, 0x0032 ... >>  57FF72 ...
2739  *    this format could be read correctly by 'libusb_get_string_descriptor_ascii'
2740  *    so this case is managed by libusb_helper::string_descriptor_equal
2741  *  - the buggy DFU is not doing any unicode conversion and returns a raw serial data in the descriptor
2742  *    0x1a, 0x03, 0x57, 0x00, 0xFF, 0x00, 0x72, 0x00 ...
2743  *            >>    57          FF          72       ...
2744  *    based on the length (0x1a = 26) we could easily decide if we have to fixup the serial
2745  *    and then we have just to convert the raw data into printable characters using sprintf
2746  */
2747 char *stlink_usb_get_alternate_serial(libusb_device_handle *device,
2748                 struct libusb_device_descriptor *dev_desc)
2749 {
2750         int usb_retval;
2751         unsigned char desc_serial[(STLINK_SERIAL_LEN + 1) * 2];
2752
2753         if (dev_desc->iSerialNumber == 0)
2754                 return NULL;
2755
2756         /* get the LANGID from String Descriptor Zero */
2757         usb_retval = libusb_get_string_descriptor(device, 0, 0, desc_serial,
2758                         sizeof(desc_serial));
2759
2760         if (usb_retval < LIBUSB_SUCCESS) {
2761                 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
2762                                 libusb_error_name(usb_retval), usb_retval);
2763                 return NULL;
2764         } else if (usb_retval < 4) {
2765                 /* the size should be least 4 bytes to contain a minimum of 1 supported LANGID */
2766                 LOG_ERROR("could not get the LANGID");
2767                 return NULL;
2768         }
2769
2770         uint32_t langid = desc_serial[2] | (desc_serial[3] << 8);
2771
2772         /* get the serial */
2773         usb_retval = libusb_get_string_descriptor(device, dev_desc->iSerialNumber,
2774                         langid, desc_serial, sizeof(desc_serial));
2775
2776         unsigned char len = desc_serial[0];
2777
2778         if (usb_retval < LIBUSB_SUCCESS) {
2779                 LOG_ERROR("libusb_get_string_descriptor() failed: %s(%d)",
2780                                 libusb_error_name(usb_retval), usb_retval);
2781                 return NULL;
2782         } else if (desc_serial[1] != LIBUSB_DT_STRING || len > usb_retval) {
2783                 LOG_ERROR("invalid string in ST-LINK USB serial descriptor");
2784                 return NULL;
2785         }
2786
2787         if (len == ((STLINK_SERIAL_LEN + 1) * 2)) {
2788                 /* good ST-Link adapter, this case is managed by
2789                  * libusb::libusb_get_string_descriptor_ascii */
2790                 return NULL;
2791         } else if (len != ((STLINK_SERIAL_LEN / 2 + 1) * 2)) {
2792                 LOG_ERROR("unexpected serial length (%d) in descriptor", len);
2793                 return NULL;
2794         }
2795
2796         /* else (len == 26) => buggy ST-Link */
2797
2798         char *alternate_serial = malloc((STLINK_SERIAL_LEN + 1) * sizeof(char));
2799         if (alternate_serial == NULL)
2800                 return NULL;
2801
2802         for (unsigned int i = 0; i < STLINK_SERIAL_LEN; i += 2)
2803                 sprintf(alternate_serial + i, "%02X", desc_serial[i + 2]);
2804
2805         alternate_serial[STLINK_SERIAL_LEN] = '\0';
2806
2807         return alternate_serial;
2808 }
2809
2810 /** */
2811 static int stlink_usb_open(struct hl_interface_param_s *param, enum stlink_mode mode, void **fd)
2812 {
2813         int err, retry_count = 1;
2814         struct stlink_usb_handle_s *h;
2815
2816         LOG_DEBUG("stlink_usb_open");
2817
2818         h = calloc(1, sizeof(struct stlink_usb_handle_s));
2819
2820         if (h == 0) {
2821                 LOG_DEBUG("malloc failed");
2822                 return ERROR_FAIL;
2823         }
2824
2825         h->st_mode = mode;
2826
2827         for (unsigned i = 0; param->vid[i]; i++) {
2828                 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
2829                           h->st_mode, param->vid[i], param->pid[i],
2830                           param->serial ? param->serial : "");
2831         }
2832
2833         /*
2834           On certain host USB configurations(e.g. MacBook Air)
2835           STLINKv2 dongle seems to have its FW in a funky state if,
2836           after plugging it in, you try to use openocd with it more
2837           then once (by launching and closing openocd). In cases like
2838           that initial attempt to read the FW info via
2839           stlink_usb_version will fail and the device has to be reset
2840           in order to become operational.
2841          */
2842         do {
2843                 if (jtag_libusb_open(param->vid, param->pid, param->serial,
2844                                 &h->fd, stlink_usb_get_alternate_serial) != ERROR_OK) {
2845                         LOG_ERROR("open failed");
2846                         goto error_open;
2847                 }
2848
2849                 jtag_libusb_set_configuration(h->fd, 0);
2850
2851                 if (libusb_claim_interface(h->fd, 0) != ERROR_OK) {
2852                         LOG_DEBUG("claim interface failed");
2853                         goto error_open;
2854                 }
2855
2856                 /* RX EP is common for all versions */
2857                 h->rx_ep = STLINK_RX_EP;
2858
2859                 uint16_t pid;
2860                 if (jtag_libusb_get_pid(libusb_get_device(h->fd), &pid) != ERROR_OK) {
2861                         LOG_DEBUG("libusb_get_pid failed");
2862                         goto error_open;
2863                 }
2864
2865                 /* wrap version for first read */
2866                 switch (pid) {
2867                         case STLINK_V1_PID:
2868                                 h->version.stlink = 1;
2869                                 h->tx_ep = STLINK_TX_EP;
2870                                 break;
2871                         case STLINK_V3_USBLOADER_PID:
2872                         case STLINK_V3E_PID:
2873                         case STLINK_V3S_PID:
2874                         case STLINK_V3_2VCP_PID:
2875                                 h->version.stlink = 3;
2876                                 h->tx_ep = STLINK_V2_1_TX_EP;
2877                                 h->trace_ep = STLINK_V2_1_TRACE_EP;
2878                                 break;
2879                         case STLINK_V2_1_PID:
2880                         case STLINK_V2_1_NO_MSD_PID:
2881                                 h->version.stlink = 2;
2882                                 h->tx_ep = STLINK_V2_1_TX_EP;
2883                                 h->trace_ep = STLINK_V2_1_TRACE_EP;
2884                                 break;
2885                         default:
2886                         /* fall through - we assume V2 to be the default version*/
2887                         case STLINK_V2_PID:
2888                                 h->version.stlink = 2;
2889                                 h->tx_ep = STLINK_TX_EP;
2890                                 h->trace_ep = STLINK_TRACE_EP;
2891                                 break;
2892                 }
2893
2894                 /* get the device version */
2895                 err = stlink_usb_version(h);
2896
2897                 if (err == ERROR_OK) {
2898                         break;
2899                 } else if (h->version.stlink == 1 ||
2900                            retry_count == 0) {
2901                         LOG_ERROR("read version failed");
2902                         goto error_open;
2903                 } else {
2904                         err = libusb_release_interface(h->fd, 0);
2905                         if (err != ERROR_OK) {
2906                                 LOG_ERROR("release interface failed");
2907                                 goto error_open;
2908                         }
2909
2910                         err = libusb_reset_device(h->fd);
2911                         if (err != ERROR_OK) {
2912                                 LOG_ERROR("reset device failed");
2913                                 goto error_open;
2914                         }
2915
2916                         jtag_libusb_close(h->fd);
2917                         /*
2918                           Give the device one second to settle down and
2919                           reenumerate.
2920                          */
2921                         usleep(1 * 1000 * 1000);
2922                         retry_count--;
2923                 }
2924         } while (1);
2925
2926         /* check if mode is supported */
2927         err = ERROR_OK;
2928
2929         switch (h->st_mode) {
2930                 case STLINK_MODE_DEBUG_SWD:
2931                         if (h->version.jtag_api == STLINK_JTAG_API_V1)
2932                                 err = ERROR_FAIL;
2933                         /* fall-through */
2934                 case STLINK_MODE_DEBUG_JTAG:
2935                         if (h->version.jtag == 0)
2936                                 err = ERROR_FAIL;
2937                         break;
2938                 case STLINK_MODE_DEBUG_SWIM:
2939                         if (h->version.swim == 0)
2940                                 err = ERROR_FAIL;
2941                         break;
2942                 default:
2943                         err = ERROR_FAIL;
2944                         break;
2945         }
2946
2947         if (err != ERROR_OK) {
2948                 LOG_ERROR("mode (transport) not supported by device");
2949                 goto error_open;
2950         }
2951
2952         /* initialize the debug hardware */
2953         err = stlink_usb_init_mode(h, param->connect_under_reset, param->initial_interface_speed);
2954
2955         if (err != ERROR_OK) {
2956                 LOG_ERROR("init mode failed (unable to connect to the target)");
2957                 goto error_open;
2958         }
2959
2960         if (h->st_mode == STLINK_MODE_DEBUG_SWIM) {
2961                 err = stlink_swim_enter(h);
2962                 if (err != ERROR_OK) {
2963                         LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
2964                         goto error_open;
2965                 }
2966                 *fd = h;
2967                 h->max_mem_packet = STLINK_DATA_SIZE;
2968                 return ERROR_OK;
2969         }
2970
2971         /* get cpuid, so we can determine the max page size
2972          * start with a safe default */
2973         h->max_mem_packet = (1 << 10);
2974
2975         uint8_t buffer[4];
2976         stlink_usb_open_ap(h, 0);
2977         err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
2978         if (err == ERROR_OK) {
2979                 uint32_t cpuid = le_to_h_u32(buffer);
2980                 int i = (cpuid >> 4) & 0xf;
2981                 if (i == 4 || i == 3) {
2982                         /* Cortex-M3/M4 has 4096 bytes autoincrement range */
2983                         h->max_mem_packet = (1 << 12);
2984                 }
2985         }
2986
2987         LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
2988
2989         *fd = h;
2990
2991         return ERROR_OK;
2992
2993 error_open:
2994         stlink_usb_close(h);
2995
2996         return ERROR_FAIL;
2997 }
2998
2999 static int stlink_usb_hl_open(struct hl_interface_param_s *param, void **fd)
3000 {
3001         return stlink_usb_open(param, stlink_get_mode(param->transport), fd);
3002 }
3003
3004 int stlink_config_trace(void *handle, bool enabled,
3005                 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
3006                 unsigned int *trace_freq, unsigned int traceclkin_freq,
3007                 uint16_t *prescaler)
3008 {
3009         struct stlink_usb_handle_s *h = handle;
3010         uint16_t presc;
3011
3012         if (enabled && (!(h->version.flags & STLINK_F_HAS_TRACE) ||
3013                         pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART)) {
3014                 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
3015                 return ERROR_FAIL;
3016         }
3017
3018         if (!enabled) {
3019                 stlink_usb_trace_disable(h);
3020                 return ERROR_OK;
3021         }
3022
3023         if (*trace_freq > STLINK_TRACE_MAX_HZ) {
3024                 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
3025                           STLINK_TRACE_MAX_HZ);
3026                 return ERROR_FAIL;
3027         }
3028
3029         stlink_usb_trace_disable(h);
3030
3031         if (!*trace_freq)
3032                 *trace_freq = STLINK_TRACE_MAX_HZ;
3033
3034         presc = traceclkin_freq / *trace_freq;
3035
3036         if (traceclkin_freq % *trace_freq > 0)
3037                 presc++;
3038
3039         if (presc > TPIU_ACPR_MAX_SWOSCALER) {
3040                 LOG_ERROR("SWO frequency is not suitable. Please choose a different "
3041                         "frequency.");
3042                 return ERROR_FAIL;
3043         }
3044
3045         *prescaler = presc;
3046         h->trace.source_hz = *trace_freq;
3047
3048         return stlink_usb_trace_enable(h);
3049 }
3050
3051 /** */
3052 static int stlink_usb_init_access_port(void *handle, unsigned char ap_num)
3053 {
3054         struct stlink_usb_handle_s *h = handle;
3055
3056         assert(handle != NULL);
3057
3058         if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3059                 return ERROR_COMMAND_NOTFOUND;
3060
3061         LOG_DEBUG_IO("init ap_num = %d", ap_num);
3062         stlink_usb_init_buffer(handle, h->rx_ep, 16);
3063         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3064         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_INIT_AP;
3065         h->cmdbuf[h->cmdidx++] = ap_num;
3066
3067         return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3068 }
3069
3070 /** */
3071 static int stlink_usb_close_access_port(void *handle, unsigned char ap_num)
3072 {
3073         struct stlink_usb_handle_s *h = handle;
3074
3075         assert(handle != NULL);
3076
3077         if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3078                 return ERROR_COMMAND_NOTFOUND;
3079
3080         LOG_DEBUG_IO("close ap_num = %d", ap_num);
3081         stlink_usb_init_buffer(handle, h->rx_ep, 16);
3082         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3083         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_CLOSE_AP_DBG;
3084         h->cmdbuf[h->cmdidx++] = ap_num;
3085
3086         /* ignore incorrectly returned error on bogus FW */
3087         if (h->version.flags & STLINK_F_FIX_CLOSE_AP)
3088                 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3089         else
3090                 return stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
3091
3092 }
3093
3094 /** */
3095 static int stlink_read_dap_register(void *handle, unsigned short dap_port,
3096                         unsigned short addr, uint32_t *val)
3097 {
3098         struct stlink_usb_handle_s *h = handle;
3099         int retval;
3100
3101         assert(handle != NULL);
3102
3103         if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3104                 return ERROR_COMMAND_NOTFOUND;
3105
3106         stlink_usb_init_buffer(handle, h->rx_ep, 16);
3107         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3108         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_DAP_REG;
3109         h_u16_to_le(&h->cmdbuf[2], dap_port);
3110         h_u16_to_le(&h->cmdbuf[4], addr);
3111
3112         retval = stlink_usb_xfer_errcheck(handle, h->databuf, 8);
3113         *val = le_to_h_u32(h->databuf + 4);
3114         LOG_DEBUG_IO("dap_port_read = %d, addr =  0x%x, value = 0x%x", dap_port, addr, *val);
3115         return retval;
3116 }
3117
3118 /** */
3119 static int stlink_write_dap_register(void *handle, unsigned short dap_port,
3120                         unsigned short addr, uint32_t val)
3121 {
3122         struct stlink_usb_handle_s *h = handle;
3123
3124         assert(handle != NULL);
3125
3126         if (!(h->version.flags & STLINK_F_HAS_DAP_REG))
3127                 return ERROR_COMMAND_NOTFOUND;
3128
3129         LOG_DEBUG_IO("dap_write port = %d, addr = 0x%x, value = 0x%x", dap_port, addr, val);
3130         stlink_usb_init_buffer(handle, h->rx_ep, 16);
3131         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
3132         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITE_DAP_REG;
3133         h_u16_to_le(&h->cmdbuf[2], dap_port);
3134         h_u16_to_le(&h->cmdbuf[4], addr);
3135         h_u32_to_le(&h->cmdbuf[6], val);
3136         return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
3137 }
3138
3139 /** */
3140 struct hl_layout_api_s stlink_usb_layout_api = {
3141         /** */
3142         .open = stlink_usb_hl_open,
3143         /** */
3144         .close = stlink_usb_close,
3145         /** */
3146         .idcode = stlink_usb_idcode,
3147         /** */
3148         .state = stlink_usb_state,
3149         /** */
3150         .reset = stlink_usb_reset,
3151         /** */
3152         .assert_srst = stlink_usb_assert_srst,
3153         /** */
3154         .run = stlink_usb_run,
3155         /** */
3156         .halt = stlink_usb_halt,
3157         /** */
3158         .step = stlink_usb_step,
3159         /** */
3160         .read_regs = stlink_usb_read_regs,
3161         /** */
3162         .read_reg = stlink_usb_read_reg,
3163         /** */
3164         .write_reg = stlink_usb_write_reg,
3165         /** */
3166         .read_mem = stlink_usb_read_mem,
3167         /** */
3168         .write_mem = stlink_usb_write_mem,
3169         /** */
3170         .write_debug_reg = stlink_usb_write_debug_reg,
3171         /** */
3172         .override_target = stlink_usb_override_target,
3173         /** */
3174         .speed = stlink_speed,
3175         /** */
3176         .config_trace = stlink_config_trace,
3177         /** */
3178         .poll_trace = stlink_usb_trace_read,
3179 };
3180
3181 /*****************************************************************************
3182  * DAP direct interface
3183  */
3184
3185 static struct stlink_usb_handle_s *stlink_dap_handle;
3186 static struct hl_interface_param_s stlink_dap_param;
3187 static DECLARE_BITMAP(opened_ap, DP_APSEL_MAX + 1);
3188 static int stlink_dap_error = ERROR_OK;
3189
3190 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3191                 uint32_t *data);
3192
3193 /** */
3194 static int stlink_dap_record_error(int error)
3195 {
3196         if (stlink_dap_error == ERROR_OK)
3197                 stlink_dap_error = error;
3198         return ERROR_OK;
3199 }
3200
3201 /** */
3202 static int stlink_dap_get_and_clear_error(void)
3203 {
3204         int retval = stlink_dap_error;
3205         stlink_dap_error = ERROR_OK;
3206         return retval;
3207 }
3208
3209 static int stlink_usb_open_ap(void *handle, unsigned short apsel)
3210 {
3211         struct stlink_usb_handle_s *h = handle;
3212         int retval;
3213
3214         /* nothing to do on old versions */
3215         if (!(h->version.flags & STLINK_F_HAS_AP_INIT))
3216                 return ERROR_OK;
3217
3218         if (apsel > DP_APSEL_MAX)
3219                 return ERROR_FAIL;
3220
3221         if (test_bit(apsel, opened_ap))
3222                 return ERROR_OK;
3223
3224         retval = stlink_usb_init_access_port(h, apsel);
3225         if (retval != ERROR_OK)
3226                 return retval;
3227
3228         LOG_DEBUG("AP %d enabled", apsel);
3229         set_bit(apsel, opened_ap);
3230         return ERROR_OK;
3231 }
3232
3233 static int stlink_dap_open_ap(unsigned short apsel)
3234 {
3235         return stlink_usb_open_ap(stlink_dap_handle, apsel);
3236 }
3237
3238 /** */
3239 static int stlink_dap_closeall_ap(void)
3240 {
3241         int retval, apsel;
3242
3243         /* nothing to do on old versions */
3244         if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT))
3245                 return ERROR_OK;
3246
3247         for (apsel = 0; apsel <= DP_APSEL_MAX; apsel++) {
3248                 if (!test_bit(apsel, opened_ap))
3249                         continue;
3250                 retval = stlink_usb_close_access_port(stlink_dap_handle, apsel);
3251                 if (retval != ERROR_OK)
3252                         return retval;
3253                 clear_bit(apsel, opened_ap);
3254         }
3255         return ERROR_OK;
3256 }
3257
3258 /** */
3259 static int stlink_dap_reinit_interface(void)
3260 {
3261         int retval;
3262
3263         /*
3264          * On JTAG only, it should be enough to call stlink_usb_reset(). But on
3265          * some firmware version it does not work as expected, and there is no
3266          * equivalent for SWD.
3267          * At least for now, to reset the interface quit from JTAG/SWD mode then
3268          * select the mode again.
3269          */
3270
3271         if (!stlink_dap_handle->reconnect_pending) {
3272                 stlink_dap_handle->reconnect_pending = true;
3273                 stlink_usb_mode_leave(stlink_dap_handle, stlink_dap_handle->st_mode);
3274         }
3275
3276         retval = stlink_usb_mode_enter(stlink_dap_handle, stlink_dap_handle->st_mode);
3277         if (retval != ERROR_OK)
3278                 return retval;
3279
3280         stlink_dap_handle->reconnect_pending = false;
3281         /* on new FW, calling mode-leave closes all the opened AP; reopen them! */
3282         if (stlink_dap_handle->version.flags & STLINK_F_HAS_AP_INIT)
3283                 for (int apsel = 0; apsel <= DP_APSEL_MAX; apsel++)
3284                         if (test_bit(apsel, opened_ap)) {
3285                                 clear_bit(apsel, opened_ap);
3286                                 stlink_dap_open_ap(apsel);
3287                         }
3288         return ERROR_OK;
3289 }
3290
3291 /** */
3292 static int stlink_dap_op_connect(struct adiv5_dap *dap)
3293 {
3294         uint32_t idcode;
3295         int retval;
3296
3297         LOG_INFO("stlink_dap_op_connect(%sconnect)", dap->do_reconnect ? "re" : "");
3298
3299         /* Check if we should reset srst already when connecting, but not if reconnecting. */
3300         if (!dap->do_reconnect) {
3301                 enum reset_types jtag_reset_config = jtag_get_reset_config();
3302
3303                 if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3304                         if (jtag_reset_config & RESET_SRST_NO_GATING)
3305                                 adapter_assert_reset();
3306                         else
3307                                 LOG_WARNING("\'srst_nogate\' reset_config option is required");
3308                 }
3309         }
3310
3311         dap->do_reconnect = false;
3312         dap_invalidate_cache(dap);
3313
3314         retval = dap_dp_init(dap);
3315         if (retval != ERROR_OK) {
3316                 dap->do_reconnect = true;
3317                 return retval;
3318         }
3319
3320         retval = stlink_usb_idcode(stlink_dap_handle, &idcode);
3321         if (retval == ERROR_OK)
3322                 LOG_INFO("%s %#8.8" PRIx32,
3323                         (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) ? "JTAG IDCODE" : "SWD DPIDR",
3324                         idcode);
3325         else
3326                 dap->do_reconnect = true;
3327
3328         return retval;
3329 }
3330
3331 /** */
3332 static int stlink_dap_check_reconnect(struct adiv5_dap *dap)
3333 {
3334         int retval;
3335
3336         if (!dap->do_reconnect)
3337                 return ERROR_OK;
3338
3339         retval = stlink_dap_reinit_interface();
3340         if (retval != ERROR_OK)
3341                 return retval;
3342
3343         return stlink_dap_op_connect(dap);
3344 }
3345
3346 /** */
3347 static int stlink_dap_op_send_sequence(struct adiv5_dap *dap, enum swd_special_seq seq)
3348 {
3349         /* Ignore the request */
3350         return ERROR_OK;
3351 }
3352
3353 /** */
3354 static int stlink_dap_op_queue_dp_read(struct adiv5_dap *dap, unsigned reg,
3355                 uint32_t *data)
3356 {
3357         uint32_t dummy;
3358         int retval;
3359
3360         if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3361                 if (reg & 0x000000F0) {
3362                         LOG_ERROR("Banked DP registers not supported in current STLink FW");
3363                         return ERROR_COMMAND_NOTFOUND;
3364                 }
3365
3366         retval = stlink_dap_check_reconnect(dap);
3367         if (retval != ERROR_OK)
3368                 return retval;
3369
3370         data = data ? : &dummy;
3371         if (stlink_dap_handle->version.flags & STLINK_F_QUIRK_JTAG_DP_READ
3372                 && stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG) {
3373                 /* Quirk required in JTAG. Read RDBUFF to get the data */
3374                 retval = stlink_read_dap_register(stlink_dap_handle,
3375                                         STLINK_DEBUG_PORT_ACCESS, reg, &dummy);
3376                 if (retval == ERROR_OK)
3377                         retval = stlink_read_dap_register(stlink_dap_handle,
3378                                                 STLINK_DEBUG_PORT_ACCESS, DP_RDBUFF, data);
3379         } else {
3380                 retval = stlink_read_dap_register(stlink_dap_handle,
3381                                         STLINK_DEBUG_PORT_ACCESS, reg, data);
3382         }
3383
3384         return stlink_dap_record_error(retval);
3385 }
3386
3387 /** */
3388 static int stlink_dap_op_queue_dp_write(struct adiv5_dap *dap, unsigned reg,
3389                 uint32_t data)
3390 {
3391         int retval;
3392
3393         if (!(stlink_dap_handle->version.flags & STLINK_F_HAS_DPBANKSEL))
3394                 if (reg & 0x000000F0) {
3395                         LOG_ERROR("Banked DP registers not supported in current STLink FW");
3396                         return ERROR_COMMAND_NOTFOUND;
3397                 }
3398
3399         if (reg == DP_SELECT && (data & DP_SELECT_DPBANK) != 0) {
3400                 /* ignored if STLINK_F_HAS_DPBANKSEL, not properly managed otherwise */
3401                 LOG_DEBUG("Ignoring DPBANKSEL while write SELECT");
3402                 data &= ~DP_SELECT_DPBANK;
3403         }
3404
3405         retval = stlink_dap_check_reconnect(dap);
3406         if (retval != ERROR_OK)
3407                 return retval;
3408
3409         /* ST-Link does not like that we set CORUNDETECT */
3410         if (reg == DP_CTRL_STAT)
3411                 data &= ~CORUNDETECT;
3412
3413         retval = stlink_write_dap_register(stlink_dap_handle,
3414                                 STLINK_DEBUG_PORT_ACCESS, reg, data);
3415         return stlink_dap_record_error(retval);
3416 }
3417
3418 /** */
3419 static int stlink_dap_op_queue_ap_read(struct adiv5_ap *ap, unsigned reg,
3420                 uint32_t *data)
3421 {
3422         struct adiv5_dap *dap = ap->dap;
3423         uint32_t dummy;
3424         int retval;
3425
3426         retval = stlink_dap_check_reconnect(dap);
3427         if (retval != ERROR_OK)
3428                 return retval;
3429
3430         if (reg != AP_REG_IDR) {
3431                 retval = stlink_dap_open_ap(ap->ap_num);
3432                 if (retval != ERROR_OK)
3433                         return retval;
3434         }
3435         data = data ? : &dummy;
3436         retval = stlink_read_dap_register(stlink_dap_handle, ap->ap_num, reg,
3437                                  data);
3438         dap->stlink_flush_ap_write = false;
3439         return stlink_dap_record_error(retval);
3440 }
3441
3442 /** */
3443 static int stlink_dap_op_queue_ap_write(struct adiv5_ap *ap, unsigned reg,
3444                 uint32_t data)
3445 {
3446         struct adiv5_dap *dap = ap->dap;
3447         int retval;
3448
3449         retval = stlink_dap_check_reconnect(dap);
3450         if (retval != ERROR_OK)
3451                 return retval;
3452
3453         retval = stlink_dap_open_ap(ap->ap_num);
3454         if (retval != ERROR_OK)
3455                 return retval;
3456
3457         retval = stlink_write_dap_register(stlink_dap_handle, ap->ap_num, reg,
3458                                 data);
3459         dap->stlink_flush_ap_write = true;
3460         return stlink_dap_record_error(retval);
3461 }
3462
3463 /** */
3464 static int stlink_dap_op_queue_ap_abort(struct adiv5_dap *dap, uint8_t *ack)
3465 {
3466         LOG_WARNING("stlink_dap_op_queue_ap_abort()");
3467         return ERROR_OK;
3468 }
3469
3470 /** */
3471 static int stlink_dap_op_run(struct adiv5_dap *dap)
3472 {
3473         uint32_t ctrlstat, pwrmask;
3474         int retval, saved_retval;
3475
3476         /* Here no LOG_DEBUG. This is called continuously! */
3477
3478         /*
3479          * ST-Link returns immediately after a DAP write, without waiting for it
3480          * to complete.
3481          * Run a dummy read to DP_RDBUFF, as suggested in
3482          * http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka16363.html
3483          */
3484         if (dap->stlink_flush_ap_write) {
3485                 dap->stlink_flush_ap_write = false;
3486                 retval = stlink_dap_op_queue_dp_read(dap, DP_RDBUFF, NULL);
3487                 if (retval != ERROR_OK) {
3488                         dap->do_reconnect = true;
3489                         return retval;
3490                 }
3491         }
3492
3493         saved_retval = stlink_dap_get_and_clear_error();
3494
3495         retval = stlink_dap_op_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
3496         if (retval != ERROR_OK) {
3497                 dap->do_reconnect = true;
3498                 return retval;
3499         }
3500         retval = stlink_dap_get_and_clear_error();
3501         if (retval != ERROR_OK) {
3502                 LOG_ERROR("Fail reading CTRL/STAT register. Force reconnect");
3503                 dap->do_reconnect = true;
3504                 return retval;
3505         }
3506
3507         if (ctrlstat & SSTICKYERR) {
3508                 if (stlink_dap_handle->st_mode == STLINK_MODE_DEBUG_JTAG)
3509                         retval = stlink_dap_op_queue_dp_write(dap, DP_CTRL_STAT,
3510                                         ctrlstat & (dap->dp_ctrl_stat | SSTICKYERR));
3511                 else
3512                         retval = stlink_dap_op_queue_dp_write(dap, DP_ABORT, STKERRCLR);
3513                 if (retval != ERROR_OK) {
3514                         dap->do_reconnect = true;
3515                         return retval;
3516                 }
3517                 retval = stlink_dap_get_and_clear_error();
3518                 if (retval != ERROR_OK) {
3519                         dap->do_reconnect = true;
3520                         return retval;
3521                 }
3522         }
3523
3524         /* check for power lost */
3525         pwrmask = dap->dp_ctrl_stat & (CDBGPWRUPREQ | CSYSPWRUPREQ);
3526         if ((ctrlstat & pwrmask) != pwrmask)
3527                 dap->do_reconnect = true;
3528
3529         return saved_retval;
3530 }
3531
3532 /** */
3533 static void stlink_dap_op_quit(struct adiv5_dap *dap)
3534 {
3535         int retval;
3536
3537         retval = stlink_dap_closeall_ap();
3538         if (retval != ERROR_OK)
3539                 LOG_ERROR("Error closing APs");
3540 }
3541
3542 static int stlink_swim_op_srst(void)
3543 {
3544         return stlink_swim_generate_rst(stlink_dap_handle);
3545 }
3546
3547 static int stlink_swim_op_read_mem(uint32_t addr, uint32_t size,
3548                                                                    uint32_t count, uint8_t *buffer)
3549 {
3550         int retval;
3551         uint32_t bytes_remaining;
3552
3553         LOG_DEBUG_IO("read at 0x%08x len %d*0x%08x", addr, size, count);
3554         count *= size;
3555
3556         while (count) {
3557                 bytes_remaining = (count > STLINK_DATA_SIZE) ? STLINK_DATA_SIZE : count;
3558                 retval = stlink_swim_readbytes(stlink_dap_handle, addr, bytes_remaining, buffer);
3559                 if (retval != ERROR_OK)
3560                         return retval;
3561
3562                 buffer += bytes_remaining;
3563                 addr += bytes_remaining;
3564                 count -= bytes_remaining;
3565         }
3566
3567         return ERROR_OK;
3568 }
3569
3570 static int stlink_swim_op_write_mem(uint32_t addr, uint32_t size,
3571                                                                         uint32_t count, const uint8_t *buffer)
3572 {
3573         int retval;
3574         uint32_t bytes_remaining;
3575
3576         LOG_DEBUG_IO("write at 0x%08x len %d*0x%08x", addr, size, count);
3577         count *= size;
3578
3579         while (count) {
3580                 bytes_remaining = (count > STLINK_DATA_SIZE) ? STLINK_DATA_SIZE : count;
3581                 retval = stlink_swim_writebytes(stlink_dap_handle, addr, bytes_remaining, buffer);
3582                 if (retval != ERROR_OK)
3583                         return retval;
3584
3585                 buffer += bytes_remaining;
3586                 addr += bytes_remaining;
3587                 count -= bytes_remaining;
3588         }
3589
3590         return ERROR_OK;
3591 }
3592
3593 static int stlink_swim_op_reconnect(void)
3594 {
3595         int retval;
3596
3597         retval = stlink_usb_mode_enter(stlink_dap_handle, STLINK_MODE_DEBUG_SWIM);
3598         if (retval != ERROR_OK)
3599                 return retval;
3600
3601         return stlink_swim_resync(stlink_dap_handle);
3602 }
3603
3604 static int stlink_dap_config_trace(bool enabled,
3605                 enum tpiu_pin_protocol pin_protocol, uint32_t port_size,
3606                 unsigned int *trace_freq, unsigned int traceclkin_freq,
3607                 uint16_t *prescaler)
3608 {
3609         return stlink_config_trace(stlink_dap_handle, enabled, pin_protocol,
3610                                                            port_size, trace_freq, traceclkin_freq,
3611                                                            prescaler);
3612 }
3613
3614 static int stlink_dap_trace_read(uint8_t *buf, size_t *size)
3615 {
3616         return stlink_usb_trace_read(stlink_dap_handle, buf, size);
3617 }
3618
3619 /** */
3620 COMMAND_HANDLER(stlink_dap_serial_command)
3621 {
3622         LOG_DEBUG("stlink_dap_serial_command");
3623
3624         if (CMD_ARGC != 1) {
3625                 LOG_ERROR("Expected exactly one argument for \"st-link serial <serial-number>\".");
3626                 return ERROR_COMMAND_SYNTAX_ERROR;
3627         }
3628
3629         if (stlink_dap_param.serial) {
3630                 LOG_WARNING("Command \"st-link serial\" already used. Replacing previous value");
3631                 free((void *)stlink_dap_param.serial);
3632         }
3633
3634         stlink_dap_param.serial = strdup(CMD_ARGV[0]);
3635         return ERROR_OK;
3636 }
3637
3638 /** */
3639 COMMAND_HANDLER(stlink_dap_vid_pid)
3640 {
3641         unsigned int i, max_usb_ids = HLA_MAX_USB_IDS;
3642
3643         if (CMD_ARGC > max_usb_ids * 2) {
3644                 LOG_WARNING("ignoring extra IDs in vid_pid "
3645                         "(maximum is %d pairs)", max_usb_ids);
3646                 CMD_ARGC = max_usb_ids * 2;
3647         }
3648         if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
3649                 LOG_WARNING("incomplete vid_pid configuration directive");
3650                 return ERROR_COMMAND_SYNTAX_ERROR;
3651         }
3652         for (i = 0; i < CMD_ARGC; i += 2) {
3653                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], stlink_dap_param.vid[i / 2]);
3654                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], stlink_dap_param.pid[i / 2]);
3655         }
3656
3657         /* null termination */
3658         stlink_dap_param.vid[i / 2] = stlink_dap_param.pid[i / 2] = 0;
3659
3660         return ERROR_OK;
3661 }
3662
3663 /** */
3664 static const struct command_registration stlink_dap_subcommand_handlers[] = {
3665         {
3666                 .name = "serial",
3667                 .handler = stlink_dap_serial_command,
3668                 .mode = COMMAND_CONFIG,
3669                 .help = "set the serial number of the adapter",
3670                 .usage = "<serial_number>",
3671         },
3672         {
3673                 .name = "vid_pid",
3674                 .handler = stlink_dap_vid_pid,
3675                 .mode = COMMAND_CONFIG,
3676                 .help = "USB VID and PID of the adapter",
3677                 .usage = "(vid pid)+",
3678         },
3679         COMMAND_REGISTRATION_DONE
3680 };
3681
3682 /** */
3683 static const struct command_registration stlink_dap_command_handlers[] = {
3684         {
3685                 .name = "st-link",
3686                 .mode = COMMAND_ANY,
3687                 .help = "perform st-link management",
3688                 .chain = stlink_dap_subcommand_handlers,
3689                 .usage = "",
3690         },
3691         COMMAND_REGISTRATION_DONE
3692 };
3693
3694 /** */
3695 static int stlink_dap_init(void)
3696 {
3697         enum reset_types jtag_reset_config = jtag_get_reset_config();
3698         enum stlink_mode mode;
3699         int retval;
3700
3701         LOG_DEBUG("stlink_dap_init()");
3702
3703         if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
3704                 if (jtag_reset_config & RESET_SRST_NO_GATING)
3705                         stlink_dap_param.connect_under_reset = true;
3706                 else
3707                         LOG_WARNING("\'srst_nogate\' reset_config option is required");
3708         }
3709
3710         if (transport_is_dapdirect_swd())
3711                 mode = STLINK_MODE_DEBUG_SWD;
3712         else if (transport_is_dapdirect_jtag())
3713                 mode = STLINK_MODE_DEBUG_JTAG;
3714         else if (transport_is_swim())
3715                 mode = STLINK_MODE_DEBUG_SWIM;
3716         else {
3717                 LOG_ERROR("Unsupported transport");
3718                 return ERROR_FAIL;
3719         }
3720
3721         retval = stlink_usb_open(&stlink_dap_param, mode, (void **)&stlink_dap_handle);
3722         if (retval != ERROR_OK)
3723                 return retval;
3724
3725         if ((mode != STLINK_MODE_DEBUG_SWIM) &&
3726                 !(stlink_dap_handle->version.flags & STLINK_F_HAS_DAP_REG)) {
3727                 LOG_ERROR("ST-Link version does not support DAP direct transport");
3728                 return ERROR_FAIL;
3729         }
3730         return ERROR_OK;
3731 }
3732
3733 /** */
3734 static int stlink_dap_quit(void)
3735 {
3736         LOG_DEBUG("stlink_dap_quit()");
3737
3738         free((void *)stlink_dap_param.serial);
3739         stlink_dap_param.serial = NULL;
3740
3741         return stlink_usb_close(stlink_dap_handle);
3742 }
3743
3744 /** */
3745 static int stlink_dap_reset(int req_trst, int req_srst)
3746 {
3747         LOG_DEBUG("stlink_dap_reset(%d)", req_srst);
3748         return stlink_usb_assert_srst(stlink_dap_handle,
3749                 req_srst ? STLINK_DEBUG_APIV2_DRIVE_NRST_LOW
3750                                  : STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH);
3751 }
3752
3753 /** */
3754 static int stlink_dap_speed(int speed)
3755 {
3756         if (speed == 0) {
3757                 LOG_ERROR("RTCK not supported. Set nonzero adapter_khz.");
3758                 return ERROR_JTAG_NOT_IMPLEMENTED;
3759         }
3760
3761         stlink_dap_param.initial_interface_speed = speed;
3762         stlink_speed(stlink_dap_handle, speed, false);
3763         return ERROR_OK;
3764 }
3765
3766 /** */
3767 static int stlink_dap_khz(int khz, int *jtag_speed)
3768 {
3769         if (khz == 0) {
3770                 LOG_ERROR("RCLK not supported");
3771                 return ERROR_FAIL;
3772         }
3773
3774         *jtag_speed = stlink_speed(stlink_dap_handle, khz, true);
3775         return ERROR_OK;
3776 }
3777
3778 /** */
3779 static int stlink_dap_speed_div(int speed, int *khz)
3780 {
3781         *khz = speed;
3782         return ERROR_OK;
3783 }
3784
3785 static const struct dap_ops stlink_dap_ops = {
3786         .connect = stlink_dap_op_connect,
3787         .send_sequence = stlink_dap_op_send_sequence,
3788         .queue_dp_read = stlink_dap_op_queue_dp_read,
3789         .queue_dp_write = stlink_dap_op_queue_dp_write,
3790         .queue_ap_read = stlink_dap_op_queue_ap_read,
3791         .queue_ap_write = stlink_dap_op_queue_ap_write,
3792         .queue_ap_abort = stlink_dap_op_queue_ap_abort,
3793         .run = stlink_dap_op_run,
3794         .sync = NULL, /* optional */
3795         .quit = stlink_dap_op_quit, /* optional */
3796 };
3797
3798 static const struct swim_driver stlink_swim_ops = {
3799         .srst = stlink_swim_op_srst,
3800         .read_mem = stlink_swim_op_read_mem,
3801         .write_mem = stlink_swim_op_write_mem,
3802         .reconnect = stlink_swim_op_reconnect,
3803 };
3804
3805 static const char *const stlink_dap_transport[] = { "dapdirect_swd", "dapdirect_jtag", "swim", NULL };
3806
3807 struct adapter_driver stlink_dap_adapter_driver = {
3808         .name = "st-link",
3809         .transports = stlink_dap_transport,
3810         .commands = stlink_dap_command_handlers,
3811
3812         .init = stlink_dap_init,
3813         .quit = stlink_dap_quit,
3814         .reset = stlink_dap_reset,
3815         .speed = stlink_dap_speed,
3816         .khz = stlink_dap_khz,
3817         .speed_div = stlink_dap_speed_div,
3818         .config_trace = stlink_dap_config_trace,
3819         .poll_trace = stlink_dap_trace_read,
3820
3821         .dap_jtag_ops = &stlink_dap_ops,
3822         .dap_swd_ops = &stlink_dap_ops,
3823         .swim_ops = &stlink_swim_ops,
3824 };