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