stlink: Set speed before entering JTAG/SWD mode
[fw/openocd] / src / jtag / drivers / stlink_usb.c
1 /***************************************************************************
2  *   SWIM contributions by Ake Rehnman                                     *
3  *   Copyright (C) 2017  Ake Rehnman                                       *
4  *   ake.rehnman(at)gmail.com                                              *
5  *                                                                         *
6  *   Copyright (C) 2011-2012 by Mathias Kuester                            *
7  *   Mathias Kuester <kesmtp@freenet.de>                                   *
8  *                                                                         *
9  *   Copyright (C) 2012 by Spencer Oliver                                  *
10  *   spen@spen-soft.co.uk                                                  *
11  *                                                                         *
12  *   This code is based on https://github.com/texane/stlink                *
13  *                                                                         *
14  *   This program is free software; you can redistribute it and/or modify  *
15  *   it under the terms of the GNU General Public License as published by  *
16  *   the Free Software Foundation; either version 2 of the License, or     *
17  *   (at your option) any later version.                                   *
18  *                                                                         *
19  *   This program is distributed in the hope that it will be useful,       *
20  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
21  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
22  *   GNU General Public License for more details.                          *
23  *                                                                         *
24  *   You should have received a copy of the GNU General Public License     *
25  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
26  ***************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 /* project specific includes */
33 #include <helper/binarybuffer.h>
34 #include <jtag/interface.h>
35 #include <jtag/hla/hla_layout.h>
36 #include <jtag/hla/hla_transport.h>
37 #include <jtag/hla/hla_interface.h>
38 #include <target/target.h>
39
40 #include <target/cortex_m.h>
41
42 #include "libusb_common.h"
43
44 #ifdef HAVE_LIBUSB1
45 #define USE_LIBUSB_ASYNCIO
46 #endif
47
48 #define ENDPOINT_IN  0x80
49 #define ENDPOINT_OUT 0x00
50
51 #define STLINK_WRITE_TIMEOUT 1000
52 #define STLINK_READ_TIMEOUT 1000
53
54 #define STLINK_NULL_EP        0
55 #define STLINK_RX_EP          (1|ENDPOINT_IN)
56 #define STLINK_TX_EP          (2|ENDPOINT_OUT)
57 #define STLINK_TRACE_EP       (3|ENDPOINT_IN)
58
59 #define STLINK_V2_1_TX_EP     (1|ENDPOINT_OUT)
60 #define STLINK_V2_1_TRACE_EP  (2|ENDPOINT_IN)
61
62 #define STLINK_SG_SIZE        (31)
63 #define STLINK_DATA_SIZE      (4096)
64 #define STLINK_CMD_SIZE_V2    (16)
65 #define STLINK_CMD_SIZE_V1    (10)
66
67 #define STLINK_V1_PID         (0x3744)
68 #define STLINK_V2_PID         (0x3748)
69 #define STLINK_V2_1_PID       (0x374B)
70 #define STLINK_V2_1_NO_MSD_PID  (0x3752)
71 #define STLINK_V3_USBLOADER_PID (0x374D)
72 #define STLINK_V3E_PID          (0x374E)
73 #define STLINK_V3S_PID          (0x374F)
74 #define STLINK_V3_2VCP_PID      (0x3753)
75
76 /*
77  * ST-Link/V1, ST-Link/V2 and ST-Link/V2.1 are full-speed USB devices and
78  * this limits the bulk packet size and the 8bit read/writes to max 64 bytes.
79  * STLINK-V3 is a high speed USB 2.0 and the limit is 512 bytes.
80  */
81 #define STLINK_MAX_RW8          (64)
82 #define STLINKV3_MAX_RW8        (512)
83
84 /* "WAIT" responses will be retried (with exponential backoff) at
85  * most this many times before failing to caller.
86  */
87 #define MAX_WAIT_RETRIES 8
88
89 enum stlink_jtag_api_version {
90         STLINK_JTAG_API_V1 = 1,
91         STLINK_JTAG_API_V2,
92         STLINK_JTAG_API_V3,
93 };
94
95 /** */
96 struct stlink_usb_version {
97         /** */
98         int stlink;
99         /** */
100         int jtag;
101         /** */
102         int swim;
103         /** jtag api version supported */
104         enum stlink_jtag_api_version jtag_api;
105         /** one bit for each feature supported. See macros STLINK_F_* */
106         uint32_t flags;
107 };
108
109 /** */
110 struct stlink_usb_handle_s {
111         /** */
112         struct jtag_libusb_device_handle *fd;
113         /** */
114         struct libusb_transfer *trans;
115         /** */
116         uint8_t rx_ep;
117         /** */
118         uint8_t tx_ep;
119         /** */
120         uint8_t trace_ep;
121         /** */
122         uint8_t cmdbuf[STLINK_SG_SIZE];
123         /** */
124         uint8_t cmdidx;
125         /** */
126         uint8_t direction;
127         /** */
128         uint8_t databuf[STLINK_DATA_SIZE];
129         /** */
130         uint32_t max_mem_packet;
131         /** */
132         enum hl_transports transport;
133         /** */
134         struct stlink_usb_version version;
135         /** */
136         uint16_t vid;
137         /** */
138         uint16_t pid;
139         /** */
140         struct {
141                 /** whether SWO tracing is enabled or not */
142                 bool enabled;
143                 /** trace module source clock */
144                 uint32_t source_hz;
145         } trace;
146         /** reconnect is needed next time we try to query the
147          * status */
148         bool reconnect_pending;
149 };
150
151 #define STLINK_SWIM_ERR_OK             0x00
152 #define STLINK_SWIM_BUSY               0x01
153 #define STLINK_DEBUG_ERR_OK            0x80
154 #define STLINK_DEBUG_ERR_FAULT         0x81
155 #define STLINK_SWD_AP_WAIT             0x10
156 #define STLINK_SWD_AP_FAULT            0x11
157 #define STLINK_SWD_AP_ERROR            0x12
158 #define STLINK_SWD_AP_PARITY_ERROR     0x13
159 #define STLINK_JTAG_GET_IDCODE_ERROR   0x09
160 #define STLINK_JTAG_WRITE_ERROR        0x0c
161 #define STLINK_JTAG_WRITE_VERIF_ERROR  0x0d
162 #define STLINK_SWD_DP_WAIT             0x14
163 #define STLINK_SWD_DP_FAULT            0x15
164 #define STLINK_SWD_DP_ERROR            0x16
165 #define STLINK_SWD_DP_PARITY_ERROR     0x17
166
167 #define STLINK_SWD_AP_WDATA_ERROR      0x18
168 #define STLINK_SWD_AP_STICKY_ERROR     0x19
169 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
170
171 #define STLINK_BAD_AP_ERROR            0x1d
172
173 #define STLINK_CORE_RUNNING            0x80
174 #define STLINK_CORE_HALTED             0x81
175 #define STLINK_CORE_STAT_UNKNOWN       -1
176
177 #define STLINK_GET_VERSION             0xF1
178 #define STLINK_DEBUG_COMMAND           0xF2
179 #define STLINK_DFU_COMMAND             0xF3
180 #define STLINK_SWIM_COMMAND            0xF4
181 #define STLINK_GET_CURRENT_MODE        0xF5
182 #define STLINK_GET_TARGET_VOLTAGE      0xF7
183
184 #define STLINK_DEV_DFU_MODE            0x00
185 #define STLINK_DEV_MASS_MODE           0x01
186 #define STLINK_DEV_DEBUG_MODE          0x02
187 #define STLINK_DEV_SWIM_MODE           0x03
188 #define STLINK_DEV_BOOTLOADER_MODE     0x04
189 #define STLINK_DEV_UNKNOWN_MODE        -1
190
191 #define STLINK_DFU_EXIT                0x07
192
193 /*
194         STLINK_SWIM_ENTER_SEQ
195         1.3ms low then 750Hz then 1.5kHz
196
197         STLINK_SWIM_GEN_RST
198         STM8 DM pulls reset pin low 50us
199
200         STLINK_SWIM_SPEED
201         uint8_t (0=low|1=high)
202
203         STLINK_SWIM_WRITEMEM
204         uint16_t length
205         uint32_t address
206
207         STLINK_SWIM_RESET
208         send syncronization seq (16us low, response 64 clocks low)
209 */
210 #define STLINK_SWIM_ENTER                  0x00
211 #define STLINK_SWIM_EXIT                   0x01
212 #define STLINK_SWIM_READ_CAP               0x02
213 #define STLINK_SWIM_SPEED                  0x03
214 #define STLINK_SWIM_ENTER_SEQ              0x04
215 #define STLINK_SWIM_GEN_RST                0x05
216 #define STLINK_SWIM_RESET                  0x06
217 #define STLINK_SWIM_ASSERT_RESET           0x07
218 #define STLINK_SWIM_DEASSERT_RESET         0x08
219 #define STLINK_SWIM_READSTATUS             0x09
220 #define STLINK_SWIM_WRITEMEM               0x0a
221 #define STLINK_SWIM_READMEM                0x0b
222 #define STLINK_SWIM_READBUF                0x0c
223
224 #define STLINK_DEBUG_GETSTATUS             0x01
225 #define STLINK_DEBUG_FORCEDEBUG            0x02
226 #define STLINK_DEBUG_APIV1_RESETSYS        0x03
227 #define STLINK_DEBUG_APIV1_READALLREGS     0x04
228 #define STLINK_DEBUG_APIV1_READREG         0x05
229 #define STLINK_DEBUG_APIV1_WRITEREG        0x06
230 #define STLINK_DEBUG_READMEM_32BIT         0x07
231 #define STLINK_DEBUG_WRITEMEM_32BIT        0x08
232 #define STLINK_DEBUG_RUNCORE               0x09
233 #define STLINK_DEBUG_STEPCORE              0x0a
234 #define STLINK_DEBUG_APIV1_SETFP           0x0b
235 #define STLINK_DEBUG_READMEM_8BIT          0x0c
236 #define STLINK_DEBUG_WRITEMEM_8BIT         0x0d
237 #define STLINK_DEBUG_APIV1_CLEARFP         0x0e
238 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG   0x0f
239 #define STLINK_DEBUG_APIV1_SETWATCHPOINT   0x10
240
241 #define STLINK_DEBUG_ENTER_JTAG_RESET      0x00
242 #define STLINK_DEBUG_ENTER_SWD_NO_RESET    0xa3
243 #define STLINK_DEBUG_ENTER_JTAG_NO_RESET   0xa4
244
245 #define STLINK_DEBUG_APIV1_ENTER           0x20
246 #define STLINK_DEBUG_EXIT                  0x21
247 #define STLINK_DEBUG_READCOREID            0x22
248
249 #define STLINK_DEBUG_APIV2_ENTER           0x30
250 #define STLINK_DEBUG_APIV2_READ_IDCODES    0x31
251 #define STLINK_DEBUG_APIV2_RESETSYS        0x32
252 #define STLINK_DEBUG_APIV2_READREG         0x33
253 #define STLINK_DEBUG_APIV2_WRITEREG        0x34
254 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG   0x35
255 #define STLINK_DEBUG_APIV2_READDEBUGREG    0x36
256
257 #define STLINK_DEBUG_APIV2_READALLREGS     0x3A
258 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
259 #define STLINK_DEBUG_APIV2_DRIVE_NRST      0x3C
260
261 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS2 0x3E
262
263 #define STLINK_DEBUG_APIV2_START_TRACE_RX  0x40
264 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX   0x41
265 #define STLINK_DEBUG_APIV2_GET_TRACE_NB    0x42
266 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ    0x43
267 #define STLINK_DEBUG_APIV2_JTAG_SET_FREQ   0x44
268
269 #define STLINK_DEBUG_APIV2_READMEM_16BIT   0x47
270 #define STLINK_DEBUG_APIV2_WRITEMEM_16BIT  0x48
271
272 #define STLINK_APIV3_SET_COM_FREQ           0x61
273 #define STLINK_APIV3_GET_COM_FREQ           0x62
274
275 #define STLINK_APIV3_GET_VERSION_EX         0xFB
276
277 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW   0x00
278 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH  0x01
279 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
280
281 #define STLINK_TRACE_SIZE               4096
282 #define STLINK_TRACE_MAX_HZ             2000000
283
284 #define STLINK_V3_MAX_FREQ_NB               10
285
286 /** */
287 enum stlink_mode {
288         STLINK_MODE_UNKNOWN = 0,
289         STLINK_MODE_DFU,
290         STLINK_MODE_MASS,
291         STLINK_MODE_DEBUG_JTAG,
292         STLINK_MODE_DEBUG_SWD,
293         STLINK_MODE_DEBUG_SWIM
294 };
295
296 #define REQUEST_SENSE        0x03
297 #define REQUEST_SENSE_LENGTH 18
298
299 /*
300  * Map the relevant features, quirks and workaround for specific firmware
301  * version of stlink
302  */
303 #define STLINK_F_HAS_TRACE              (1UL << 0)
304 #define STLINK_F_HAS_SWD_SET_FREQ       (1UL << 1)
305 #define STLINK_F_HAS_JTAG_SET_FREQ      (1UL << 2)
306 #define STLINK_F_HAS_MEM_16BIT          (1UL << 3)
307 #define STLINK_F_HAS_GETLASTRWSTATUS2   (1UL << 4)
308
309 /* aliases */
310 #define STLINK_F_HAS_TARGET_VOLT        STLINK_F_HAS_TRACE
311
312 struct speed_map {
313         int speed;
314         int speed_divisor;
315 };
316
317 /* SWD clock speed */
318 static const struct speed_map stlink_khz_to_speed_map_swd[] = {
319         {4000, 0},
320         {1800, 1}, /* default */
321         {1200, 2},
322         {950,  3},
323         {480,  7},
324         {240, 15},
325         {125, 31},
326         {100, 40},
327         {50,  79},
328         {25, 158},
329         {15, 265},
330         {5,  798}
331 };
332
333 /* JTAG clock speed */
334 static const struct speed_map stlink_khz_to_speed_map_jtag[] = {
335         {18000, 2},
336         {9000,  4},
337         {4500,  8},
338         {2250, 16},
339         {1125, 32}, /* default */
340         {562,  64},
341         {281, 128},
342         {140, 256}
343 };
344
345 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
346 static int stlink_swim_status(void *handle);
347 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size);
348 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map);
349 static int stlink_speed(void *handle, int khz, bool query);
350
351 /** */
352 static unsigned int stlink_usb_block(void *handle)
353 {
354         struct stlink_usb_handle_s *h = handle;
355
356         assert(handle != NULL);
357
358         if (h->version.stlink == 3)
359                 return STLINKV3_MAX_RW8;
360         else
361                 return STLINK_MAX_RW8;
362 }
363
364
365
366 #ifdef USE_LIBUSB_ASYNCIO
367
368 static LIBUSB_CALL void sync_transfer_cb(struct libusb_transfer *transfer)
369 {
370         int *completed = transfer->user_data;
371         *completed = 1;
372         /* caller interprets result and frees transfer */
373 }
374
375
376 static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
377 {
378         int r, *completed = transfer->user_data;
379
380         /* Assuming a single libusb context exists.  There no existing interface into this
381          * module to pass a libusb context.
382          */
383         struct libusb_context *ctx = NULL;
384
385         while (!*completed) {
386                 r = libusb_handle_events_completed(ctx, completed);
387                 if (r < 0) {
388                         if (r == LIBUSB_ERROR_INTERRUPTED)
389                                 continue;
390                         libusb_cancel_transfer(transfer);
391                         continue;
392                 }
393         }
394 }
395
396
397 static int transfer_error_status(const struct libusb_transfer *transfer)
398 {
399         int r = 0;
400
401         switch (transfer->status) {
402                 case LIBUSB_TRANSFER_COMPLETED:
403                         r = 0;
404                         break;
405                 case LIBUSB_TRANSFER_TIMED_OUT:
406                         r = LIBUSB_ERROR_TIMEOUT;
407                         break;
408                 case LIBUSB_TRANSFER_STALL:
409                         r = LIBUSB_ERROR_PIPE;
410                         break;
411                 case LIBUSB_TRANSFER_OVERFLOW:
412                         r = LIBUSB_ERROR_OVERFLOW;
413                         break;
414                 case LIBUSB_TRANSFER_NO_DEVICE:
415                         r = LIBUSB_ERROR_NO_DEVICE;
416                         break;
417                 case LIBUSB_TRANSFER_ERROR:
418                 case LIBUSB_TRANSFER_CANCELLED:
419                         r = LIBUSB_ERROR_IO;
420                         break;
421                 default:
422                         r = LIBUSB_ERROR_OTHER;
423                         break;
424         }
425
426         return r;
427 }
428
429 struct jtag_xfer {
430         int ep;
431         uint8_t *buf;
432         size_t size;
433         /* Internal */
434         int retval;
435         int completed;
436         size_t transfer_size;
437         struct libusb_transfer *transfer;
438 };
439
440 static int jtag_libusb_bulk_transfer_n(
441                 jtag_libusb_device_handle * dev_handle,
442                 struct jtag_xfer *transfers,
443                 size_t n_transfers,
444                 int timeout)
445 {
446         int retval = 0;
447         int returnval = ERROR_OK;
448
449
450         for (size_t i = 0; i < n_transfers; ++i) {
451                 transfers[i].retval = 0;
452                 transfers[i].completed = 0;
453                 transfers[i].transfer_size = 0;
454                 transfers[i].transfer = libusb_alloc_transfer(0);
455
456                 if (transfers[i].transfer == NULL) {
457                         for (size_t j = 0; j < i; ++j)
458                                 libusb_free_transfer(transfers[j].transfer);
459
460                         LOG_DEBUG("ERROR, failed to alloc usb transfers");
461                         for (size_t k = 0; k < n_transfers; ++k)
462                                 transfers[k].retval = LIBUSB_ERROR_NO_MEM;
463                         return ERROR_FAIL;
464                 }
465         }
466
467         for (size_t i = 0; i < n_transfers; ++i) {
468                 libusb_fill_bulk_transfer(
469                                 transfers[i].transfer,
470                                 dev_handle,
471                                 transfers[i].ep, transfers[i].buf, transfers[i].size,
472                                 sync_transfer_cb, &transfers[i].completed, timeout);
473                 transfers[i].transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
474
475                 retval = libusb_submit_transfer(transfers[i].transfer);
476                 if (retval < 0) {
477                         LOG_DEBUG("ERROR, failed to submit transfer %zu, error %d", i, retval);
478
479                         /* Probably no point continuing to submit transfers once a submission fails.
480                          * As a result, tag all remaining transfers as errors.
481                          */
482                         for (size_t j = i; j < n_transfers; ++j)
483                                 transfers[j].retval = retval;
484
485                         returnval = ERROR_FAIL;
486                         break;
487                 }
488         }
489
490         /* Wait for every submitted USB transfer to complete.
491         */
492         for (size_t i = 0; i < n_transfers; ++i) {
493                 if (transfers[i].retval == 0) {
494                         sync_transfer_wait_for_completion(transfers[i].transfer);
495
496                         retval = transfer_error_status(transfers[i].transfer);
497                         if (retval) {
498                                 returnval = ERROR_FAIL;
499                                 transfers[i].retval = retval;
500                                 LOG_DEBUG("ERROR, transfer %zu failed, error %d", i, retval);
501                         } else {
502                                 /* Assuming actual_length is only valid if there is no transfer error.
503                                  */
504                                 transfers[i].transfer_size = transfers[i].transfer->actual_length;
505                         }
506                 }
507
508                 libusb_free_transfer(transfers[i].transfer);
509                 transfers[i].transfer = NULL;
510         }
511
512         return returnval;
513 }
514
515 #endif
516
517
518 /** */
519 static int stlink_usb_xfer_v1_get_status(void *handle)
520 {
521         struct stlink_usb_handle_s *h = handle;
522
523         assert(handle != NULL);
524
525         /* read status */
526         memset(h->cmdbuf, 0, STLINK_SG_SIZE);
527
528         if (jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)h->cmdbuf,
529                         13, STLINK_READ_TIMEOUT) != 13)
530                 return ERROR_FAIL;
531
532         uint32_t t1;
533
534         t1 = buf_get_u32(h->cmdbuf, 0, 32);
535
536         /* check for USBS */
537         if (t1 != 0x53425355)
538                 return ERROR_FAIL;
539         /*
540          * CSW status:
541          * 0 success
542          * 1 command failure
543          * 2 phase error
544          */
545         if (h->cmdbuf[12] != 0)
546                 return ERROR_FAIL;
547
548         return ERROR_OK;
549 }
550
551 #ifdef USE_LIBUSB_ASYNCIO
552 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
553 {
554         struct stlink_usb_handle_s *h = handle;
555
556         assert(handle != NULL);
557
558         size_t n_transfers = 0;
559         struct jtag_xfer transfers[2];
560
561         memset(transfers, 0, sizeof(transfers));
562
563         transfers[0].ep = h->tx_ep;
564         transfers[0].buf = h->cmdbuf;
565         transfers[0].size = cmdsize;
566
567         ++n_transfers;
568
569         if (h->direction == h->tx_ep && size) {
570                 transfers[1].ep = h->tx_ep;
571                 transfers[1].buf = (uint8_t *)buf;
572                 transfers[1].size = size;
573
574                 ++n_transfers;
575         } else if (h->direction == h->rx_ep && size) {
576                 transfers[1].ep = h->rx_ep;
577                 transfers[1].buf = (uint8_t *)buf;
578                 transfers[1].size = size;
579
580                 ++n_transfers;
581         }
582
583         return jtag_libusb_bulk_transfer_n(
584                         h->fd,
585                         transfers,
586                         n_transfers,
587                         STLINK_WRITE_TIMEOUT);
588 }
589 #else
590 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
591 {
592         struct stlink_usb_handle_s *h = handle;
593
594         assert(handle != NULL);
595
596         if (jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)h->cmdbuf, cmdsize,
597                         STLINK_WRITE_TIMEOUT) != cmdsize) {
598                 return ERROR_FAIL;
599         }
600
601         if (h->direction == h->tx_ep && size) {
602                 if (jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)buf,
603                                 size, STLINK_WRITE_TIMEOUT) != size) {
604                         LOG_DEBUG("bulk write failed");
605                         return ERROR_FAIL;
606                 }
607         } else if (h->direction == h->rx_ep && size) {
608                 if (jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)buf,
609                                 size, STLINK_READ_TIMEOUT) != size) {
610                         LOG_DEBUG("bulk read failed");
611                         return ERROR_FAIL;
612                 }
613         }
614
615         return ERROR_OK;
616 }
617 #endif
618
619 /** */
620 static int stlink_usb_xfer_v1_get_sense(void *handle)
621 {
622         int res;
623         struct stlink_usb_handle_s *h = handle;
624
625         assert(handle != NULL);
626
627         stlink_usb_init_buffer(handle, h->rx_ep, 16);
628
629         h->cmdbuf[h->cmdidx++] = REQUEST_SENSE;
630         h->cmdbuf[h->cmdidx++] = 0;
631         h->cmdbuf[h->cmdidx++] = 0;
632         h->cmdbuf[h->cmdidx++] = 0;
633         h->cmdbuf[h->cmdidx++] = REQUEST_SENSE_LENGTH;
634
635         res = stlink_usb_xfer_rw(handle, REQUEST_SENSE_LENGTH, h->databuf, 16);
636
637         if (res != ERROR_OK)
638                 return res;
639
640         if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK)
641                 return ERROR_FAIL;
642
643         return ERROR_OK;
644 }
645
646 /*
647         transfers block in cmdbuf
648         <size> indicates number of bytes in the following
649         data phase.
650         Ignore the (eventual) error code in the received packet.
651 */
652 static int stlink_usb_xfer_noerrcheck(void *handle, const uint8_t *buf, int size)
653 {
654         int err, cmdsize = STLINK_CMD_SIZE_V2;
655         struct stlink_usb_handle_s *h = handle;
656
657         assert(handle != NULL);
658
659         if (h->version.stlink == 1) {
660                 cmdsize = STLINK_SG_SIZE;
661                 /* put length in bCBWCBLength */
662                 h->cmdbuf[14] = h->cmdidx-15;
663         }
664
665         err = stlink_usb_xfer_rw(handle, cmdsize, buf, size);
666
667         if (err != ERROR_OK)
668                 return err;
669
670         if (h->version.stlink == 1) {
671                 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK) {
672                         /* check csw status */
673                         if (h->cmdbuf[12] == 1) {
674                                 LOG_DEBUG("get sense");
675                                 if (stlink_usb_xfer_v1_get_sense(handle) != ERROR_OK)
676                                         return ERROR_FAIL;
677                         }
678                         return ERROR_FAIL;
679                 }
680         }
681
682         return ERROR_OK;
683 }
684
685 /**
686     Converts an STLINK status code held in the first byte of a response
687     to an openocd error, logs any error/wait status as debug output.
688 */
689 static int stlink_usb_error_check(void *handle)
690 {
691         struct stlink_usb_handle_s *h = handle;
692
693         assert(handle != NULL);
694
695         if (h->transport == HL_TRANSPORT_SWIM) {
696                 switch (h->databuf[0]) {
697                         case STLINK_SWIM_ERR_OK:
698                                 return ERROR_OK;
699                         case STLINK_SWIM_BUSY:
700                                 return ERROR_WAIT;
701                         default:
702                                 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
703                                 return ERROR_FAIL;
704                 }
705         }
706
707         /* TODO: no error checking yet on api V1 */
708         if (h->version.jtag_api == STLINK_JTAG_API_V1)
709                 h->databuf[0] = STLINK_DEBUG_ERR_OK;
710
711         switch (h->databuf[0]) {
712                 case STLINK_DEBUG_ERR_OK:
713                         return ERROR_OK;
714                 case STLINK_DEBUG_ERR_FAULT:
715                         LOG_DEBUG("SWD fault response (0x%x)", STLINK_DEBUG_ERR_FAULT);
716                         return ERROR_FAIL;
717                 case STLINK_SWD_AP_WAIT:
718                         LOG_DEBUG("wait status SWD_AP_WAIT (0x%x)", STLINK_SWD_AP_WAIT);
719                         return ERROR_WAIT;
720                 case STLINK_SWD_DP_WAIT:
721                         LOG_DEBUG("wait status SWD_DP_WAIT (0x%x)", STLINK_SWD_DP_WAIT);
722                         return ERROR_WAIT;
723                 case STLINK_JTAG_GET_IDCODE_ERROR:
724                         LOG_DEBUG("STLINK_JTAG_GET_IDCODE_ERROR");
725                         return ERROR_FAIL;
726                 case STLINK_JTAG_WRITE_ERROR:
727                         LOG_DEBUG("Write error");
728                         return ERROR_FAIL;
729                 case STLINK_JTAG_WRITE_VERIF_ERROR:
730                         LOG_DEBUG("Write verify error, ignoring");
731                         return ERROR_OK;
732                 case STLINK_SWD_AP_FAULT:
733                         /* git://git.ac6.fr/openocd commit 657e3e885b9ee10
734                          * returns ERROR_OK with the comment:
735                          * Change in error status when reading outside RAM.
736                          * This fix allows CDT plugin to visualize memory.
737                          */
738                         LOG_DEBUG("STLINK_SWD_AP_FAULT");
739                         return ERROR_FAIL;
740                 case STLINK_SWD_AP_ERROR:
741                         LOG_DEBUG("STLINK_SWD_AP_ERROR");
742                         return ERROR_FAIL;
743                 case STLINK_SWD_AP_PARITY_ERROR:
744                         LOG_DEBUG("STLINK_SWD_AP_PARITY_ERROR");
745                         return ERROR_FAIL;
746                 case STLINK_SWD_DP_FAULT:
747                         LOG_DEBUG("STLINK_SWD_DP_FAULT");
748                         return ERROR_FAIL;
749                 case STLINK_SWD_DP_ERROR:
750                         LOG_DEBUG("STLINK_SWD_DP_ERROR");
751                         return ERROR_FAIL;
752                 case STLINK_SWD_DP_PARITY_ERROR:
753                         LOG_DEBUG("STLINK_SWD_DP_PARITY_ERROR");
754                         return ERROR_FAIL;
755                 case STLINK_SWD_AP_WDATA_ERROR:
756                         LOG_DEBUG("STLINK_SWD_AP_WDATA_ERROR");
757                         return ERROR_FAIL;
758                 case STLINK_SWD_AP_STICKY_ERROR:
759                         LOG_DEBUG("STLINK_SWD_AP_STICKY_ERROR");
760                         return ERROR_FAIL;
761                 case STLINK_SWD_AP_STICKYORUN_ERROR:
762                         LOG_DEBUG("STLINK_SWD_AP_STICKYORUN_ERROR");
763                         return ERROR_FAIL;
764                 case STLINK_BAD_AP_ERROR:
765                         LOG_DEBUG("STLINK_BAD_AP_ERROR");
766                         return ERROR_FAIL;
767                 default:
768                         LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
769                         return ERROR_FAIL;
770         }
771 }
772
773 /*
774  * Wrapper around stlink_usb_xfer_noerrcheck()
775  * to check the error code in the received packet
776  */
777 static int stlink_usb_xfer_errcheck(void *handle, const uint8_t *buf, int size)
778 {
779         int retval;
780
781         assert(size > 0);
782
783         retval = stlink_usb_xfer_noerrcheck(handle, buf, size);
784         if (retval != ERROR_OK)
785                 return retval;
786
787         return stlink_usb_error_check(handle);
788 }
789
790 /** Issue an STLINK command via USB transfer, with retries on any wait status responses.
791
792     Works for commands where the STLINK_DEBUG status is returned in the first
793     byte of the response packet. For SWIM a SWIM_READSTATUS is requested instead.
794
795     Returns an openocd result code.
796 */
797 static int stlink_cmd_allow_retry(void *handle, const uint8_t *buf, int size)
798 {
799         int retries = 0;
800         int res;
801         struct stlink_usb_handle_s *h = handle;
802
803         while (1) {
804                 if ((h->transport != HL_TRANSPORT_SWIM) || !retries) {
805                         res = stlink_usb_xfer_noerrcheck(handle, buf, size);
806                         if (res != ERROR_OK)
807                                 return res;
808                 }
809
810                 if (h->transport == HL_TRANSPORT_SWIM) {
811                         res = stlink_swim_status(handle);
812                         if (res != ERROR_OK)
813                                 return res;
814                 }
815
816                 res = stlink_usb_error_check(handle);
817                 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
818                         useconds_t delay_us = (1<<retries++) * 1000;
819                         LOG_DEBUG("stlink_cmd_allow_retry ERROR_WAIT, retry %d, delaying %u microseconds", retries, delay_us);
820                         usleep(delay_us);
821                         continue;
822                 }
823                 return res;
824         }
825 }
826
827 /** */
828 static int stlink_usb_read_trace(void *handle, const uint8_t *buf, int size)
829 {
830         struct stlink_usb_handle_s *h = handle;
831
832         assert(handle != NULL);
833
834         assert(h->version.flags & STLINK_F_HAS_TRACE);
835
836         if (jtag_libusb_bulk_read(h->fd, h->trace_ep, (char *)buf,
837                         size, STLINK_READ_TIMEOUT) != size) {
838                 LOG_ERROR("bulk trace read failed");
839                 return ERROR_FAIL;
840         }
841
842         return ERROR_OK;
843 }
844
845 /*
846         this function writes transfer length in
847         the right place in the cb
848 */
849 static void stlink_usb_set_cbw_transfer_datalength(void *handle, uint32_t size)
850 {
851         struct stlink_usb_handle_s *h = handle;
852
853         buf_set_u32(h->cmdbuf+8, 0, 32, size);
854 }
855
856 static void stlink_usb_xfer_v1_create_cmd(void *handle, uint8_t direction, uint32_t size)
857 {
858         struct stlink_usb_handle_s *h = handle;
859
860         /* fill the send buffer */
861         strcpy((char *)h->cmdbuf, "USBC");
862         h->cmdidx += 4;
863         /* csw tag not used */
864         buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, 0);
865         h->cmdidx += 4;
866         /* cbw data transfer length (in the following data phase in or out) */
867         buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, size);
868         h->cmdidx += 4;
869         /* cbw flags */
870         h->cmdbuf[h->cmdidx++] = (direction == h->rx_ep ? ENDPOINT_IN : ENDPOINT_OUT);
871         h->cmdbuf[h->cmdidx++] = 0; /* lun */
872         /* cdb clength (is filled in at xfer) */
873         h->cmdbuf[h->cmdidx++] = 0;
874 }
875
876 /** */
877 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size)
878 {
879         struct stlink_usb_handle_s *h = handle;
880
881         h->direction = direction;
882
883         h->cmdidx = 0;
884
885         memset(h->cmdbuf, 0, STLINK_SG_SIZE);
886         memset(h->databuf, 0, STLINK_DATA_SIZE);
887
888         if (h->version.stlink == 1)
889                 stlink_usb_xfer_v1_create_cmd(handle, direction, size);
890 }
891
892 /** */
893 static int stlink_usb_version(void *handle)
894 {
895         int res;
896         uint32_t flags;
897         uint16_t version;
898         uint8_t v, x, y, jtag, swim, msd, bridge = 0;
899         char v_str[5 * (1 + 3) + 1]; /* VvJjMmBbSs */
900         char *p;
901         struct stlink_usb_handle_s *h = handle;
902
903         assert(handle != NULL);
904
905         stlink_usb_init_buffer(handle, h->rx_ep, 6);
906
907         h->cmdbuf[h->cmdidx++] = STLINK_GET_VERSION;
908
909         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 6);
910
911         if (res != ERROR_OK)
912                 return res;
913
914         version = be_to_h_u16(h->databuf);
915         v = (version >> 12) & 0x0f;
916         x = (version >> 6) & 0x3f;
917         y = version & 0x3f;
918
919         h->vid = le_to_h_u16(h->databuf + 2);
920         h->pid = le_to_h_u16(h->databuf + 4);
921
922         switch (h->pid) {
923         case STLINK_V2_1_PID:
924         case STLINK_V2_1_NO_MSD_PID:
925                 if ((x <= 22 && y == 7) || (x >= 25 && y >= 7 && y <= 12)) {
926                         /* MxSy : STM8 V2.1 - SWIM only */
927                         msd = x;
928                         swim = y;
929                         jtag = 0;
930                 } else {
931                         /* JxMy : STM32 V2.1 - JTAG/SWD only */
932                         jtag = x;
933                         msd = y;
934                         swim = 0;
935                 }
936                 break;
937         default:
938                 jtag = x;
939                 swim = y;
940                 msd = 0;
941                 break;
942         }
943
944         /* STLINK-V3 requires a specific command */
945         if (v == 3 && x == 0 && y == 0) {
946                 stlink_usb_init_buffer(handle, h->rx_ep, 16);
947
948                 h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_VERSION_EX;
949
950                 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 12);
951                 if (res != ERROR_OK)
952                         return res;
953
954                 v = h->databuf[0];
955                 swim = h->databuf[1];
956                 jtag = h->databuf[2];
957                 msd  = h->databuf[3];
958                 bridge = h->databuf[4];
959                 h->vid = le_to_h_u16(h->databuf + 8);
960                 h->pid = le_to_h_u16(h->databuf + 10);
961         }
962
963         h->version.stlink = v;
964         h->version.jtag = jtag;
965         h->version.swim = swim;
966
967         flags = 0;
968         switch (h->version.stlink) {
969         case 1:
970                 /* ST-LINK/V1 from J11 switch to api-v2 (and support SWD) */
971                 if (h->version.jtag >= 11)
972                         h->version.jtag_api = STLINK_JTAG_API_V2;
973                 else
974                         h->version.jtag_api = STLINK_JTAG_API_V1;
975
976                 break;
977         case 2:
978                 /* all ST-LINK/V2 and ST-Link/V2.1 use api-v2 */
979                 h->version.jtag_api = STLINK_JTAG_API_V2;
980
981                 /* API for trace from J13 */
982                 /* API for target voltage from J13 */
983                 if (h->version.jtag >= 13)
984                         flags |= STLINK_F_HAS_TRACE;
985
986                 /* preferred API to get last R/W status from J15 */
987                 if (h->version.jtag >= 15)
988                         flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
989
990                 /* API to set SWD frequency from J22 */
991                 if (h->version.jtag >= 22)
992                         flags |= STLINK_F_HAS_SWD_SET_FREQ;
993
994                 /* API to set JTAG frequency from J24 */
995                 if (h->version.jtag >= 24)
996                         flags |= STLINK_F_HAS_JTAG_SET_FREQ;
997
998                 /* API to read/write memory at 16 bit from J26 */
999                 if (h->version.jtag >= 26)
1000                         flags |= STLINK_F_HAS_MEM_16BIT;
1001
1002                 break;
1003         case 3:
1004                 /* all STLINK-V3 use api-v3 */
1005                 h->version.jtag_api = STLINK_JTAG_API_V3;
1006
1007                 /* STLINK-V3 is a superset of ST-LINK/V2 */
1008
1009                 /* API for trace */
1010                 /* API for target voltage */
1011                 flags |= STLINK_F_HAS_TRACE;
1012
1013                 /* preferred API to get last R/W status */
1014                 flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1015
1016                 /* API to read/write memory at 16 bit */
1017                 flags |= STLINK_F_HAS_MEM_16BIT;
1018
1019                 break;
1020         default:
1021                 break;
1022         }
1023         h->version.flags = flags;
1024
1025         p = v_str;
1026         p += sprintf(p, "V%d", v);
1027         if (jtag || !msd)
1028                 p += sprintf(p, "J%d", jtag);
1029         if (msd)
1030                 p += sprintf(p, "M%d", msd);
1031         if (bridge)
1032                 p += sprintf(p, "B%d", bridge);
1033         if (swim || !msd)
1034                 sprintf(p, "S%d", swim);
1035
1036         LOG_INFO("STLINK %s (API v%d) VID:PID %04X:%04X",
1037                 v_str,
1038                 h->version.jtag_api,
1039                 h->vid,
1040                 h->pid);
1041
1042         return ERROR_OK;
1043 }
1044
1045 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
1046 {
1047         struct stlink_usb_handle_s *h = handle;
1048         uint32_t adc_results[2];
1049
1050         /* no error message, simply quit with error */
1051         if (!(h->version.flags & STLINK_F_HAS_TARGET_VOLT))
1052                 return ERROR_COMMAND_NOTFOUND;
1053
1054         stlink_usb_init_buffer(handle, h->rx_ep, 8);
1055
1056         h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
1057
1058         int result = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1059
1060         if (result != ERROR_OK)
1061                 return result;
1062
1063         /* convert result */
1064         adc_results[0] = le_to_h_u32(h->databuf);
1065         adc_results[1] = le_to_h_u32(h->databuf + 4);
1066
1067         *target_voltage = 0;
1068
1069         if (adc_results[0])
1070                 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
1071
1072         LOG_INFO("Target voltage: %f", (double)*target_voltage);
1073
1074         return ERROR_OK;
1075 }
1076
1077 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
1078 {
1079         struct stlink_usb_handle_s *h = handle;
1080
1081         assert(handle != NULL);
1082
1083         if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
1084                 return ERROR_COMMAND_NOTFOUND;
1085
1086         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1087
1088         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1089         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
1090         h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1091         h->cmdidx += 2;
1092
1093         int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1094
1095         if (result != ERROR_OK)
1096                 return result;
1097
1098         return ERROR_OK;
1099 }
1100
1101 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
1102 {
1103         struct stlink_usb_handle_s *h = handle;
1104
1105         assert(handle != NULL);
1106
1107         if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
1108                 return ERROR_COMMAND_NOTFOUND;
1109
1110         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1111
1112         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1113         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
1114         h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
1115         h->cmdidx += 2;
1116
1117         int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
1118
1119         if (result != ERROR_OK)
1120                 return result;
1121
1122         return ERROR_OK;
1123 }
1124
1125 /** */
1126 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
1127 {
1128         int res;
1129         struct stlink_usb_handle_s *h = handle;
1130
1131         assert(handle != NULL);
1132
1133         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1134
1135         h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
1136
1137         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1138
1139         if (res != ERROR_OK)
1140                 return res;
1141
1142         *mode = h->databuf[0];
1143
1144         return ERROR_OK;
1145 }
1146
1147 /** */
1148 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
1149 {
1150         int rx_size = 0;
1151         struct stlink_usb_handle_s *h = handle;
1152
1153         assert(handle != NULL);
1154
1155         /* on api V2 we are able the read the latest command
1156          * status
1157          * TODO: we need the test on api V1 too
1158          */
1159         if (h->version.jtag_api != STLINK_JTAG_API_V1)
1160                 rx_size = 2;
1161
1162         stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
1163
1164         switch (type) {
1165                 case STLINK_MODE_DEBUG_JTAG:
1166                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1167                         if (h->version.jtag_api == STLINK_JTAG_API_V1)
1168                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1169                         else
1170                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1171                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG_NO_RESET;
1172                         break;
1173                 case STLINK_MODE_DEBUG_SWD:
1174                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1175                         if (h->version.jtag_api == STLINK_JTAG_API_V1)
1176                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
1177                         else
1178                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
1179                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD_NO_RESET;
1180                         break;
1181                 case STLINK_MODE_DEBUG_SWIM:
1182                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1183                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
1184                         /* no answer for this function... */
1185                         rx_size = 0;
1186                         break;
1187                 case STLINK_MODE_DFU:
1188                 case STLINK_MODE_MASS:
1189                 default:
1190                         return ERROR_FAIL;
1191         }
1192
1193         return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
1194 }
1195
1196 /** */
1197 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
1198 {
1199         int res;
1200         struct stlink_usb_handle_s *h = handle;
1201
1202         assert(handle != NULL);
1203
1204         stlink_usb_init_buffer(handle, STLINK_NULL_EP, 0);
1205
1206         switch (type) {
1207                 case STLINK_MODE_DEBUG_JTAG:
1208                 case STLINK_MODE_DEBUG_SWD:
1209                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1210                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
1211                         break;
1212                 case STLINK_MODE_DEBUG_SWIM:
1213                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1214                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
1215                         break;
1216                 case STLINK_MODE_DFU:
1217                         h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
1218                         h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
1219                         break;
1220                 case STLINK_MODE_MASS:
1221                 default:
1222                         return ERROR_FAIL;
1223         }
1224
1225         res = stlink_usb_xfer_noerrcheck(handle, 0, 0);
1226
1227         if (res != ERROR_OK)
1228                 return res;
1229
1230         return ERROR_OK;
1231 }
1232
1233 static int stlink_usb_assert_srst(void *handle, int srst);
1234
1235 static enum stlink_mode stlink_get_mode(enum hl_transports t)
1236 {
1237         switch (t) {
1238         case HL_TRANSPORT_SWD:
1239                 return STLINK_MODE_DEBUG_SWD;
1240         case HL_TRANSPORT_JTAG:
1241                 return STLINK_MODE_DEBUG_JTAG;
1242         case HL_TRANSPORT_SWIM:
1243                 return STLINK_MODE_DEBUG_SWIM;
1244         default:
1245                 return STLINK_MODE_UNKNOWN;
1246         }
1247 }
1248
1249 /** */
1250 static int stlink_usb_init_mode(void *handle, bool connect_under_reset, int initial_interface_speed)
1251 {
1252         int res;
1253         uint8_t mode;
1254         enum stlink_mode emode;
1255         struct stlink_usb_handle_s *h = handle;
1256
1257         assert(handle != NULL);
1258
1259         res = stlink_usb_current_mode(handle, &mode);
1260
1261         if (res != ERROR_OK)
1262                 return res;
1263
1264         LOG_DEBUG("MODE: 0x%02X", mode);
1265
1266         /* try to exit current mode */
1267         switch (mode) {
1268                 case STLINK_DEV_DFU_MODE:
1269                         emode = STLINK_MODE_DFU;
1270                         break;
1271                 case STLINK_DEV_DEBUG_MODE:
1272                         emode = STLINK_MODE_DEBUG_SWD;
1273                         break;
1274                 case STLINK_DEV_SWIM_MODE:
1275                         emode = STLINK_MODE_DEBUG_SWIM;
1276                         break;
1277                 case STLINK_DEV_BOOTLOADER_MODE:
1278                 case STLINK_DEV_MASS_MODE:
1279                 default:
1280                         emode = STLINK_MODE_UNKNOWN;
1281                         break;
1282         }
1283
1284         if (emode != STLINK_MODE_UNKNOWN) {
1285                 res = stlink_usb_mode_leave(handle, emode);
1286
1287                 if (res != ERROR_OK)
1288                         return res;
1289         }
1290
1291         res = stlink_usb_current_mode(handle, &mode);
1292
1293         if (res != ERROR_OK)
1294                 return res;
1295
1296         /* we check the target voltage here as an aid to debugging connection problems.
1297          * the stlink requires the target Vdd to be connected for reliable debugging.
1298          * this cmd is supported in all modes except DFU
1299          */
1300         if (mode != STLINK_DEV_DFU_MODE) {
1301
1302                 float target_voltage;
1303
1304                 /* check target voltage (if supported) */
1305                 res = stlink_usb_check_voltage(h, &target_voltage);
1306
1307                 if (res != ERROR_OK) {
1308                         if (res != ERROR_COMMAND_NOTFOUND)
1309                                 LOG_ERROR("voltage check failed");
1310                         /* attempt to continue as it is not a catastrophic failure */
1311                 } else {
1312                         /* check for a sensible target voltage, operating range is 1.65-5.5v
1313                          * according to datasheet */
1314                         if (target_voltage < 1.5)
1315                                 LOG_ERROR("target voltage may be too low for reliable debugging");
1316                 }
1317         }
1318
1319         LOG_DEBUG("MODE: 0x%02X", mode);
1320
1321         /* set selected mode */
1322         emode = stlink_get_mode(h->transport);
1323
1324         if (emode == STLINK_MODE_UNKNOWN) {
1325                 LOG_ERROR("selected mode (transport) not supported");
1326                 return ERROR_FAIL;
1327         }
1328
1329         /* set the speed before entering the mode, as the chip discovery phase should be done at this speed too */
1330         if (h->transport == HL_TRANSPORT_JTAG) {
1331                 if (h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ) {
1332                         stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
1333                         stlink_speed(h, initial_interface_speed, false);
1334                 }
1335         } else if (h->transport == HL_TRANSPORT_SWD) {
1336                 if (h->version.flags & STLINK_F_HAS_SWD_SET_FREQ) {
1337                         stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
1338                         stlink_speed(h, initial_interface_speed, false);
1339                 }
1340         }
1341
1342         if (h->version.jtag_api == STLINK_JTAG_API_V3) {
1343                 struct speed_map map[STLINK_V3_MAX_FREQ_NB];
1344
1345                 stlink_get_com_freq(h, (h->transport == HL_TRANSPORT_JTAG), map);
1346                 stlink_dump_speed_map(map, ARRAY_SIZE(map));
1347                 stlink_speed(h, initial_interface_speed, false);
1348         }
1349
1350         /* preliminary SRST assert:
1351          * We want SRST is asserted before activating debug signals (mode_enter).
1352          * As the required mode has not been set, the adapter may not know what pin to use.
1353          * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
1354          * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
1355          * after power on, SWIM_RST stays unchanged */
1356         if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
1357                 stlink_usb_assert_srst(handle, 0);
1358                 /* do not check the return status here, we will
1359                    proceed and enter the desired mode below
1360                    and try asserting srst again. */
1361
1362         res = stlink_usb_mode_enter(handle, emode);
1363         if (res != ERROR_OK)
1364                 return res;
1365
1366         /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
1367         if (connect_under_reset) {
1368                 res = stlink_usb_assert_srst(handle, 0);
1369                 if (res != ERROR_OK)
1370                         return res;
1371         }
1372
1373         res = stlink_usb_current_mode(handle, &mode);
1374
1375         if (res != ERROR_OK)
1376                 return res;
1377
1378         LOG_DEBUG("MODE: 0x%02X", mode);
1379
1380         return ERROR_OK;
1381 }
1382
1383 /* request status from last swim request */
1384 static int stlink_swim_status(void *handle)
1385 {
1386         struct stlink_usb_handle_s *h = handle;
1387         int res;
1388
1389         stlink_usb_init_buffer(handle, h->rx_ep, 4);
1390         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1391         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
1392         /* error is checked by the caller */
1393         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1394         if (res != ERROR_OK)
1395                 return res;
1396         return ERROR_OK;
1397 }
1398 /*
1399         the purpose of this function is unknown...
1400         capabilites? anyway for swim v6 it returns
1401         0001020600000000
1402 */
1403 __attribute__((unused))
1404 static int stlink_swim_cap(void *handle, uint8_t *cap)
1405 {
1406         struct stlink_usb_handle_s *h = handle;
1407         int res;
1408
1409         stlink_usb_init_buffer(handle, h->rx_ep, 8);
1410         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1411         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1412         h->cmdbuf[h->cmdidx++] = 0x01;
1413         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 8);
1414         if (res != ERROR_OK)
1415                 return res;
1416         memcpy(cap, h->databuf, 8);
1417         return ERROR_OK;
1418 }
1419
1420 /*      debug dongle assert/deassert sreset line */
1421 static int stlink_swim_assert_reset(void *handle, int reset)
1422 {
1423         struct stlink_usb_handle_s *h = handle;
1424         int res;
1425
1426         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1427         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1428         if (!reset)
1429                 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1430         else
1431                 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1432         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1433         if (res != ERROR_OK)
1434                 return res;
1435         return ERROR_OK;
1436 }
1437
1438 /*
1439         send swim enter seq
1440         1.3ms low then 750Hz then 1.5kHz
1441 */
1442 static int stlink_swim_enter(void *handle)
1443 {
1444         struct stlink_usb_handle_s *h = handle;
1445         int res;
1446
1447         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1448         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1449         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1450         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1451         if (res != ERROR_OK)
1452                 return res;
1453         return ERROR_OK;
1454 }
1455
1456 /*      switch high/low speed swim */
1457 static int stlink_swim_speed(void *handle, int speed)
1458 {
1459         struct stlink_usb_handle_s *h = handle;
1460         int res;
1461
1462         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1463         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1464         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1465         if (speed)
1466                 h->cmdbuf[h->cmdidx++] = 1;
1467         else
1468                 h->cmdbuf[h->cmdidx++] = 0;
1469         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1470         if (res != ERROR_OK)
1471                 return res;
1472         return ERROR_OK;
1473 }
1474
1475 /*
1476         initiate srst from swim.
1477         nrst is pulled low for 50us.
1478 */
1479 static int stlink_swim_generate_rst(void *handle)
1480 {
1481         struct stlink_usb_handle_s *h = handle;
1482         int res;
1483
1484         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1485         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1486         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1487         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1488         if (res != ERROR_OK)
1489                 return res;
1490         return ERROR_OK;
1491 }
1492
1493 /*
1494         send resyncronize sequence
1495         swim is pulled low for 16us
1496         reply is 64 clks low
1497 */
1498 static int stlink_swim_resync(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_RESET;
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 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1513 {
1514         struct stlink_usb_handle_s *h = handle;
1515         int res;
1516         unsigned int i;
1517         unsigned int datalen = 0;
1518         int cmdsize = STLINK_CMD_SIZE_V2;
1519
1520         if (len > STLINK_DATA_SIZE)
1521                 return ERROR_FAIL;
1522
1523         if (h->version.stlink == 1)
1524                 cmdsize = STLINK_SG_SIZE;
1525
1526         stlink_usb_init_buffer(handle, h->tx_ep, 0);
1527         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1528         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1529         h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1530         h->cmdidx += 2;
1531         h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1532         h->cmdidx += 4;
1533         for (i = 0; i < len; i++) {
1534                 if (h->cmdidx == cmdsize)
1535                         h->databuf[datalen++] = *(data++);
1536                 else
1537                         h->cmdbuf[h->cmdidx++] = *(data++);
1538         }
1539         if (h->version.stlink == 1)
1540                 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1541
1542         res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1543         if (res != ERROR_OK)
1544                 return res;
1545         return ERROR_OK;
1546 }
1547
1548 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1549 {
1550         struct stlink_usb_handle_s *h = handle;
1551         int res;
1552
1553         if (len > STLINK_DATA_SIZE)
1554                 return ERROR_FAIL;
1555
1556         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1557         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1558         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1559         h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1560         h->cmdidx += 2;
1561         h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1562         h->cmdidx += 4;
1563         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1564         if (res != ERROR_OK)
1565                 return res;
1566
1567         stlink_usb_init_buffer(handle, h->rx_ep, len);
1568         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1569         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1570         res = stlink_usb_xfer_noerrcheck(handle, data, len);
1571         if (res != ERROR_OK)
1572                 return res;
1573
1574         return ERROR_OK;
1575 }
1576
1577 /** */
1578 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1579 {
1580         int res, offset;
1581         struct stlink_usb_handle_s *h = handle;
1582
1583         assert(handle != NULL);
1584
1585         /* there is no swim read core id cmd */
1586         if (h->transport == HL_TRANSPORT_SWIM) {
1587                 *idcode = 0;
1588                 return ERROR_OK;
1589         }
1590
1591         stlink_usb_init_buffer(handle, h->rx_ep, 12);
1592
1593         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1594         if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1595                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1596
1597                 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1598                 offset = 0;
1599         } else {
1600                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READ_IDCODES;
1601
1602                 res = stlink_usb_xfer_errcheck(handle, h->databuf, 12);
1603                 offset = 4;
1604         }
1605
1606         if (res != ERROR_OK)
1607                 return res;
1608
1609         *idcode = le_to_h_u32(h->databuf + offset);
1610
1611         LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1612
1613         return ERROR_OK;
1614 }
1615
1616 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1617 {
1618         struct stlink_usb_handle_s *h = handle;
1619         int res;
1620
1621         assert(handle != NULL);
1622
1623         stlink_usb_init_buffer(handle, h->rx_ep, 8);
1624
1625         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1626         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1627         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1628         h->cmdidx += 4;
1629
1630         res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1631         if (res != ERROR_OK)
1632                 return res;
1633
1634         *val = le_to_h_u32(h->databuf + 4);
1635         return ERROR_OK;
1636 }
1637
1638 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1639 {
1640         struct stlink_usb_handle_s *h = handle;
1641
1642         assert(handle != NULL);
1643
1644         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1645
1646         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1647         if (h->version.jtag_api == STLINK_JTAG_API_V1)
1648                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1649         else
1650                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1651         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1652         h->cmdidx += 4;
1653         h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1654         h->cmdidx += 4;
1655
1656         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1657 }
1658
1659 /** */
1660 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1661 {
1662         struct stlink_usb_handle_s *h = handle;
1663
1664         assert(handle != NULL);
1665
1666         if (h->trace.enabled && (h->version.flags & STLINK_F_HAS_TRACE)) {
1667                 int res;
1668
1669                 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1670
1671                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1672                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1673
1674                 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1675                 if (res != ERROR_OK)
1676                         return res;
1677
1678                 size_t bytes_avail = le_to_h_u16(h->databuf);
1679                 *size = bytes_avail < *size ? bytes_avail : *size - 1;
1680
1681                 if (*size > 0) {
1682                         res = stlink_usb_read_trace(handle, buf, *size);
1683                         if (res != ERROR_OK)
1684                                 return res;
1685                         return ERROR_OK;
1686                 }
1687         }
1688         *size = 0;
1689         return ERROR_OK;
1690 }
1691
1692 static enum target_state stlink_usb_v2_get_status(void *handle)
1693 {
1694         int result;
1695         uint32_t status;
1696
1697         result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1698         if  (result != ERROR_OK)
1699                 return TARGET_UNKNOWN;
1700
1701         if (status & S_HALT)
1702                 return TARGET_HALTED;
1703         else if (status & S_RESET_ST)
1704                 return TARGET_RESET;
1705
1706         return TARGET_RUNNING;
1707 }
1708
1709 /** */
1710 static enum target_state stlink_usb_state(void *handle)
1711 {
1712         int res;
1713         struct stlink_usb_handle_s *h = handle;
1714
1715         assert(handle != NULL);
1716
1717         if (h->transport == HL_TRANSPORT_SWIM) {
1718                 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1719                 if (res != ERROR_OK)
1720                         return TARGET_UNKNOWN;
1721
1722                 res = stlink_swim_resync(handle);
1723                 if (res != ERROR_OK)
1724                         return TARGET_UNKNOWN;
1725
1726                 return ERROR_OK;
1727         }
1728
1729         if (h->reconnect_pending) {
1730                 LOG_INFO("Previous state query failed, trying to reconnect");
1731                 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1732
1733                 if (res != ERROR_OK)
1734                         return TARGET_UNKNOWN;
1735
1736                 h->reconnect_pending = false;
1737         }
1738
1739         if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1740                 res = stlink_usb_v2_get_status(handle);
1741                 if (res == TARGET_UNKNOWN)
1742                         h->reconnect_pending = true;
1743                 return res;
1744         }
1745
1746         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1747
1748         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1749         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
1750
1751         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 2);
1752
1753         if (res != ERROR_OK)
1754                 return TARGET_UNKNOWN;
1755
1756         if (h->databuf[0] == STLINK_CORE_RUNNING)
1757                 return TARGET_RUNNING;
1758         if (h->databuf[0] == STLINK_CORE_HALTED)
1759                 return TARGET_HALTED;
1760
1761         h->reconnect_pending = true;
1762
1763         return TARGET_UNKNOWN;
1764 }
1765
1766 static int stlink_usb_assert_srst(void *handle, int srst)
1767 {
1768         struct stlink_usb_handle_s *h = handle;
1769
1770         assert(handle != NULL);
1771
1772         if (h->transport == HL_TRANSPORT_SWIM)
1773                 return stlink_swim_assert_reset(handle, srst);
1774
1775         if (h->version.stlink == 1)
1776                 return ERROR_COMMAND_NOTFOUND;
1777
1778         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1779
1780         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1781         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
1782         h->cmdbuf[h->cmdidx++] = srst;
1783
1784         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1785 }
1786
1787 /** */
1788 static void stlink_usb_trace_disable(void *handle)
1789 {
1790         int res = ERROR_OK;
1791         struct stlink_usb_handle_s *h = handle;
1792
1793         assert(handle != NULL);
1794
1795         assert(h->version.flags & STLINK_F_HAS_TRACE);
1796
1797         LOG_DEBUG("Tracing: disable");
1798
1799         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1800         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1801         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
1802         res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1803
1804         if (res == ERROR_OK)
1805                 h->trace.enabled = false;
1806 }
1807
1808
1809 /** */
1810 static int stlink_usb_trace_enable(void *handle)
1811 {
1812         int res;
1813         struct stlink_usb_handle_s *h = handle;
1814
1815         assert(handle != NULL);
1816
1817         if (h->version.flags & STLINK_F_HAS_TRACE) {
1818                 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1819
1820                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1821                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
1822                 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
1823                 h->cmdidx += 2;
1824                 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
1825                 h->cmdidx += 4;
1826
1827                 res = stlink_usb_xfer_errcheck(handle, h->databuf, 2);
1828
1829                 if (res == ERROR_OK)  {
1830                         h->trace.enabled = true;
1831                         LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
1832                 }
1833         } else {
1834                 LOG_ERROR("Tracing is not supported by this version.");
1835                 res = ERROR_FAIL;
1836         }
1837
1838         return res;
1839 }
1840
1841 /** */
1842 static int stlink_usb_reset(void *handle)
1843 {
1844         struct stlink_usb_handle_s *h = handle;
1845         int retval;
1846
1847         assert(handle != NULL);
1848
1849         if (h->transport == HL_TRANSPORT_SWIM)
1850                 return stlink_swim_generate_rst(handle);
1851
1852         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1853
1854         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1855
1856         if (h->version.jtag_api == STLINK_JTAG_API_V1)
1857                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
1858         else
1859                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
1860
1861         retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
1862         if (retval != ERROR_OK)
1863                 return retval;
1864
1865         if (h->trace.enabled) {
1866                 stlink_usb_trace_disable(h);
1867                 return stlink_usb_trace_enable(h);
1868         }
1869
1870         return ERROR_OK;
1871 }
1872
1873 /** */
1874 static int stlink_usb_run(void *handle)
1875 {
1876         int res;
1877         struct stlink_usb_handle_s *h = handle;
1878
1879         assert(handle != NULL);
1880
1881         if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1882                 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
1883
1884                 return res;
1885         }
1886
1887         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1888
1889         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1890         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
1891
1892         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1893 }
1894
1895 /** */
1896 static int stlink_usb_halt(void *handle)
1897 {
1898         int res;
1899         struct stlink_usb_handle_s *h = handle;
1900
1901         assert(handle != NULL);
1902
1903         if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1904                 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1905
1906                 return res;
1907         }
1908
1909         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1910
1911         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1912         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
1913
1914         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1915 }
1916
1917 /** */
1918 static int stlink_usb_step(void *handle)
1919 {
1920         struct stlink_usb_handle_s *h = handle;
1921
1922         assert(handle != NULL);
1923
1924         if (h->version.jtag_api != STLINK_JTAG_API_V1) {
1925                 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
1926                  * that the Cortex-M3 currently does. */
1927                 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
1928                 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
1929                 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1930         }
1931
1932         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1933
1934         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1935         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
1936
1937         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1938 }
1939
1940 /** */
1941 static int stlink_usb_read_regs(void *handle)
1942 {
1943         int res;
1944         struct stlink_usb_handle_s *h = handle;
1945
1946         assert(handle != NULL);
1947
1948         stlink_usb_init_buffer(handle, h->rx_ep, 88);
1949
1950         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1951         if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1952
1953                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
1954                 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 84);
1955                 /* regs data from offset 0 */
1956         } else {
1957                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
1958                 res = stlink_usb_xfer_errcheck(handle, h->databuf, 88);
1959                 /* status at offset 0, regs data from offset 4 */
1960         }
1961
1962         return res;
1963 }
1964
1965 /** */
1966 static int stlink_usb_read_reg(void *handle, int num, uint32_t *val)
1967 {
1968         int res;
1969         struct stlink_usb_handle_s *h = handle;
1970
1971         assert(handle != NULL);
1972
1973         stlink_usb_init_buffer(handle, h->rx_ep, h->version.jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
1974
1975         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1976         if (h->version.jtag_api == STLINK_JTAG_API_V1)
1977                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
1978         else
1979                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
1980         h->cmdbuf[h->cmdidx++] = num;
1981
1982         if (h->version.jtag_api == STLINK_JTAG_API_V1) {
1983                 res = stlink_usb_xfer_noerrcheck(handle, h->databuf, 4);
1984                 if (res != ERROR_OK)
1985                         return res;
1986                 *val = le_to_h_u32(h->databuf);
1987                 return ERROR_OK;
1988         } else {
1989                 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1990                 if (res != ERROR_OK)
1991                         return res;
1992                 *val = le_to_h_u32(h->databuf + 4);
1993                 return ERROR_OK;
1994         }
1995 }
1996
1997 /** */
1998 static int stlink_usb_write_reg(void *handle, int num, uint32_t val)
1999 {
2000         struct stlink_usb_handle_s *h = handle;
2001
2002         assert(handle != NULL);
2003
2004         stlink_usb_init_buffer(handle, h->rx_ep, 2);
2005
2006         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2007         if (h->version.jtag_api == STLINK_JTAG_API_V1)
2008                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
2009         else
2010                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
2011         h->cmdbuf[h->cmdidx++] = num;
2012         h_u32_to_le(h->cmdbuf+h->cmdidx, val);
2013         h->cmdidx += 4;
2014
2015         return stlink_cmd_allow_retry(handle, h->databuf, 2);
2016 }
2017
2018 static int stlink_usb_get_rw_status(void *handle)
2019 {
2020         struct stlink_usb_handle_s *h = handle;
2021
2022         assert(handle != NULL);
2023
2024         if (h->version.jtag_api == STLINK_JTAG_API_V1)
2025                 return ERROR_OK;
2026
2027         stlink_usb_init_buffer(handle, h->rx_ep, 2);
2028
2029         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2030         if (h->version.flags & STLINK_F_HAS_GETLASTRWSTATUS2) {
2031                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS2;
2032                 return stlink_usb_xfer_errcheck(handle, h->databuf, 12);
2033         } else {
2034                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
2035                 return stlink_usb_xfer_errcheck(handle, h->databuf, 2);
2036         }
2037 }
2038
2039 /** */
2040 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
2041                           uint8_t *buffer)
2042 {
2043         int res;
2044         uint16_t read_len = len;
2045         struct stlink_usb_handle_s *h = handle;
2046
2047         assert(handle != NULL);
2048
2049         /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2050         if (len > stlink_usb_block(h)) {
2051                 LOG_DEBUG("max buffer (%d) length exceeded", stlink_usb_block(h));
2052                 return ERROR_FAIL;
2053         }
2054
2055         stlink_usb_init_buffer(handle, h->rx_ep, read_len);
2056
2057         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2058         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
2059         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2060         h->cmdidx += 4;
2061         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2062         h->cmdidx += 2;
2063
2064         /* we need to fix read length for single bytes */
2065         if (read_len == 1)
2066                 read_len++;
2067
2068         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, read_len);
2069
2070         if (res != ERROR_OK)
2071                 return res;
2072
2073         memcpy(buffer, h->databuf, len);
2074
2075         return stlink_usb_get_rw_status(handle);
2076 }
2077
2078 /** */
2079 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
2080                            const uint8_t *buffer)
2081 {
2082         int res;
2083         struct stlink_usb_handle_s *h = handle;
2084
2085         assert(handle != NULL);
2086
2087         /* max 8 bit read/write is 64 bytes or 512 bytes for v3 */
2088         if (len > stlink_usb_block(h)) {
2089                 LOG_DEBUG("max buffer length (%d) exceeded", stlink_usb_block(h));
2090                 return ERROR_FAIL;
2091         }
2092
2093         stlink_usb_init_buffer(handle, h->tx_ep, len);
2094
2095         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2096         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
2097         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2098         h->cmdidx += 4;
2099         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2100         h->cmdidx += 2;
2101
2102         res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2103
2104         if (res != ERROR_OK)
2105                 return res;
2106
2107         return stlink_usb_get_rw_status(handle);
2108 }
2109
2110 /** */
2111 static int stlink_usb_read_mem16(void *handle, uint32_t addr, uint16_t len,
2112                           uint8_t *buffer)
2113 {
2114         int res;
2115         struct stlink_usb_handle_s *h = handle;
2116
2117         assert(handle != NULL);
2118
2119         if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2120                 return ERROR_COMMAND_NOTFOUND;
2121
2122         /* data must be a multiple of 2 and half-word aligned */
2123         if (len % 2 || addr % 2) {
2124                 LOG_DEBUG("Invalid data alignment");
2125                 return ERROR_TARGET_UNALIGNED_ACCESS;
2126         }
2127
2128         stlink_usb_init_buffer(handle, h->rx_ep, len);
2129
2130         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2131         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READMEM_16BIT;
2132         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2133         h->cmdidx += 4;
2134         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2135         h->cmdidx += 2;
2136
2137         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2138
2139         if (res != ERROR_OK)
2140                 return res;
2141
2142         memcpy(buffer, h->databuf, len);
2143
2144         return stlink_usb_get_rw_status(handle);
2145 }
2146
2147 /** */
2148 static int stlink_usb_write_mem16(void *handle, uint32_t addr, uint16_t len,
2149                            const uint8_t *buffer)
2150 {
2151         int res;
2152         struct stlink_usb_handle_s *h = handle;
2153
2154         assert(handle != NULL);
2155
2156         if (!(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2157                 return ERROR_COMMAND_NOTFOUND;
2158
2159         /* data must be a multiple of 2 and half-word aligned */
2160         if (len % 2 || addr % 2) {
2161                 LOG_DEBUG("Invalid data alignment");
2162                 return ERROR_TARGET_UNALIGNED_ACCESS;
2163         }
2164
2165         stlink_usb_init_buffer(handle, h->tx_ep, len);
2166
2167         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2168         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEMEM_16BIT;
2169         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2170         h->cmdidx += 4;
2171         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2172         h->cmdidx += 2;
2173
2174         res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2175
2176         if (res != ERROR_OK)
2177                 return res;
2178
2179         return stlink_usb_get_rw_status(handle);
2180 }
2181
2182 /** */
2183 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
2184                           uint8_t *buffer)
2185 {
2186         int res;
2187         struct stlink_usb_handle_s *h = handle;
2188
2189         assert(handle != NULL);
2190
2191         /* data must be a multiple of 4 and word aligned */
2192         if (len % 4 || addr % 4) {
2193                 LOG_DEBUG("Invalid data alignment");
2194                 return ERROR_TARGET_UNALIGNED_ACCESS;
2195         }
2196
2197         stlink_usb_init_buffer(handle, h->rx_ep, len);
2198
2199         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2200         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
2201         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2202         h->cmdidx += 4;
2203         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2204         h->cmdidx += 2;
2205
2206         res = stlink_usb_xfer_noerrcheck(handle, h->databuf, len);
2207
2208         if (res != ERROR_OK)
2209                 return res;
2210
2211         memcpy(buffer, h->databuf, len);
2212
2213         return stlink_usb_get_rw_status(handle);
2214 }
2215
2216 /** */
2217 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
2218                            const uint8_t *buffer)
2219 {
2220         int res;
2221         struct stlink_usb_handle_s *h = handle;
2222
2223         assert(handle != NULL);
2224
2225         /* data must be a multiple of 4 and word aligned */
2226         if (len % 4 || addr % 4) {
2227                 LOG_DEBUG("Invalid data alignment");
2228                 return ERROR_TARGET_UNALIGNED_ACCESS;
2229         }
2230
2231         stlink_usb_init_buffer(handle, h->tx_ep, len);
2232
2233         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2234         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
2235         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
2236         h->cmdidx += 4;
2237         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
2238         h->cmdidx += 2;
2239
2240         res = stlink_usb_xfer_noerrcheck(handle, buffer, len);
2241
2242         if (res != ERROR_OK)
2243                 return res;
2244
2245         return stlink_usb_get_rw_status(handle);
2246 }
2247
2248 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
2249 {
2250         uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
2251         if (max_tar_block == 0)
2252                 max_tar_block = 4;
2253         return max_tar_block;
2254 }
2255
2256 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
2257                 uint32_t count, uint8_t *buffer)
2258 {
2259         int retval = ERROR_OK;
2260         uint32_t bytes_remaining;
2261         int retries = 0;
2262         struct stlink_usb_handle_s *h = handle;
2263
2264         /* calculate byte count */
2265         count *= size;
2266
2267         /* switch to 8 bit if stlink does not support 16 bit memory read */
2268         if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2269                 size = 1;
2270
2271         while (count) {
2272
2273                 bytes_remaining = (size != 1) ? \
2274                                 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2275
2276                 if (count < bytes_remaining)
2277                         bytes_remaining = count;
2278
2279                 if (h->transport == HL_TRANSPORT_SWIM) {
2280                         retval = stlink_swim_readbytes(handle, addr, bytes_remaining, buffer);
2281                         if (retval != ERROR_OK)
2282                                 return retval;
2283                 } else
2284                 /*
2285                  * all stlink support 8/32bit memory read/writes and only from
2286                  * stlink V2J26 there is support for 16 bit memory read/write.
2287                  * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2288                  * as 8bit access.
2289                  */
2290                 if (size != 1) {
2291
2292                         /* When in jtag mode the stlink uses the auto-increment functionality.
2293                          * However it expects us to pass the data correctly, this includes
2294                          * alignment and any page boundaries. We already do this as part of the
2295                          * adi_v5 implementation, but the stlink is a hla adapter and so this
2296                          * needs implementing manually.
2297                          * currently this only affects jtag mode, according to ST they do single
2298                          * access in SWD mode - but this may change and so we do it for both modes */
2299
2300                         /* we first need to check for any unaligned bytes */
2301                         if (addr & (size - 1)) {
2302
2303                                 uint32_t head_bytes = size - (addr & (size - 1));
2304                                 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
2305                                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2306                                         usleep((1<<retries++) * 1000);
2307                                         continue;
2308                                 }
2309                                 if (retval != ERROR_OK)
2310                                         return retval;
2311                                 buffer += head_bytes;
2312                                 addr += head_bytes;
2313                                 count -= head_bytes;
2314                                 bytes_remaining -= head_bytes;
2315                         }
2316
2317                         if (bytes_remaining & (size - 1))
2318                                 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
2319                         else if (size == 2)
2320                                 retval = stlink_usb_read_mem16(handle, addr, bytes_remaining, buffer);
2321                         else
2322                                 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
2323                 } else
2324                         retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
2325
2326                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2327                         usleep((1<<retries++) * 1000);
2328                         continue;
2329                 }
2330                 if (retval != ERROR_OK)
2331                         return retval;
2332
2333                 buffer += bytes_remaining;
2334                 addr += bytes_remaining;
2335                 count -= bytes_remaining;
2336         }
2337
2338         return retval;
2339 }
2340
2341 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
2342                 uint32_t count, const uint8_t *buffer)
2343 {
2344         int retval = ERROR_OK;
2345         uint32_t bytes_remaining;
2346         int retries = 0;
2347         struct stlink_usb_handle_s *h = handle;
2348
2349         /* calculate byte count */
2350         count *= size;
2351
2352         /* switch to 8 bit if stlink does not support 16 bit memory read */
2353         if (size == 2 && !(h->version.flags & STLINK_F_HAS_MEM_16BIT))
2354                 size = 1;
2355
2356         while (count) {
2357
2358                 bytes_remaining = (size != 1) ? \
2359                                 stlink_max_block_size(h->max_mem_packet, addr) : stlink_usb_block(h);
2360
2361                 if (count < bytes_remaining)
2362                         bytes_remaining = count;
2363
2364                 if (h->transport == HL_TRANSPORT_SWIM) {
2365                         retval = stlink_swim_writebytes(handle, addr, bytes_remaining, buffer);
2366                         if (retval != ERROR_OK)
2367                                 return retval;
2368                 } else
2369                 /*
2370                  * all stlink support 8/32bit memory read/writes and only from
2371                  * stlink V2J26 there is support for 16 bit memory read/write.
2372                  * Honour 32 bit and, if possible, 16 bit too. Otherwise, handle
2373                  * as 8bit access.
2374                  */
2375                 if (size != 1) {
2376
2377                         /* When in jtag mode the stlink uses the auto-increment functionality.
2378                          * However it expects us to pass the data correctly, this includes
2379                          * alignment and any page boundaries. We already do this as part of the
2380                          * adi_v5 implementation, but the stlink is a hla adapter and so this
2381                          * needs implementing manually.
2382                          * currently this only affects jtag mode, according to ST they do single
2383                          * access in SWD mode - but this may change and so we do it for both modes */
2384
2385                         /* we first need to check for any unaligned bytes */
2386                         if (addr & (size - 1)) {
2387
2388                                 uint32_t head_bytes = size - (addr & (size - 1));
2389                                 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
2390                                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2391                                         usleep((1<<retries++) * 1000);
2392                                         continue;
2393                                 }
2394                                 if (retval != ERROR_OK)
2395                                         return retval;
2396                                 buffer += head_bytes;
2397                                 addr += head_bytes;
2398                                 count -= head_bytes;
2399                                 bytes_remaining -= head_bytes;
2400                         }
2401
2402                         if (bytes_remaining & (size - 1))
2403                                 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
2404                         else if (size == 2)
2405                                 retval = stlink_usb_write_mem16(handle, addr, bytes_remaining, buffer);
2406                         else
2407                                 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
2408
2409                 } else
2410                         retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
2411                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
2412                         usleep((1<<retries++) * 1000);
2413                         continue;
2414                 }
2415                 if (retval != ERROR_OK)
2416                         return retval;
2417
2418                 buffer += bytes_remaining;
2419                 addr += bytes_remaining;
2420                 count -= bytes_remaining;
2421         }
2422
2423         return retval;
2424 }
2425
2426 /** */
2427 static int stlink_usb_override_target(const char *targetname)
2428 {
2429         return !strcmp(targetname, "cortex_m");
2430 }
2431
2432 static int stlink_speed_swim(void *handle, int khz, bool query)
2433 {
2434         /*
2435                         we dont care what the khz rate is
2436                         we only have low and high speed...
2437                         before changing speed the SWIM_CSR HS bit
2438                         must be updated
2439          */
2440         if (khz == 0)
2441                 stlink_swim_speed(handle, 0);
2442         else
2443                 stlink_swim_speed(handle, 1);
2444         return khz;
2445 }
2446
2447 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
2448 {
2449         unsigned int i;
2450         int speed_index = -1;
2451         int speed_diff = INT_MAX;
2452         int last_valid_speed = -1;
2453         bool match = true;
2454
2455         for (i = 0; i < map_size; i++) {
2456                 if (!map[i].speed)
2457                         continue;
2458                 last_valid_speed = i;
2459                 if (khz == map[i].speed) {
2460                         speed_index = i;
2461                         break;
2462                 } else {
2463                         int current_diff = khz - map[i].speed;
2464                         /* get abs value for comparison */
2465                         current_diff = (current_diff > 0) ? current_diff : -current_diff;
2466                         if ((current_diff < speed_diff) && khz >= map[i].speed) {
2467                                 speed_diff = current_diff;
2468                                 speed_index = i;
2469                         }
2470                 }
2471         }
2472
2473         if (speed_index == -1) {
2474                 /* this will only be here if we cannot match the slow speed.
2475                  * use the slowest speed we support.*/
2476                 speed_index = last_valid_speed;
2477                 match = false;
2478         } else if (i == map_size)
2479                 match = false;
2480
2481         if (!match && query) {
2482                 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz", \
2483                                 khz, map[speed_index].speed);
2484         }
2485
2486         return speed_index;
2487 }
2488
2489 static int stlink_speed_swd(void *handle, int khz, bool query)
2490 {
2491         int speed_index;
2492         struct stlink_usb_handle_s *h = handle;
2493
2494         /* old firmware cannot change it */
2495         if (!(h->version.flags & STLINK_F_HAS_SWD_SET_FREQ))
2496                 return khz;
2497
2498         speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
2499                 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
2500
2501         if (!query) {
2502                 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
2503                 if (result != ERROR_OK) {
2504                         LOG_ERROR("Unable to set adapter speed");
2505                         return khz;
2506                 }
2507         }
2508
2509         return stlink_khz_to_speed_map_swd[speed_index].speed;
2510 }
2511
2512 static int stlink_speed_jtag(void *handle, int khz, bool query)
2513 {
2514         int speed_index;
2515         struct stlink_usb_handle_s *h = handle;
2516
2517         /* old firmware cannot change it */
2518         if (!(h->version.flags & STLINK_F_HAS_JTAG_SET_FREQ))
2519                 return khz;
2520
2521         speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2522                 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2523
2524         if (!query) {
2525                 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2526                 if (result != ERROR_OK) {
2527                         LOG_ERROR("Unable to set adapter speed");
2528                         return khz;
2529                 }
2530         }
2531
2532         return stlink_khz_to_speed_map_jtag[speed_index].speed;
2533 }
2534
2535 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2536 {
2537         unsigned int i;
2538
2539         LOG_DEBUG("Supported clock speeds are:");
2540         for (i = 0; i < map_size; i++)
2541                 if (map[i].speed)
2542                         LOG_DEBUG("%d kHz", map[i].speed);
2543 }
2544
2545 static int stlink_get_com_freq(void *handle, bool is_jtag, struct speed_map *map)
2546 {
2547         struct stlink_usb_handle_s *h = handle;
2548         int i;
2549
2550         if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2551                 LOG_ERROR("Unknown command");
2552                 return 0;
2553         }
2554
2555         stlink_usb_init_buffer(handle, h->rx_ep, 16);
2556
2557         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2558         h->cmdbuf[h->cmdidx++] = STLINK_APIV3_GET_COM_FREQ;
2559         h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2560
2561         int res = stlink_usb_xfer_errcheck(handle, h->databuf, 52);
2562
2563         int size = h->databuf[8];
2564
2565         if (size > STLINK_V3_MAX_FREQ_NB)
2566                 size = STLINK_V3_MAX_FREQ_NB;
2567
2568         for (i = 0; i < size; i++) {
2569                 map[i].speed = le_to_h_u32(&h->databuf[12 + 4 * i]);
2570                 map[i].speed_divisor = i;
2571         }
2572
2573         /* set to zero all the next entries */
2574         for (i = size; i < STLINK_V3_MAX_FREQ_NB; i++)
2575                 map[i].speed = 0;
2576
2577         return res;
2578 }
2579
2580 static int stlink_set_com_freq(void *handle, bool is_jtag, unsigned int frequency)
2581 {
2582         struct stlink_usb_handle_s *h = handle;
2583
2584         if (h->version.jtag_api != STLINK_JTAG_API_V3) {
2585                 LOG_ERROR("Unknown command");
2586                 return 0;
2587         }
2588
2589         stlink_usb_init_buffer(handle, h->rx_ep, 16);
2590
2591         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
2592         h->cmdbuf[h->cmdidx++] = STLINK_APIV3_SET_COM_FREQ;
2593         h->cmdbuf[h->cmdidx++] = is_jtag ? 1 : 0;
2594         h->cmdbuf[h->cmdidx++] = 0;
2595
2596         h_u32_to_le(&h->cmdbuf[4], frequency);
2597
2598         return stlink_usb_xfer_errcheck(handle, h->databuf, 8);
2599 }
2600
2601 static int stlink_speed_v3(void *handle, bool is_jtag, int khz, bool query)
2602 {
2603         struct stlink_usb_handle_s *h = handle;
2604         int speed_index;
2605         struct speed_map map[STLINK_V3_MAX_FREQ_NB];
2606
2607         stlink_get_com_freq(h, is_jtag, map);
2608
2609         speed_index = stlink_match_speed_map(map, ARRAY_SIZE(map), khz, query);
2610
2611         if (!query) {
2612                 int result = stlink_set_com_freq(h, is_jtag, map[speed_index].speed);
2613                 if (result != ERROR_OK) {
2614                         LOG_ERROR("Unable to set adapter speed");
2615                         return khz;
2616                 }
2617         }
2618         return map[speed_index].speed;
2619 }
2620
2621 static int stlink_speed(void *handle, int khz, bool query)
2622 {
2623         struct stlink_usb_handle_s *h = handle;
2624
2625         if (!handle)
2626                 return khz;
2627
2628         switch (h->transport) {
2629         case HL_TRANSPORT_SWIM:
2630                 return stlink_speed_swim(handle, khz, query);
2631                 break;
2632         case HL_TRANSPORT_SWD:
2633                 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2634                         return stlink_speed_v3(handle, false, khz, query);
2635                 else
2636                         return stlink_speed_swd(handle, khz, query);
2637                 break;
2638         case HL_TRANSPORT_JTAG:
2639                 if (h->version.jtag_api == STLINK_JTAG_API_V3)
2640                         return stlink_speed_v3(handle, true, khz, query);
2641                 else
2642                         return stlink_speed_jtag(handle, khz, query);
2643                 break;
2644         default:
2645                 break;
2646         }
2647
2648         return khz;
2649 }
2650
2651 /** */
2652 static int stlink_usb_close(void *handle)
2653 {
2654         int res;
2655         uint8_t mode;
2656         enum stlink_mode emode;
2657         struct stlink_usb_handle_s *h = handle;
2658
2659         if (h && h->fd)
2660                 res = stlink_usb_current_mode(handle, &mode);
2661         else
2662                 res = ERROR_FAIL;
2663         /* do not exit if return code != ERROR_OK,
2664            it prevents us from closing jtag_libusb */
2665
2666         if (res == ERROR_OK) {
2667                 /* try to exit current mode */
2668                 switch (mode) {
2669                         case STLINK_DEV_DFU_MODE:
2670                                 emode = STLINK_MODE_DFU;
2671                                 break;
2672                         case STLINK_DEV_DEBUG_MODE:
2673                                 emode = STLINK_MODE_DEBUG_SWD;
2674                                 break;
2675                         case STLINK_DEV_SWIM_MODE:
2676                                 emode = STLINK_MODE_DEBUG_SWIM;
2677                                 break;
2678                         case STLINK_DEV_BOOTLOADER_MODE:
2679                         case STLINK_DEV_MASS_MODE:
2680                         default:
2681                                 emode = STLINK_MODE_UNKNOWN;
2682                                 break;
2683                 }
2684
2685                 if (emode != STLINK_MODE_UNKNOWN)
2686                         stlink_usb_mode_leave(handle, emode);
2687                         /* do not check return code, it prevent
2688                         us from closing jtag_libusb */
2689         }
2690
2691         if (h && h->fd)
2692                 jtag_libusb_close(h->fd);
2693
2694         free(h);
2695
2696         return ERROR_OK;
2697 }
2698
2699 /** */
2700 static int stlink_usb_open(struct hl_interface_param_s *param, void **fd)
2701 {
2702         int err, retry_count = 1;
2703         struct stlink_usb_handle_s *h;
2704
2705         LOG_DEBUG("stlink_usb_open");
2706
2707         h = calloc(1, sizeof(struct stlink_usb_handle_s));
2708
2709         if (h == 0) {
2710                 LOG_DEBUG("malloc failed");
2711                 return ERROR_FAIL;
2712         }
2713
2714         h->transport = param->transport;
2715
2716         for (unsigned i = 0; param->vid[i]; i++) {
2717                 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
2718                           param->transport, param->vid[i], param->pid[i],
2719                           param->serial ? param->serial : "");
2720         }
2721
2722         /*
2723           On certain host USB configurations(e.g. MacBook Air)
2724           STLINKv2 dongle seems to have its FW in a funky state if,
2725           after plugging it in, you try to use openocd with it more
2726           then once (by launching and closing openocd). In cases like
2727           that initial attempt to read the FW info via
2728           stlink_usb_version will fail and the device has to be reset
2729           in order to become operational.
2730          */
2731         do {
2732                 if (jtag_libusb_open(param->vid, param->pid, param->serial, &h->fd) != ERROR_OK) {
2733                         LOG_ERROR("open failed");
2734                         goto error_open;
2735                 }
2736
2737                 jtag_libusb_set_configuration(h->fd, 0);
2738
2739                 if (jtag_libusb_claim_interface(h->fd, 0) != ERROR_OK) {
2740                         LOG_DEBUG("claim interface failed");
2741                         goto error_open;
2742                 }
2743
2744                 /* RX EP is common for all versions */
2745                 h->rx_ep = STLINK_RX_EP;
2746
2747                 uint16_t pid;
2748                 if (jtag_libusb_get_pid(jtag_libusb_get_device(h->fd), &pid) != ERROR_OK) {
2749                         LOG_DEBUG("libusb_get_pid failed");
2750                         goto error_open;
2751                 }
2752
2753                 /* wrap version for first read */
2754                 switch (pid) {
2755                         case STLINK_V1_PID:
2756                                 h->version.stlink = 1;
2757                                 h->tx_ep = STLINK_TX_EP;
2758                                 break;
2759                         case STLINK_V3_USBLOADER_PID:
2760                         case STLINK_V3E_PID:
2761                         case STLINK_V3S_PID:
2762                         case STLINK_V3_2VCP_PID:
2763                                 h->version.stlink = 3;
2764                                 h->tx_ep = STLINK_V2_1_TX_EP;
2765                                 h->trace_ep = STLINK_V2_1_TRACE_EP;
2766                                 break;
2767                         case STLINK_V2_1_PID:
2768                         case STLINK_V2_1_NO_MSD_PID:
2769                                 h->version.stlink = 2;
2770                                 h->tx_ep = STLINK_V2_1_TX_EP;
2771                                 h->trace_ep = STLINK_V2_1_TRACE_EP;
2772                                 break;
2773                         default:
2774                         /* fall through - we assume V2 to be the default version*/
2775                         case STLINK_V2_PID:
2776                                 h->version.stlink = 2;
2777                                 h->tx_ep = STLINK_TX_EP;
2778                                 h->trace_ep = STLINK_TRACE_EP;
2779                                 break;
2780                 }
2781
2782                 /* get the device version */
2783                 err = stlink_usb_version(h);
2784
2785                 if (err == ERROR_OK) {
2786                         break;
2787                 } else if (h->version.stlink == 1 ||
2788                            retry_count == 0) {
2789                         LOG_ERROR("read version failed");
2790                         goto error_open;
2791                 } else {
2792                         err = jtag_libusb_release_interface(h->fd, 0);
2793                         if (err != ERROR_OK) {
2794                                 LOG_ERROR("release interface failed");
2795                                 goto error_open;
2796                         }
2797
2798                         err = jtag_libusb_reset_device(h->fd);
2799                         if (err != ERROR_OK) {
2800                                 LOG_ERROR("reset device failed");
2801                                 goto error_open;
2802                         }
2803
2804                         jtag_libusb_close(h->fd);
2805                         /*
2806                           Give the device one second to settle down and
2807                           reenumerate.
2808                          */
2809                         usleep(1 * 1000 * 1000);
2810                         retry_count--;
2811                 }
2812         } while (1);
2813
2814         /* check if mode is supported */
2815         err = ERROR_OK;
2816
2817         switch (h->transport) {
2818                 case HL_TRANSPORT_SWD:
2819                         if (h->version.jtag_api == STLINK_JTAG_API_V1)
2820                                 err = ERROR_FAIL;
2821                         /* fall-through */
2822                 case HL_TRANSPORT_JTAG:
2823                         if (h->version.jtag == 0)
2824                                 err = ERROR_FAIL;
2825                         break;
2826                 case HL_TRANSPORT_SWIM:
2827                         if (h->version.swim == 0)
2828                                 err = ERROR_FAIL;
2829                         break;
2830                 default:
2831                         err = ERROR_FAIL;
2832                         break;
2833         }
2834
2835         if (err != ERROR_OK) {
2836                 LOG_ERROR("mode (transport) not supported by device");
2837                 goto error_open;
2838         }
2839
2840         /* initialize the debug hardware */
2841         err = stlink_usb_init_mode(h, param->connect_under_reset, param->initial_interface_speed);
2842
2843         if (err != ERROR_OK) {
2844                 LOG_ERROR("init mode failed (unable to connect to the target)");
2845                 goto error_open;
2846         }
2847
2848         if (h->transport == HL_TRANSPORT_SWIM) {
2849                 err = stlink_swim_enter(h);
2850                 if (err != ERROR_OK) {
2851                         LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
2852                         goto error_open;
2853                 }
2854                 *fd = h;
2855                 h->max_mem_packet = STLINK_DATA_SIZE;
2856                 return ERROR_OK;
2857         }
2858
2859         /* get cpuid, so we can determine the max page size
2860          * start with a safe default */
2861         h->max_mem_packet = (1 << 10);
2862
2863         uint8_t buffer[4];
2864         err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
2865         if (err == ERROR_OK) {
2866                 uint32_t cpuid = le_to_h_u32(buffer);
2867                 int i = (cpuid >> 4) & 0xf;
2868                 if (i == 4 || i == 3) {
2869                         /* Cortex-M3/M4 has 4096 bytes autoincrement range */
2870                         h->max_mem_packet = (1 << 12);
2871                 }
2872         }
2873
2874         LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
2875
2876         *fd = h;
2877
2878         return ERROR_OK;
2879
2880 error_open:
2881         stlink_usb_close(h);
2882
2883         return ERROR_FAIL;
2884 }
2885
2886 int stlink_config_trace(void *handle, bool enabled, enum tpiu_pin_protocol pin_protocol,
2887                         uint32_t port_size, unsigned int *trace_freq)
2888 {
2889         struct stlink_usb_handle_s *h = handle;
2890
2891         if (enabled && (!(h->version.flags & STLINK_F_HAS_TRACE) ||
2892                         pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART)) {
2893                 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
2894                 return ERROR_FAIL;
2895         }
2896
2897         if (!enabled) {
2898                 stlink_usb_trace_disable(h);
2899                 return ERROR_OK;
2900         }
2901
2902         if (*trace_freq > STLINK_TRACE_MAX_HZ) {
2903                 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
2904                           STLINK_TRACE_MAX_HZ);
2905                 return ERROR_FAIL;
2906         }
2907
2908         stlink_usb_trace_disable(h);
2909
2910         if (!*trace_freq)
2911                 *trace_freq = STLINK_TRACE_MAX_HZ;
2912         h->trace.source_hz = *trace_freq;
2913
2914         return stlink_usb_trace_enable(h);
2915 }
2916
2917 /** */
2918 struct hl_layout_api_s stlink_usb_layout_api = {
2919         /** */
2920         .open = stlink_usb_open,
2921         /** */
2922         .close = stlink_usb_close,
2923         /** */
2924         .idcode = stlink_usb_idcode,
2925         /** */
2926         .state = stlink_usb_state,
2927         /** */
2928         .reset = stlink_usb_reset,
2929         /** */
2930         .assert_srst = stlink_usb_assert_srst,
2931         /** */
2932         .run = stlink_usb_run,
2933         /** */
2934         .halt = stlink_usb_halt,
2935         /** */
2936         .step = stlink_usb_step,
2937         /** */
2938         .read_regs = stlink_usb_read_regs,
2939         /** */
2940         .read_reg = stlink_usb_read_reg,
2941         /** */
2942         .write_reg = stlink_usb_write_reg,
2943         /** */
2944         .read_mem = stlink_usb_read_mem,
2945         /** */
2946         .write_mem = stlink_usb_write_mem,
2947         /** */
2948         .write_debug_reg = stlink_usb_write_debug_reg,
2949         /** */
2950         .override_target = stlink_usb_override_target,
2951         /** */
2952         .speed = stlink_speed,
2953         /** */
2954         .config_trace = stlink_config_trace,
2955         /** */
2956         .poll_trace = stlink_usb_trace_read,
2957 };