stlink: add JTAG speed selection
[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 #define ENDPOINT_IN  0x80
45 #define ENDPOINT_OUT 0x00
46
47 #define STLINK_WRITE_TIMEOUT 1000
48 #define STLINK_READ_TIMEOUT 1000
49
50 #define STLINK_NULL_EP        0
51 #define STLINK_RX_EP          (1|ENDPOINT_IN)
52 #define STLINK_TX_EP          (2|ENDPOINT_OUT)
53 #define STLINK_TRACE_EP       (3|ENDPOINT_IN)
54
55 #define STLINK_V2_1_TX_EP     (1|ENDPOINT_OUT)
56 #define STLINK_V2_1_TRACE_EP  (2|ENDPOINT_IN)
57
58 #define STLINK_SG_SIZE        (31)
59 #define STLINK_DATA_SIZE      (4096)
60 #define STLINK_CMD_SIZE_V2    (16)
61 #define STLINK_CMD_SIZE_V1    (10)
62
63 #define STLINK_V1_PID         (0x3744)
64 #define STLINK_V2_PID         (0x3748)
65 #define STLINK_V2_1_PID       (0x374B)
66 #define STLINK_V2_1_NO_MSD_PID  (0x3752)
67
68 /* the current implementation of the stlink limits
69  * 8bit read/writes to max 64 bytes. */
70 #define STLINK_MAX_RW8          (64)
71
72 /* "WAIT" responses will be retried (with exponential backoff) at
73  * most this many times before failing to caller.
74  */
75 #define MAX_WAIT_RETRIES 8
76
77 enum stlink_jtag_api_version {
78         STLINK_JTAG_API_V1 = 1,
79         STLINK_JTAG_API_V2,
80 };
81
82 /** */
83 struct stlink_usb_version {
84         /** */
85         int stlink;
86         /** */
87         int jtag;
88         /** */
89         int swim;
90         /** highest supported jtag api version */
91         enum stlink_jtag_api_version jtag_api_max;
92 };
93
94 /** */
95 struct stlink_usb_handle_s {
96         /** */
97         struct jtag_libusb_device_handle *fd;
98         /** */
99         struct libusb_transfer *trans;
100         /** */
101         uint8_t rx_ep;
102         /** */
103         uint8_t tx_ep;
104         /** */
105         uint8_t trace_ep;
106         /** */
107         uint8_t cmdbuf[STLINK_SG_SIZE];
108         /** */
109         uint8_t cmdidx;
110         /** */
111         uint8_t direction;
112         /** */
113         uint8_t databuf[STLINK_DATA_SIZE];
114         /** */
115         uint32_t max_mem_packet;
116         /** */
117         enum hl_transports transport;
118         /** */
119         struct stlink_usb_version version;
120         /** */
121         uint16_t vid;
122         /** */
123         uint16_t pid;
124         /** this is the currently used jtag api */
125         enum stlink_jtag_api_version jtag_api;
126         /** */
127         struct {
128                 /** whether SWO tracing is enabled or not */
129                 bool enabled;
130                 /** trace module source clock */
131                 uint32_t source_hz;
132         } trace;
133         /** reconnect is needed next time we try to query the
134          * status */
135         bool reconnect_pending;
136 };
137
138 #define STLINK_SWIM_ERR_OK             0x00
139 #define STLINK_SWIM_BUSY               0x01
140 #define STLINK_DEBUG_ERR_OK            0x80
141 #define STLINK_DEBUG_ERR_FAULT         0x81
142 #define STLINK_SWD_AP_WAIT             0x10
143 #define STLINK_SWD_AP_FAULT            0x11
144 #define STLINK_SWD_AP_ERROR            0x12
145 #define STLINK_SWD_AP_PARITY_ERROR     0x13
146 #define STLINK_JTAG_WRITE_ERROR        0x0c
147 #define STLINK_JTAG_WRITE_VERIF_ERROR  0x0d
148 #define STLINK_SWD_DP_WAIT             0x14
149 #define STLINK_SWD_DP_FAULT            0x15
150 #define STLINK_SWD_DP_ERROR            0x16
151 #define STLINK_SWD_DP_PARITY_ERROR     0x17
152
153 #define STLINK_SWD_AP_WDATA_ERROR      0x18
154 #define STLINK_SWD_AP_STICKY_ERROR     0x19
155 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
156
157 #define STLINK_CORE_RUNNING            0x80
158 #define STLINK_CORE_HALTED             0x81
159 #define STLINK_CORE_STAT_UNKNOWN       -1
160
161 #define STLINK_GET_VERSION             0xF1
162 #define STLINK_DEBUG_COMMAND           0xF2
163 #define STLINK_DFU_COMMAND             0xF3
164 #define STLINK_SWIM_COMMAND            0xF4
165 #define STLINK_GET_CURRENT_MODE        0xF5
166 #define STLINK_GET_TARGET_VOLTAGE      0xF7
167
168 #define STLINK_DEV_DFU_MODE            0x00
169 #define STLINK_DEV_MASS_MODE           0x01
170 #define STLINK_DEV_DEBUG_MODE          0x02
171 #define STLINK_DEV_SWIM_MODE           0x03
172 #define STLINK_DEV_BOOTLOADER_MODE     0x04
173 #define STLINK_DEV_UNKNOWN_MODE        -1
174
175 #define STLINK_DFU_EXIT                0x07
176
177 /*
178         STLINK_SWIM_ENTER_SEQ
179         1.3ms low then 750Hz then 1.5kHz
180
181         STLINK_SWIM_GEN_RST
182         STM8 DM pulls reset pin low 50us
183
184         STLINK_SWIM_SPEED
185         uint8_t (0=low|1=high)
186
187         STLINK_SWIM_WRITEMEM
188         uint16_t length
189         uint32_t address
190
191         STLINK_SWIM_RESET
192         send syncronization seq (16us low, response 64 clocks low)
193 */
194 #define STLINK_SWIM_ENTER                  0x00
195 #define STLINK_SWIM_EXIT                   0x01
196 #define STLINK_SWIM_READ_CAP               0x02
197 #define STLINK_SWIM_SPEED                  0x03
198 #define STLINK_SWIM_ENTER_SEQ              0x04
199 #define STLINK_SWIM_GEN_RST                0x05
200 #define STLINK_SWIM_RESET                  0x06
201 #define STLINK_SWIM_ASSERT_RESET           0x07
202 #define STLINK_SWIM_DEASSERT_RESET         0x08
203 #define STLINK_SWIM_READSTATUS             0x09
204 #define STLINK_SWIM_WRITEMEM               0x0a
205 #define STLINK_SWIM_READMEM                0x0b
206 #define STLINK_SWIM_READBUF                0x0c
207
208 #define STLINK_DEBUG_ENTER_JTAG            0x00
209 #define STLINK_DEBUG_GETSTATUS             0x01
210 #define STLINK_DEBUG_FORCEDEBUG            0x02
211 #define STLINK_DEBUG_APIV1_RESETSYS        0x03
212 #define STLINK_DEBUG_APIV1_READALLREGS     0x04
213 #define STLINK_DEBUG_APIV1_READREG         0x05
214 #define STLINK_DEBUG_APIV1_WRITEREG        0x06
215 #define STLINK_DEBUG_READMEM_32BIT         0x07
216 #define STLINK_DEBUG_WRITEMEM_32BIT        0x08
217 #define STLINK_DEBUG_RUNCORE               0x09
218 #define STLINK_DEBUG_STEPCORE              0x0a
219 #define STLINK_DEBUG_APIV1_SETFP           0x0b
220 #define STLINK_DEBUG_READMEM_8BIT          0x0c
221 #define STLINK_DEBUG_WRITEMEM_8BIT         0x0d
222 #define STLINK_DEBUG_APIV1_CLEARFP         0x0e
223 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG   0x0f
224 #define STLINK_DEBUG_APIV1_SETWATCHPOINT   0x10
225
226 #define STLINK_DEBUG_ENTER_JTAG            0x00
227 #define STLINK_DEBUG_ENTER_SWD             0xa3
228
229 #define STLINK_DEBUG_APIV1_ENTER           0x20
230 #define STLINK_DEBUG_EXIT                  0x21
231 #define STLINK_DEBUG_READCOREID            0x22
232
233 #define STLINK_DEBUG_APIV2_ENTER           0x30
234 #define STLINK_DEBUG_APIV2_READ_IDCODES    0x31
235 #define STLINK_DEBUG_APIV2_RESETSYS        0x32
236 #define STLINK_DEBUG_APIV2_READREG         0x33
237 #define STLINK_DEBUG_APIV2_WRITEREG        0x34
238 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG   0x35
239 #define STLINK_DEBUG_APIV2_READDEBUGREG    0x36
240
241 #define STLINK_DEBUG_APIV2_READALLREGS     0x3A
242 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
243 #define STLINK_DEBUG_APIV2_DRIVE_NRST      0x3C
244
245 #define STLINK_DEBUG_APIV2_START_TRACE_RX  0x40
246 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX   0x41
247 #define STLINK_DEBUG_APIV2_GET_TRACE_NB    0x42
248 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ    0x43
249 #define STLINK_DEBUG_APIV2_JTAG_SET_FREQ   0x44
250
251 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW   0x00
252 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH  0x01
253 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
254
255 #define STLINK_TRACE_SIZE               4096
256 #define STLINK_TRACE_MAX_HZ             2000000
257 #define STLINK_TRACE_MIN_VERSION        13
258
259 /** */
260 enum stlink_mode {
261         STLINK_MODE_UNKNOWN = 0,
262         STLINK_MODE_DFU,
263         STLINK_MODE_MASS,
264         STLINK_MODE_DEBUG_JTAG,
265         STLINK_MODE_DEBUG_SWD,
266         STLINK_MODE_DEBUG_SWIM
267 };
268
269 #define REQUEST_SENSE        0x03
270 #define REQUEST_SENSE_LENGTH 18
271
272 struct speed_map {
273         int speed;
274         int speed_divisor;
275 };
276
277 /* SWD clock speed */
278 static const struct speed_map stlink_khz_to_speed_map_swd[] = {
279         {4000, 0},
280         {1800, 1}, /* default */
281         {1200, 2},
282         {950,  3},
283         {480,  7},
284         {240, 15},
285         {125, 31},
286         {100, 40},
287         {50,  79},
288         {25, 158},
289         {15, 265},
290         {5,  798}
291 };
292
293 /* JTAG clock speed */
294 static const struct speed_map stlink_khz_to_speed_map_jtag[] = {
295         {18000, 2},
296         {9000,  4},
297         {4500,  8},
298         {2250, 16},
299         {1125, 32}, /* default */
300         {562,  64},
301         {281, 128},
302         {140, 256}
303 };
304
305 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
306 static int stlink_swim_status(void *handle);
307
308 /** */
309 static int stlink_usb_xfer_v1_get_status(void *handle)
310 {
311         struct stlink_usb_handle_s *h = handle;
312
313         assert(handle != NULL);
314
315         /* read status */
316         memset(h->cmdbuf, 0, STLINK_SG_SIZE);
317
318         if (jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)h->cmdbuf,
319                         13, STLINK_READ_TIMEOUT) != 13)
320                 return ERROR_FAIL;
321
322         uint32_t t1;
323
324         t1 = buf_get_u32(h->cmdbuf, 0, 32);
325
326         /* check for USBS */
327         if (t1 != 0x53425355)
328                 return ERROR_FAIL;
329         /*
330          * CSW status:
331          * 0 success
332          * 1 command failure
333          * 2 phase error
334          */
335         if (h->cmdbuf[12] != 0)
336                 return ERROR_FAIL;
337
338         return ERROR_OK;
339 }
340
341 /** */
342 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
343 {
344         struct stlink_usb_handle_s *h = handle;
345
346         assert(handle != NULL);
347
348         if (jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)h->cmdbuf, cmdsize,
349                         STLINK_WRITE_TIMEOUT) != cmdsize) {
350                 return ERROR_FAIL;
351         }
352
353         if (h->direction == h->tx_ep && size) {
354                 if (jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)buf,
355                                 size, STLINK_WRITE_TIMEOUT) != size) {
356                         LOG_DEBUG("bulk write failed");
357                         return ERROR_FAIL;
358                 }
359         } else if (h->direction == h->rx_ep && size) {
360                 if (jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)buf,
361                                 size, STLINK_READ_TIMEOUT) != size) {
362                         LOG_DEBUG("bulk read failed");
363                         return ERROR_FAIL;
364                 }
365         }
366
367         return ERROR_OK;
368 }
369
370 /** */
371 static int stlink_usb_xfer_v1_get_sense(void *handle)
372 {
373         int res;
374         struct stlink_usb_handle_s *h = handle;
375
376         assert(handle != NULL);
377
378         stlink_usb_init_buffer(handle, h->rx_ep, 16);
379
380         h->cmdbuf[h->cmdidx++] = REQUEST_SENSE;
381         h->cmdbuf[h->cmdidx++] = 0;
382         h->cmdbuf[h->cmdidx++] = 0;
383         h->cmdbuf[h->cmdidx++] = 0;
384         h->cmdbuf[h->cmdidx++] = REQUEST_SENSE_LENGTH;
385
386         res = stlink_usb_xfer_rw(handle, REQUEST_SENSE_LENGTH, h->databuf, 16);
387
388         if (res != ERROR_OK)
389                 return res;
390
391         if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK)
392                 return ERROR_FAIL;
393
394         return ERROR_OK;
395 }
396
397 /*
398         transfers block in cmdbuf
399         <size> indicates number of bytes in the following
400         data phase.
401 */
402 static int stlink_usb_xfer(void *handle, const uint8_t *buf, int size)
403 {
404         int err, cmdsize = STLINK_CMD_SIZE_V2;
405         struct stlink_usb_handle_s *h = handle;
406
407         assert(handle != NULL);
408
409         if (h->version.stlink == 1) {
410                 cmdsize = STLINK_SG_SIZE;
411                 /* put length in bCBWCBLength */
412                 h->cmdbuf[14] = h->cmdidx-15;
413         }
414
415         err = stlink_usb_xfer_rw(handle, cmdsize, buf, size);
416
417         if (err != ERROR_OK)
418                 return err;
419
420         if (h->version.stlink == 1) {
421                 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK) {
422                         /* check csw status */
423                         if (h->cmdbuf[12] == 1) {
424                                 LOG_DEBUG("get sense");
425                                 if (stlink_usb_xfer_v1_get_sense(handle) != ERROR_OK)
426                                         return ERROR_FAIL;
427                         }
428                         return ERROR_FAIL;
429                 }
430         }
431
432         return ERROR_OK;
433 }
434
435 /**
436     Converts an STLINK status code held in the first byte of a response
437     to an openocd error, logs any error/wait status as debug output.
438 */
439 static int stlink_usb_error_check(void *handle)
440 {
441         struct stlink_usb_handle_s *h = handle;
442
443         assert(handle != NULL);
444
445         if (h->transport == HL_TRANSPORT_SWIM) {
446                 switch (h->databuf[0]) {
447                         case STLINK_SWIM_ERR_OK:
448                                 return ERROR_OK;
449                         case STLINK_SWIM_BUSY:
450                                 return ERROR_WAIT;
451                         default:
452                                 LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
453                                 return ERROR_FAIL;
454                 }
455         }
456
457         /* TODO: no error checking yet on api V1 */
458         if (h->jtag_api == STLINK_JTAG_API_V1)
459                 h->databuf[0] = STLINK_DEBUG_ERR_OK;
460
461         switch (h->databuf[0]) {
462                 case STLINK_DEBUG_ERR_OK:
463                         return ERROR_OK;
464                 case STLINK_DEBUG_ERR_FAULT:
465                         LOG_DEBUG("SWD fault response (0x%x)", STLINK_DEBUG_ERR_FAULT);
466                         return ERROR_FAIL;
467                 case STLINK_SWD_AP_WAIT:
468                         LOG_DEBUG("wait status SWD_AP_WAIT (0x%x)", STLINK_SWD_AP_WAIT);
469                         return ERROR_WAIT;
470                 case STLINK_SWD_DP_WAIT:
471                         LOG_DEBUG("wait status SWD_DP_WAIT (0x%x)", STLINK_SWD_DP_WAIT);
472                         return ERROR_WAIT;
473                 case STLINK_JTAG_WRITE_ERROR:
474                         LOG_DEBUG("Write error");
475                         return ERROR_FAIL;
476                 case STLINK_JTAG_WRITE_VERIF_ERROR:
477                         LOG_DEBUG("Write verify error, ignoring");
478                         return ERROR_OK;
479                 case STLINK_SWD_AP_FAULT:
480                         /* git://git.ac6.fr/openocd commit 657e3e885b9ee10
481                          * returns ERROR_OK with the comment:
482                          * Change in error status when reading outside RAM.
483                          * This fix allows CDT plugin to visualize memory.
484                          */
485                         LOG_DEBUG("STLINK_SWD_AP_FAULT");
486                         return ERROR_FAIL;
487                 case STLINK_SWD_AP_ERROR:
488                         LOG_DEBUG("STLINK_SWD_AP_ERROR");
489                         return ERROR_FAIL;
490                 case STLINK_SWD_AP_PARITY_ERROR:
491                         LOG_DEBUG("STLINK_SWD_AP_PARITY_ERROR");
492                         return ERROR_FAIL;
493                 case STLINK_SWD_DP_FAULT:
494                         LOG_DEBUG("STLINK_SWD_DP_FAULT");
495                         return ERROR_FAIL;
496                 case STLINK_SWD_DP_ERROR:
497                         LOG_DEBUG("STLINK_SWD_DP_ERROR");
498                         return ERROR_FAIL;
499                 case STLINK_SWD_DP_PARITY_ERROR:
500                         LOG_DEBUG("STLINK_SWD_DP_PARITY_ERROR");
501                         return ERROR_FAIL;
502                 case STLINK_SWD_AP_WDATA_ERROR:
503                         LOG_DEBUG("STLINK_SWD_AP_WDATA_ERROR");
504                         return ERROR_FAIL;
505                 case STLINK_SWD_AP_STICKY_ERROR:
506                         LOG_DEBUG("STLINK_SWD_AP_STICKY_ERROR");
507                         return ERROR_FAIL;
508                 case STLINK_SWD_AP_STICKYORUN_ERROR:
509                         LOG_DEBUG("STLINK_SWD_AP_STICKYORUN_ERROR");
510                         return ERROR_FAIL;
511                 default:
512                         LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
513                         return ERROR_FAIL;
514         }
515 }
516
517
518 /** Issue an STLINK command via USB transfer, with retries on any wait status responses.
519
520     Works for commands where the STLINK_DEBUG status is returned in the first
521     byte of the response packet. For SWIM a SWIM_READSTATUS is requested instead.
522
523     Returns an openocd result code.
524 */
525 static int stlink_cmd_allow_retry(void *handle, const uint8_t *buf, int size)
526 {
527         int retries = 0;
528         int res;
529         struct stlink_usb_handle_s *h = handle;
530
531         while (1) {
532                 if ((h->transport != HL_TRANSPORT_SWIM) || !retries) {
533                         res = stlink_usb_xfer(handle, buf, size);
534                         if (res != ERROR_OK)
535                                 return res;
536                 }
537
538                 if (h->transport == HL_TRANSPORT_SWIM) {
539                         res = stlink_swim_status(handle);
540                         if (res != ERROR_OK)
541                                 return res;
542                 }
543
544                 res = stlink_usb_error_check(handle);
545                 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
546                         usleep((1<<retries++) * 1000);
547                         continue;
548                 }
549                 return res;
550         }
551 }
552
553 /** */
554 static int stlink_usb_read_trace(void *handle, const uint8_t *buf, int size)
555 {
556         struct stlink_usb_handle_s *h = handle;
557
558         assert(handle != NULL);
559
560         assert(h->version.stlink >= 2);
561
562         if (jtag_libusb_bulk_read(h->fd, h->trace_ep, (char *)buf,
563                         size, STLINK_READ_TIMEOUT) != size) {
564                 LOG_ERROR("bulk trace read failed");
565                 return ERROR_FAIL;
566         }
567
568         return ERROR_OK;
569 }
570
571 /*
572         this function writes transfer length in
573         the right place in the cb
574 */
575 static void stlink_usb_set_cbw_transfer_datalength(void *handle, uint32_t size)
576 {
577         struct stlink_usb_handle_s *h = handle;
578
579         buf_set_u32(h->cmdbuf+8, 0, 32, size);
580 }
581
582 static void stlink_usb_xfer_v1_create_cmd(void *handle, uint8_t direction, uint32_t size)
583 {
584         struct stlink_usb_handle_s *h = handle;
585
586         /* fill the send buffer */
587         strcpy((char *)h->cmdbuf, "USBC");
588         h->cmdidx += 4;
589         /* csw tag not used */
590         buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, 0);
591         h->cmdidx += 4;
592         /* cbw data transfer length (in the following data phase in or out) */
593         buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, size);
594         h->cmdidx += 4;
595         /* cbw flags */
596         h->cmdbuf[h->cmdidx++] = (direction == h->rx_ep ? ENDPOINT_IN : ENDPOINT_OUT);
597         h->cmdbuf[h->cmdidx++] = 0; /* lun */
598         /* cdb clength (is filled in at xfer) */
599         h->cmdbuf[h->cmdidx++] = 0;
600 }
601
602 /** */
603 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size)
604 {
605         struct stlink_usb_handle_s *h = handle;
606
607         h->direction = direction;
608
609         h->cmdidx = 0;
610
611         memset(h->cmdbuf, 0, STLINK_SG_SIZE);
612         memset(h->databuf, 0, STLINK_DATA_SIZE);
613
614         if (h->version.stlink == 1)
615                 stlink_usb_xfer_v1_create_cmd(handle, direction, size);
616 }
617
618 /** */
619 static int stlink_usb_version(void *handle)
620 {
621         int res;
622         uint16_t v;
623         struct stlink_usb_handle_s *h = handle;
624
625         assert(handle != NULL);
626
627         stlink_usb_init_buffer(handle, h->rx_ep, 6);
628
629         h->cmdbuf[h->cmdidx++] = STLINK_GET_VERSION;
630
631         res = stlink_usb_xfer(handle, h->databuf, 6);
632
633         if (res != ERROR_OK)
634                 return res;
635
636         v = (h->databuf[0] << 8) | h->databuf[1];
637
638         h->version.stlink = (v >> 12) & 0x0f;
639         h->version.jtag = (v >> 6) & 0x3f;
640         h->version.swim = v & 0x3f;
641         h->vid = buf_get_u32(h->databuf, 16, 16);
642         h->pid = buf_get_u32(h->databuf, 32, 16);
643
644         /* set the supported jtag api version
645          * API V2 is supported since JTAG V11
646          */
647         if (h->version.jtag >= 11)
648                 h->version.jtag_api_max = STLINK_JTAG_API_V2;
649         else
650                 h->version.jtag_api_max = STLINK_JTAG_API_V1;
651
652         LOG_INFO("STLINK v%d JTAG v%d API v%d SWIM v%d VID 0x%04X PID 0x%04X",
653                 h->version.stlink,
654                 h->version.jtag,
655                 (h->version.jtag_api_max == STLINK_JTAG_API_V1) ? 1 : 2,
656                 h->version.swim,
657                 h->vid,
658                 h->pid);
659
660         return ERROR_OK;
661 }
662
663 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
664 {
665         struct stlink_usb_handle_s *h = handle;
666         uint32_t adc_results[2];
667
668         /* only supported by stlink/v2 and for firmware >= 13 */
669         if (h->version.stlink == 1 || h->version.jtag < 13)
670                 return ERROR_COMMAND_NOTFOUND;
671
672         stlink_usb_init_buffer(handle, h->rx_ep, 8);
673
674         h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
675
676         int result = stlink_usb_xfer(handle, h->databuf, 8);
677
678         if (result != ERROR_OK)
679                 return result;
680
681         /* convert result */
682         adc_results[0] = le_to_h_u32(h->databuf);
683         adc_results[1] = le_to_h_u32(h->databuf + 4);
684
685         *target_voltage = 0;
686
687         if (adc_results[0])
688                 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
689
690         LOG_INFO("Target voltage: %f", (double)*target_voltage);
691
692         return ERROR_OK;
693 }
694
695 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
696 {
697         struct stlink_usb_handle_s *h = handle;
698
699         assert(handle != NULL);
700
701         /* only supported by stlink/v2 and for firmware >= 22 */
702         if (h->version.stlink == 1 || h->version.jtag < 22)
703                 return ERROR_COMMAND_NOTFOUND;
704
705         stlink_usb_init_buffer(handle, h->rx_ep, 2);
706
707         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
708         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
709         h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
710         h->cmdidx += 2;
711
712         int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
713
714         if (result != ERROR_OK)
715                 return result;
716
717         return ERROR_OK;
718 }
719
720 static int stlink_usb_set_jtagclk(void *handle, uint16_t clk_divisor)
721 {
722         struct stlink_usb_handle_s *h = handle;
723
724         assert(handle != NULL);
725
726         /* only supported by stlink/v2 and for firmware >= 24 */
727         if (h->version.stlink == 1 || h->version.jtag < 24)
728                 return ERROR_COMMAND_NOTFOUND;
729
730         stlink_usb_init_buffer(handle, h->rx_ep, 2);
731
732         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
733         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_JTAG_SET_FREQ;
734         h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
735         h->cmdidx += 2;
736
737         int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
738
739         if (result != ERROR_OK)
740                 return result;
741
742         return ERROR_OK;
743 }
744
745 /** */
746 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
747 {
748         int res;
749         struct stlink_usb_handle_s *h = handle;
750
751         assert(handle != NULL);
752
753         stlink_usb_init_buffer(handle, h->rx_ep, 2);
754
755         h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
756
757         res = stlink_usb_xfer(handle, h->databuf, 2);
758
759         if (res != ERROR_OK)
760                 return res;
761
762         *mode = h->databuf[0];
763
764         return ERROR_OK;
765 }
766
767 /** */
768 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
769 {
770         int rx_size = 0;
771         struct stlink_usb_handle_s *h = handle;
772
773         assert(handle != NULL);
774
775         /* on api V2 we are able the read the latest command
776          * status
777          * TODO: we need the test on api V1 too
778          */
779         if (h->jtag_api == STLINK_JTAG_API_V2)
780                 rx_size = 2;
781
782         stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
783
784         switch (type) {
785                 case STLINK_MODE_DEBUG_JTAG:
786                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
787                         if (h->jtag_api == STLINK_JTAG_API_V1)
788                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
789                         else
790                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
791                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG;
792                         break;
793                 case STLINK_MODE_DEBUG_SWD:
794                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
795                         if (h->jtag_api == STLINK_JTAG_API_V1)
796                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
797                         else
798                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
799                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD;
800                         break;
801                 case STLINK_MODE_DEBUG_SWIM:
802                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
803                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
804                         /* no answer for this function... */
805                         rx_size = 0;
806                         break;
807                 case STLINK_MODE_DFU:
808                 case STLINK_MODE_MASS:
809                 default:
810                         return ERROR_FAIL;
811         }
812
813         return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
814 }
815
816 /** */
817 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
818 {
819         int res;
820         struct stlink_usb_handle_s *h = handle;
821
822         assert(handle != NULL);
823
824         stlink_usb_init_buffer(handle, STLINK_NULL_EP, 0);
825
826         switch (type) {
827                 case STLINK_MODE_DEBUG_JTAG:
828                 case STLINK_MODE_DEBUG_SWD:
829                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
830                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
831                         break;
832                 case STLINK_MODE_DEBUG_SWIM:
833                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
834                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
835                         break;
836                 case STLINK_MODE_DFU:
837                         h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
838                         h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
839                         break;
840                 case STLINK_MODE_MASS:
841                 default:
842                         return ERROR_FAIL;
843         }
844
845         res = stlink_usb_xfer(handle, 0, 0);
846
847         if (res != ERROR_OK)
848                 return res;
849
850         return ERROR_OK;
851 }
852
853 static int stlink_usb_assert_srst(void *handle, int srst);
854
855 static enum stlink_mode stlink_get_mode(enum hl_transports t)
856 {
857         switch (t) {
858         case HL_TRANSPORT_SWD:
859                 return STLINK_MODE_DEBUG_SWD;
860         case HL_TRANSPORT_JTAG:
861                 return STLINK_MODE_DEBUG_JTAG;
862         case HL_TRANSPORT_SWIM:
863                 return STLINK_MODE_DEBUG_SWIM;
864         default:
865                 return STLINK_MODE_UNKNOWN;
866         }
867 }
868
869 /** */
870 static int stlink_usb_init_mode(void *handle, bool connect_under_reset)
871 {
872         int res;
873         uint8_t mode;
874         enum stlink_mode emode;
875         struct stlink_usb_handle_s *h = handle;
876
877         assert(handle != NULL);
878
879         res = stlink_usb_current_mode(handle, &mode);
880
881         if (res != ERROR_OK)
882                 return res;
883
884         LOG_DEBUG("MODE: 0x%02X", mode);
885
886         /* try to exit current mode */
887         switch (mode) {
888                 case STLINK_DEV_DFU_MODE:
889                         emode = STLINK_MODE_DFU;
890                         break;
891                 case STLINK_DEV_DEBUG_MODE:
892                         emode = STLINK_MODE_DEBUG_SWD;
893                         break;
894                 case STLINK_DEV_SWIM_MODE:
895                         emode = STLINK_MODE_DEBUG_SWIM;
896                         break;
897                 case STLINK_DEV_BOOTLOADER_MODE:
898                 case STLINK_DEV_MASS_MODE:
899                 default:
900                         emode = STLINK_MODE_UNKNOWN;
901                         break;
902         }
903
904         if (emode != STLINK_MODE_UNKNOWN) {
905                 res = stlink_usb_mode_leave(handle, emode);
906
907                 if (res != ERROR_OK)
908                         return res;
909         }
910
911         res = stlink_usb_current_mode(handle, &mode);
912
913         if (res != ERROR_OK)
914                 return res;
915
916         /* we check the target voltage here as an aid to debugging connection problems.
917          * the stlink requires the target Vdd to be connected for reliable debugging.
918          * this cmd is supported in all modes except DFU
919          */
920         if (mode != STLINK_DEV_DFU_MODE) {
921
922                 float target_voltage;
923
924                 /* check target voltage (if supported) */
925                 res = stlink_usb_check_voltage(h, &target_voltage);
926
927                 if (res != ERROR_OK) {
928                         if (res != ERROR_COMMAND_NOTFOUND)
929                                 LOG_ERROR("voltage check failed");
930                         /* attempt to continue as it is not a catastrophic failure */
931                 } else {
932                         /* check for a sensible target voltage, operating range is 1.65-5.5v
933                          * according to datasheet */
934                         if (target_voltage < 1.5)
935                                 LOG_ERROR("target voltage may be too low for reliable debugging");
936                 }
937         }
938
939         LOG_DEBUG("MODE: 0x%02X", mode);
940
941         /* set selected mode */
942         emode = stlink_get_mode(h->transport);
943
944         if (emode == STLINK_MODE_UNKNOWN) {
945                 LOG_ERROR("selected mode (transport) not supported");
946                 return ERROR_FAIL;
947         }
948
949         /* preliminary SRST assert:
950          * We want SRST is asserted before activating debug signals (mode_enter).
951          * As the required mode has not been set, the adapter may not know what pin to use.
952          * Tested firmware STLINK v2 JTAG v29 API v2 SWIM v0 uses T_NRST pin by default
953          * Tested firmware STLINK v2 JTAG v27 API v2 SWIM v6 uses T_NRST pin by default
954          * after power on, SWIM_RST stays unchanged */
955         if (connect_under_reset && emode != STLINK_MODE_DEBUG_SWIM)
956                 stlink_usb_assert_srst(handle, 0);
957                 /* do not check the return status here, we will
958                    proceed and enter the desired mode below
959                    and try asserting srst again. */
960
961         res = stlink_usb_mode_enter(handle, emode);
962         if (res != ERROR_OK)
963                 return res;
964
965         /* assert SRST again: a little bit late but now the adapter knows for sure what pin to use */
966         if (connect_under_reset) {
967                 res = stlink_usb_assert_srst(handle, 0);
968                 if (res != ERROR_OK)
969                         return res;
970         }
971
972         res = stlink_usb_current_mode(handle, &mode);
973
974         if (res != ERROR_OK)
975                 return res;
976
977         LOG_DEBUG("MODE: 0x%02X", mode);
978
979         return ERROR_OK;
980 }
981
982 /* request status from last swim request */
983 static int stlink_swim_status(void *handle)
984 {
985         struct stlink_usb_handle_s *h = handle;
986         int res;
987
988         stlink_usb_init_buffer(handle, h->rx_ep, 4);
989         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
990         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READSTATUS;
991         res = stlink_usb_xfer(handle, h->databuf, 4);
992         if (res != ERROR_OK)
993                 return res;
994         return ERROR_OK;
995 }
996 /*
997         the purpose of this function is unknown...
998         capabilites? anyway for swim v6 it returns
999         0001020600000000
1000 */
1001 __attribute__((unused))
1002 static int stlink_swim_cap(void *handle, uint8_t *cap)
1003 {
1004         struct stlink_usb_handle_s *h = handle;
1005         int res;
1006
1007         stlink_usb_init_buffer(handle, h->rx_ep, 8);
1008         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1009         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READ_CAP;
1010         h->cmdbuf[h->cmdidx++] = 0x01;
1011         res = stlink_usb_xfer(handle, h->databuf, 8);
1012         if (res != ERROR_OK)
1013                 return res;
1014         memcpy(cap, h->databuf, 8);
1015         return ERROR_OK;
1016 }
1017
1018 /*      debug dongle assert/deassert sreset line */
1019 static int stlink_swim_assert_reset(void *handle, int reset)
1020 {
1021         struct stlink_usb_handle_s *h = handle;
1022         int res;
1023
1024         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1025         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1026         if (!reset)
1027                 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ASSERT_RESET;
1028         else
1029                 h->cmdbuf[h->cmdidx++] = STLINK_SWIM_DEASSERT_RESET;
1030         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1031         if (res != ERROR_OK)
1032                 return res;
1033         return ERROR_OK;
1034 }
1035
1036 /*
1037         send swim enter seq
1038         1.3ms low then 750Hz then 1.5kHz
1039 */
1040 static int stlink_swim_enter(void *handle)
1041 {
1042         struct stlink_usb_handle_s *h = handle;
1043         int res;
1044
1045         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1046         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1047         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER_SEQ;
1048         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1049         if (res != ERROR_OK)
1050                 return res;
1051         return ERROR_OK;
1052 }
1053
1054 /*      switch high/low speed swim */
1055 static int stlink_swim_speed(void *handle, int speed)
1056 {
1057         struct stlink_usb_handle_s *h = handle;
1058         int res;
1059
1060         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1061         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1062         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_SPEED;
1063         if (speed)
1064                 h->cmdbuf[h->cmdidx++] = 1;
1065         else
1066                 h->cmdbuf[h->cmdidx++] = 0;
1067         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1068         if (res != ERROR_OK)
1069                 return res;
1070         return ERROR_OK;
1071 }
1072
1073 /*
1074         initiate srst from swim.
1075         nrst is pulled low for 50us.
1076 */
1077 static int stlink_swim_generate_rst(void *handle)
1078 {
1079         struct stlink_usb_handle_s *h = handle;
1080         int res;
1081
1082         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1083         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1084         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_GEN_RST;
1085         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1086         if (res != ERROR_OK)
1087                 return res;
1088         return ERROR_OK;
1089 }
1090
1091 /*
1092         send resyncronize sequence
1093         swim is pulled low for 16us
1094         reply is 64 clks low
1095 */
1096 static int stlink_swim_resync(void *handle)
1097 {
1098         struct stlink_usb_handle_s *h = handle;
1099         int res;
1100
1101         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1102         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1103         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_RESET;
1104         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1105         if (res != ERROR_OK)
1106                 return res;
1107         return ERROR_OK;
1108 }
1109
1110 static int stlink_swim_writebytes(void *handle, uint32_t addr, uint32_t len, const uint8_t *data)
1111 {
1112         struct stlink_usb_handle_s *h = handle;
1113         int res;
1114         unsigned int i;
1115         unsigned int datalen = 0;
1116         int cmdsize = STLINK_CMD_SIZE_V2;
1117
1118         if (len > STLINK_DATA_SIZE)
1119                 return ERROR_FAIL;
1120
1121         if (h->version.stlink == 1)
1122                 cmdsize = STLINK_SG_SIZE;
1123
1124         stlink_usb_init_buffer(handle, h->tx_ep, 0);
1125         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1126         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_WRITEMEM;
1127         h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1128         h->cmdidx += 2;
1129         h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1130         h->cmdidx += 4;
1131         for (i = 0; i < len; i++) {
1132                 if (h->cmdidx == cmdsize)
1133                         h->databuf[datalen++] = *(data++);
1134                 else
1135                         h->cmdbuf[h->cmdidx++] = *(data++);
1136         }
1137         if (h->version.stlink == 1)
1138                 stlink_usb_set_cbw_transfer_datalength(handle, datalen);
1139
1140         res = stlink_cmd_allow_retry(handle, h->databuf, datalen);
1141         if (res != ERROR_OK)
1142                 return res;
1143         return ERROR_OK;
1144 }
1145
1146 static int stlink_swim_readbytes(void *handle, uint32_t addr, uint32_t len, uint8_t *data)
1147 {
1148         struct stlink_usb_handle_s *h = handle;
1149         int res;
1150
1151         if (len > STLINK_DATA_SIZE)
1152                 return ERROR_FAIL;
1153
1154         stlink_usb_init_buffer(handle, h->rx_ep, 0);
1155         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1156         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READMEM;
1157         h_u16_to_be(h->cmdbuf+h->cmdidx, len);
1158         h->cmdidx += 2;
1159         h_u32_to_be(h->cmdbuf+h->cmdidx, addr);
1160         h->cmdidx += 4;
1161         res = stlink_cmd_allow_retry(handle, h->databuf, 0);
1162         if (res != ERROR_OK)
1163                 return res;
1164
1165         stlink_usb_init_buffer(handle, h->rx_ep, len);
1166         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
1167         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_READBUF;
1168         res = stlink_usb_xfer(handle, data, len);
1169         if (res != ERROR_OK)
1170                 return res;
1171
1172         return ERROR_OK;
1173 }
1174
1175 /** */
1176 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
1177 {
1178         int res;
1179         struct stlink_usb_handle_s *h = handle;
1180
1181         assert(handle != NULL);
1182
1183         /* there is no swim read core id cmd */
1184         if (h->transport == HL_TRANSPORT_SWIM) {
1185                 *idcode = 0;
1186                 return ERROR_OK;
1187         }
1188
1189         stlink_usb_init_buffer(handle, h->rx_ep, 4);
1190
1191         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1192         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
1193
1194         res = stlink_usb_xfer(handle, h->databuf, 4);
1195
1196         if (res != ERROR_OK)
1197                 return res;
1198
1199         *idcode = le_to_h_u32(h->databuf);
1200
1201         LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
1202
1203         return ERROR_OK;
1204 }
1205
1206 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
1207 {
1208         struct stlink_usb_handle_s *h = handle;
1209         int res;
1210
1211         assert(handle != NULL);
1212
1213         stlink_usb_init_buffer(handle, h->rx_ep, 8);
1214
1215         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1216         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
1217         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1218         h->cmdidx += 4;
1219
1220         res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1221         if (res != ERROR_OK)
1222                 return res;
1223
1224         *val = le_to_h_u32(h->databuf + 4);
1225         return ERROR_OK;
1226 }
1227
1228 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
1229 {
1230         struct stlink_usb_handle_s *h = handle;
1231
1232         assert(handle != NULL);
1233
1234         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1235
1236         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1237         if (h->jtag_api == STLINK_JTAG_API_V1)
1238                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
1239         else
1240                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
1241         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1242         h->cmdidx += 4;
1243         h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1244         h->cmdidx += 4;
1245
1246         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1247 }
1248
1249 /** */
1250 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
1251 {
1252         struct stlink_usb_handle_s *h = handle;
1253
1254         assert(handle != NULL);
1255
1256         if (h->trace.enabled && h->version.jtag >= STLINK_TRACE_MIN_VERSION) {
1257                 int res;
1258
1259                 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1260
1261                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1262                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
1263
1264                 res = stlink_usb_xfer(handle, h->databuf, 2);
1265                 if (res != ERROR_OK)
1266                         return res;
1267
1268                 size_t bytes_avail = le_to_h_u16(h->databuf);
1269                 *size = bytes_avail < *size ? bytes_avail : *size - 1;
1270
1271                 if (*size > 0) {
1272                         res = stlink_usb_read_trace(handle, buf, *size);
1273                         if (res != ERROR_OK)
1274                                 return res;
1275                         return ERROR_OK;
1276                 }
1277         }
1278         *size = 0;
1279         return ERROR_OK;
1280 }
1281
1282 static enum target_state stlink_usb_v2_get_status(void *handle)
1283 {
1284         int result;
1285         uint32_t status;
1286
1287         result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
1288         if  (result != ERROR_OK)
1289                 return TARGET_UNKNOWN;
1290
1291         if (status & S_HALT)
1292                 return TARGET_HALTED;
1293         else if (status & S_RESET_ST)
1294                 return TARGET_RESET;
1295
1296         return TARGET_RUNNING;
1297 }
1298
1299 /** */
1300 static enum target_state stlink_usb_state(void *handle)
1301 {
1302         int res;
1303         struct stlink_usb_handle_s *h = handle;
1304
1305         assert(handle != NULL);
1306
1307         if (h->transport == HL_TRANSPORT_SWIM) {
1308                 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1309                 if (res != ERROR_OK)
1310                         return TARGET_UNKNOWN;
1311
1312                 res = stlink_swim_resync(handle);
1313                 if (res != ERROR_OK)
1314                         return TARGET_UNKNOWN;
1315
1316                 return ERROR_OK;
1317         }
1318
1319         if (h->reconnect_pending) {
1320                 LOG_INFO("Previous state query failed, trying to reconnect");
1321                 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
1322
1323                 if (res != ERROR_OK)
1324                         return TARGET_UNKNOWN;
1325
1326                 h->reconnect_pending = false;
1327         }
1328
1329         if (h->jtag_api == STLINK_JTAG_API_V2) {
1330                 res = stlink_usb_v2_get_status(handle);
1331                 if (res == TARGET_UNKNOWN)
1332                         h->reconnect_pending = true;
1333                 return res;
1334         }
1335
1336         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1337
1338         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1339         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
1340
1341         res = stlink_usb_xfer(handle, h->databuf, 2);
1342
1343         if (res != ERROR_OK)
1344                 return TARGET_UNKNOWN;
1345
1346         if (h->databuf[0] == STLINK_CORE_RUNNING)
1347                 return TARGET_RUNNING;
1348         if (h->databuf[0] == STLINK_CORE_HALTED)
1349                 return TARGET_HALTED;
1350
1351         h->reconnect_pending = true;
1352
1353         return TARGET_UNKNOWN;
1354 }
1355
1356 static int stlink_usb_assert_srst(void *handle, int srst)
1357 {
1358         struct stlink_usb_handle_s *h = handle;
1359
1360         assert(handle != NULL);
1361
1362         if (h->transport == HL_TRANSPORT_SWIM)
1363                 return stlink_swim_assert_reset(handle, srst);
1364
1365         if (h->version.stlink == 1)
1366                 return ERROR_COMMAND_NOTFOUND;
1367
1368         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1369
1370         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1371         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
1372         h->cmdbuf[h->cmdidx++] = srst;
1373
1374         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1375 }
1376
1377 /** */
1378 static void stlink_usb_trace_disable(void *handle)
1379 {
1380         int res = ERROR_OK;
1381         struct stlink_usb_handle_s *h = handle;
1382
1383         assert(handle != NULL);
1384
1385         assert(h->version.jtag >= STLINK_TRACE_MIN_VERSION);
1386
1387         LOG_DEBUG("Tracing: disable");
1388
1389         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1390         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1391         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
1392         res = stlink_usb_xfer(handle, h->databuf, 2);
1393
1394         if (res == ERROR_OK)
1395                 h->trace.enabled = false;
1396 }
1397
1398
1399 /** */
1400 static int stlink_usb_trace_enable(void *handle)
1401 {
1402         int res;
1403         struct stlink_usb_handle_s *h = handle;
1404
1405         assert(handle != NULL);
1406
1407         if (h->version.jtag >= STLINK_TRACE_MIN_VERSION) {
1408                 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1409
1410                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1411                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
1412                 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
1413                 h->cmdidx += 2;
1414                 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
1415                 h->cmdidx += 4;
1416
1417                 res = stlink_usb_xfer(handle, h->databuf, 2);
1418
1419                 if (res == ERROR_OK)  {
1420                         h->trace.enabled = true;
1421                         LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
1422                 }
1423         } else {
1424                 LOG_ERROR("Tracing is not supported by this version.");
1425                 res = ERROR_FAIL;
1426         }
1427
1428         return res;
1429 }
1430
1431 /** */
1432 static int stlink_usb_reset(void *handle)
1433 {
1434         struct stlink_usb_handle_s *h = handle;
1435         int retval;
1436
1437         assert(handle != NULL);
1438
1439         if (h->transport == HL_TRANSPORT_SWIM)
1440                 return stlink_swim_generate_rst(handle);
1441
1442         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1443
1444         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1445
1446         if (h->jtag_api == STLINK_JTAG_API_V1)
1447                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
1448         else
1449                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
1450
1451         retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
1452         if (retval != ERROR_OK)
1453                 return retval;
1454
1455         if (h->trace.enabled) {
1456                 stlink_usb_trace_disable(h);
1457                 return stlink_usb_trace_enable(h);
1458         }
1459
1460         return ERROR_OK;
1461 }
1462
1463 /** */
1464 static int stlink_usb_run(void *handle)
1465 {
1466         int res;
1467         struct stlink_usb_handle_s *h = handle;
1468
1469         assert(handle != NULL);
1470
1471         if (h->jtag_api == STLINK_JTAG_API_V2) {
1472                 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
1473
1474                 return res;
1475         }
1476
1477         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1478
1479         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1480         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
1481
1482         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1483 }
1484
1485 /** */
1486 static int stlink_usb_halt(void *handle)
1487 {
1488         int res;
1489         struct stlink_usb_handle_s *h = handle;
1490
1491         assert(handle != NULL);
1492
1493         if (h->jtag_api == STLINK_JTAG_API_V2) {
1494                 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1495
1496                 return res;
1497         }
1498
1499         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1500
1501         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1502         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
1503
1504         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1505 }
1506
1507 /** */
1508 static int stlink_usb_step(void *handle)
1509 {
1510         struct stlink_usb_handle_s *h = handle;
1511
1512         assert(handle != NULL);
1513
1514         if (h->jtag_api == STLINK_JTAG_API_V2) {
1515                 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
1516                  * that the Cortex-M3 currently does. */
1517                 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
1518                 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
1519                 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1520         }
1521
1522         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1523
1524         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1525         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
1526
1527         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1528 }
1529
1530 /** */
1531 static int stlink_usb_read_regs(void *handle)
1532 {
1533         int res;
1534         struct stlink_usb_handle_s *h = handle;
1535
1536         assert(handle != NULL);
1537
1538         stlink_usb_init_buffer(handle, h->rx_ep, 84);
1539
1540         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1541         if (h->jtag_api == STLINK_JTAG_API_V1)
1542                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
1543         else
1544                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
1545
1546         res = stlink_usb_xfer(handle, h->databuf, 84);
1547
1548         if (res != ERROR_OK)
1549                 return res;
1550
1551         return ERROR_OK;
1552 }
1553
1554 /** */
1555 static int stlink_usb_read_reg(void *handle, int num, uint32_t *val)
1556 {
1557         int res;
1558         struct stlink_usb_handle_s *h = handle;
1559
1560         assert(handle != NULL);
1561
1562         stlink_usb_init_buffer(handle, h->rx_ep, h->jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
1563
1564         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1565         if (h->jtag_api == STLINK_JTAG_API_V1)
1566                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
1567         else
1568                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
1569         h->cmdbuf[h->cmdidx++] = num;
1570
1571         if (h->jtag_api == STLINK_JTAG_API_V1) {
1572                 res = stlink_usb_xfer(handle, h->databuf, 4);
1573                 if (res != ERROR_OK)
1574                         return res;
1575                 *val = le_to_h_u32(h->databuf);
1576                 return ERROR_OK;
1577         } else {
1578                 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1579                 if (res != ERROR_OK)
1580                         return res;
1581                 *val = le_to_h_u32(h->databuf + 4);
1582                 return ERROR_OK;
1583         }
1584 }
1585
1586 /** */
1587 static int stlink_usb_write_reg(void *handle, int num, uint32_t val)
1588 {
1589         struct stlink_usb_handle_s *h = handle;
1590
1591         assert(handle != NULL);
1592
1593         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1594
1595         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1596         if (h->jtag_api == STLINK_JTAG_API_V1)
1597                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
1598         else
1599                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
1600         h->cmdbuf[h->cmdidx++] = num;
1601         h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1602         h->cmdidx += 4;
1603
1604         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1605 }
1606
1607 static int stlink_usb_get_rw_status(void *handle)
1608 {
1609         int res;
1610         struct stlink_usb_handle_s *h = handle;
1611
1612         assert(handle != NULL);
1613
1614         if (h->jtag_api == STLINK_JTAG_API_V1)
1615                 return ERROR_OK;
1616
1617         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1618
1619         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1620         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
1621
1622         res = stlink_usb_xfer(handle, h->databuf, 2);
1623
1624         if (res != ERROR_OK)
1625                 return res;
1626
1627         return stlink_usb_error_check(h);
1628 }
1629
1630 /** */
1631 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
1632                           uint8_t *buffer)
1633 {
1634         int res;
1635         uint16_t read_len = len;
1636         struct stlink_usb_handle_s *h = handle;
1637
1638         assert(handle != NULL);
1639
1640         /* max 8bit read/write is 64bytes */
1641         if (len > STLINK_MAX_RW8) {
1642                 LOG_DEBUG("max buffer length exceeded");
1643                 return ERROR_FAIL;
1644         }
1645
1646         stlink_usb_init_buffer(handle, h->rx_ep, read_len);
1647
1648         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1649         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
1650         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1651         h->cmdidx += 4;
1652         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
1653         h->cmdidx += 2;
1654
1655         /* we need to fix read length for single bytes */
1656         if (read_len == 1)
1657                 read_len++;
1658
1659         res = stlink_usb_xfer(handle, h->databuf, read_len);
1660
1661         if (res != ERROR_OK)
1662                 return res;
1663
1664         memcpy(buffer, h->databuf, len);
1665
1666         return stlink_usb_get_rw_status(handle);
1667 }
1668
1669 /** */
1670 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
1671                            const uint8_t *buffer)
1672 {
1673         int res;
1674         struct stlink_usb_handle_s *h = handle;
1675
1676         assert(handle != NULL);
1677
1678         /* max 8bit read/write is 64bytes */
1679         if (len > STLINK_MAX_RW8) {
1680                 LOG_DEBUG("max buffer length exceeded");
1681                 return ERROR_FAIL;
1682         }
1683
1684         stlink_usb_init_buffer(handle, h->tx_ep, len);
1685
1686         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1687         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
1688         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1689         h->cmdidx += 4;
1690         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
1691         h->cmdidx += 2;
1692
1693         res = stlink_usb_xfer(handle, buffer, len);
1694
1695         if (res != ERROR_OK)
1696                 return res;
1697
1698         return stlink_usb_get_rw_status(handle);
1699 }
1700
1701 /** */
1702 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
1703                           uint8_t *buffer)
1704 {
1705         int res;
1706         struct stlink_usb_handle_s *h = handle;
1707
1708         assert(handle != NULL);
1709
1710         /* data must be a multiple of 4 and word aligned */
1711         if (len % 4 || addr % 4) {
1712                 LOG_DEBUG("Invalid data alignment");
1713                 return ERROR_TARGET_UNALIGNED_ACCESS;
1714         }
1715
1716         stlink_usb_init_buffer(handle, h->rx_ep, len);
1717
1718         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1719         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
1720         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1721         h->cmdidx += 4;
1722         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
1723         h->cmdidx += 2;
1724
1725         res = stlink_usb_xfer(handle, h->databuf, len);
1726
1727         if (res != ERROR_OK)
1728                 return res;
1729
1730         memcpy(buffer, h->databuf, len);
1731
1732         return stlink_usb_get_rw_status(handle);
1733 }
1734
1735 /** */
1736 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
1737                            const uint8_t *buffer)
1738 {
1739         int res;
1740         struct stlink_usb_handle_s *h = handle;
1741
1742         assert(handle != NULL);
1743
1744         /* data must be a multiple of 4 and word aligned */
1745         if (len % 4 || addr % 4) {
1746                 LOG_DEBUG("Invalid data alignment");
1747                 return ERROR_TARGET_UNALIGNED_ACCESS;
1748         }
1749
1750         stlink_usb_init_buffer(handle, h->tx_ep, len);
1751
1752         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1753         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
1754         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1755         h->cmdidx += 4;
1756         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
1757         h->cmdidx += 2;
1758
1759         res = stlink_usb_xfer(handle, buffer, len);
1760
1761         if (res != ERROR_OK)
1762                 return res;
1763
1764         return stlink_usb_get_rw_status(handle);
1765 }
1766
1767 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
1768 {
1769         uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
1770         if (max_tar_block == 0)
1771                 max_tar_block = 4;
1772         return max_tar_block;
1773 }
1774
1775 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
1776                 uint32_t count, uint8_t *buffer)
1777 {
1778         int retval = ERROR_OK;
1779         uint32_t bytes_remaining;
1780         int retries = 0;
1781         struct stlink_usb_handle_s *h = handle;
1782
1783         /* calculate byte count */
1784         count *= size;
1785
1786         while (count) {
1787
1788                 bytes_remaining = (size == 4) ? \
1789                                 stlink_max_block_size(h->max_mem_packet, addr) : STLINK_MAX_RW8;
1790
1791                 if (count < bytes_remaining)
1792                         bytes_remaining = count;
1793
1794                 if (h->transport == HL_TRANSPORT_SWIM) {
1795                         retval = stlink_swim_readbytes(handle, addr, bytes_remaining, buffer);
1796                         if (retval != ERROR_OK)
1797                                 return retval;
1798                 } else
1799                 /* the stlink only supports 8/32bit memory read/writes
1800                  * honour 32bit, all others will be handled as 8bit access */
1801                 if (size == 4) {
1802
1803                         /* When in jtag mode the stlink uses the auto-increment functinality.
1804                          * However it expects us to pass the data correctly, this includes
1805                          * alignment and any page boundaries. We already do this as part of the
1806                          * adi_v5 implementation, but the stlink is a hla adapter and so this
1807                          * needs implementiong manually.
1808                          * currently this only affects jtag mode, according to ST they do single
1809                          * access in SWD mode - but this may change and so we do it for both modes */
1810
1811                         /* we first need to check for any unaligned bytes */
1812                         if (addr % 4) {
1813
1814                                 uint32_t head_bytes = 4 - (addr % 4);
1815                                 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
1816                                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1817                                         usleep((1<<retries++) * 1000);
1818                                         continue;
1819                                 }
1820                                 if (retval != ERROR_OK)
1821                                         return retval;
1822                                 buffer += head_bytes;
1823                                 addr += head_bytes;
1824                                 count -= head_bytes;
1825                                 bytes_remaining -= head_bytes;
1826                         }
1827
1828                         if (bytes_remaining % 4)
1829                                 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
1830                         else
1831                                 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
1832                 } else
1833                         retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
1834
1835                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1836                         usleep((1<<retries++) * 1000);
1837                         continue;
1838                 }
1839                 if (retval != ERROR_OK)
1840                         return retval;
1841
1842                 buffer += bytes_remaining;
1843                 addr += bytes_remaining;
1844                 count -= bytes_remaining;
1845         }
1846
1847         return retval;
1848 }
1849
1850 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
1851                 uint32_t count, const uint8_t *buffer)
1852 {
1853         int retval = ERROR_OK;
1854         uint32_t bytes_remaining;
1855         int retries = 0;
1856         struct stlink_usb_handle_s *h = handle;
1857
1858         /* calculate byte count */
1859         count *= size;
1860
1861         while (count) {
1862
1863                 bytes_remaining = (size == 4) ? \
1864                                 stlink_max_block_size(h->max_mem_packet, addr) : STLINK_MAX_RW8;
1865
1866                 if (count < bytes_remaining)
1867                         bytes_remaining = count;
1868
1869                 if (h->transport == HL_TRANSPORT_SWIM) {
1870                         retval = stlink_swim_writebytes(handle, addr, bytes_remaining, buffer);
1871                         if (retval != ERROR_OK)
1872                                 return retval;
1873                 } else
1874                 /* the stlink only supports 8/32bit memory read/writes
1875                  * honour 32bit, all others will be handled as 8bit access */
1876                 if (size == 4) {
1877
1878                         /* When in jtag mode the stlink uses the auto-increment functinality.
1879                          * However it expects us to pass the data correctly, this includes
1880                          * alignment and any page boundaries. We already do this as part of the
1881                          * adi_v5 implementation, but the stlink is a hla adapter and so this
1882                          * needs implementiong manually.
1883                          * currently this only affects jtag mode, according to ST they do single
1884                          * access in SWD mode - but this may change and so we do it for both modes */
1885
1886                         /* we first need to check for any unaligned bytes */
1887                         if (addr % 4) {
1888
1889                                 uint32_t head_bytes = 4 - (addr % 4);
1890                                 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
1891                                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1892                                         usleep((1<<retries++) * 1000);
1893                                         continue;
1894                                 }
1895                                 if (retval != ERROR_OK)
1896                                         return retval;
1897                                 buffer += head_bytes;
1898                                 addr += head_bytes;
1899                                 count -= head_bytes;
1900                                 bytes_remaining -= head_bytes;
1901                         }
1902
1903                         if (bytes_remaining % 4)
1904                                 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
1905                         else
1906                                 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
1907
1908                 } else
1909                         retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
1910                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1911                         usleep((1<<retries++) * 1000);
1912                         continue;
1913                 }
1914                 if (retval != ERROR_OK)
1915                         return retval;
1916
1917                 buffer += bytes_remaining;
1918                 addr += bytes_remaining;
1919                 count -= bytes_remaining;
1920         }
1921
1922         return retval;
1923 }
1924
1925 /** */
1926 static int stlink_usb_override_target(const char *targetname)
1927 {
1928         return !strcmp(targetname, "cortex_m");
1929 }
1930
1931 static int stlink_speed_swim(void *handle, int khz, bool query)
1932 {
1933         /*
1934                         we dont care what the khz rate is
1935                         we only have low and high speed...
1936                         before changing speed the SWIM_CSR HS bit
1937                         must be updated
1938          */
1939         if (khz == 0)
1940                 stlink_swim_speed(handle, 0);
1941         else
1942                 stlink_swim_speed(handle, 1);
1943         return khz;
1944 }
1945
1946 static int stlink_match_speed_map(const struct speed_map *map, unsigned int map_size, int khz, bool query)
1947 {
1948         unsigned int i;
1949         int speed_index = -1;
1950         int speed_diff = INT_MAX;
1951         bool match = true;
1952
1953         for (i = 0; i < map_size; i++) {
1954                 if (khz == map[i].speed) {
1955                         speed_index = i;
1956                         break;
1957                 } else {
1958                         int current_diff = khz - map[i].speed;
1959                         /* get abs value for comparison */
1960                         current_diff = (current_diff > 0) ? current_diff : -current_diff;
1961                         if ((current_diff < speed_diff) && khz >= map[i].speed) {
1962                                 speed_diff = current_diff;
1963                                 speed_index = i;
1964                         }
1965                 }
1966         }
1967
1968         if (speed_index == -1) {
1969                 /* this will only be here if we cannot match the slow speed.
1970                  * use the slowest speed we support.*/
1971                 speed_index = map_size - 1;
1972                 match = false;
1973         } else if (i == map_size)
1974                 match = false;
1975
1976         if (!match && query) {
1977                 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz", \
1978                                 khz, map[speed_index].speed);
1979         }
1980
1981         return speed_index;
1982 }
1983
1984 static int stlink_speed_swd(void *handle, int khz, bool query)
1985 {
1986         int speed_index;
1987         struct stlink_usb_handle_s *h = handle;
1988
1989         /* only supported by stlink/v2 and for firmware >= 22 */
1990         if (h->version.stlink == 1 || h->version.jtag < 22)
1991                 return khz;
1992
1993         speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_swd,
1994                 ARRAY_SIZE(stlink_khz_to_speed_map_swd), khz, query);
1995
1996         if (!query) {
1997                 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map_swd[speed_index].speed_divisor);
1998                 if (result != ERROR_OK) {
1999                         LOG_ERROR("Unable to set adapter speed");
2000                         return khz;
2001                 }
2002         }
2003
2004         return stlink_khz_to_speed_map_swd[speed_index].speed;
2005 }
2006
2007 static int stlink_speed_jtag(void *handle, int khz, bool query)
2008 {
2009         int speed_index;
2010         struct stlink_usb_handle_s *h = handle;
2011
2012         /* only supported by stlink/v2 and for firmware >= 24 */
2013         if (h->version.stlink == 1 || h->version.jtag < 24)
2014                 return khz;
2015
2016         speed_index = stlink_match_speed_map(stlink_khz_to_speed_map_jtag,
2017                 ARRAY_SIZE(stlink_khz_to_speed_map_jtag), khz, query);
2018
2019         if (!query) {
2020                 int result = stlink_usb_set_jtagclk(h, stlink_khz_to_speed_map_jtag[speed_index].speed_divisor);
2021                 if (result != ERROR_OK) {
2022                         LOG_ERROR("Unable to set adapter speed");
2023                         return khz;
2024                 }
2025         }
2026
2027         return stlink_khz_to_speed_map_jtag[speed_index].speed;
2028 }
2029
2030 void stlink_dump_speed_map(const struct speed_map *map, unsigned int map_size)
2031 {
2032         unsigned int i;
2033
2034         LOG_DEBUG("Supported clock speeds are:");
2035         for (i = 0; i < map_size; i++)
2036                 LOG_DEBUG("%d kHz", map[i].speed);
2037 }
2038
2039 static int stlink_speed(void *handle, int khz, bool query)
2040 {
2041         struct stlink_usb_handle_s *h = handle;
2042
2043         if (!handle)
2044                 return khz;
2045
2046         if (h->transport == HL_TRANSPORT_SWIM)
2047                 return stlink_speed_swim(handle, khz, query);
2048         else if (h->transport == HL_TRANSPORT_SWD)
2049                 return stlink_speed_swd(handle, khz, query);
2050         else if (h->transport == HL_TRANSPORT_JTAG)
2051                 return stlink_speed_jtag(handle, khz, query);
2052
2053         return khz;
2054 }
2055
2056 /** */
2057 static int stlink_usb_close(void *handle)
2058 {
2059         int res;
2060         uint8_t mode;
2061         enum stlink_mode emode;
2062         struct stlink_usb_handle_s *h = handle;
2063
2064         if (h && h->fd)
2065                 res = stlink_usb_current_mode(handle, &mode);
2066         else
2067                 res = ERROR_FAIL;
2068         /* do not exit if return code != ERROR_OK,
2069            it prevents us from closing jtag_libusb */
2070
2071         if (res == ERROR_OK) {
2072                 /* try to exit current mode */
2073                 switch (mode) {
2074                         case STLINK_DEV_DFU_MODE:
2075                                 emode = STLINK_MODE_DFU;
2076                                 break;
2077                         case STLINK_DEV_DEBUG_MODE:
2078                                 emode = STLINK_MODE_DEBUG_SWD;
2079                                 break;
2080                         case STLINK_DEV_SWIM_MODE:
2081                                 emode = STLINK_MODE_DEBUG_SWIM;
2082                                 break;
2083                         case STLINK_DEV_BOOTLOADER_MODE:
2084                         case STLINK_DEV_MASS_MODE:
2085                         default:
2086                                 emode = STLINK_MODE_UNKNOWN;
2087                                 break;
2088                 }
2089
2090                 if (emode != STLINK_MODE_UNKNOWN)
2091                         stlink_usb_mode_leave(handle, emode);
2092                         /* do not check return code, it prevent
2093                         us from closing jtag_libusb */
2094         }
2095
2096         if (h && h->fd)
2097                 jtag_libusb_close(h->fd);
2098
2099         free(h);
2100
2101         return ERROR_OK;
2102 }
2103
2104 /** */
2105 static int stlink_usb_open(struct hl_interface_param_s *param, void **fd)
2106 {
2107         int err, retry_count = 1;
2108         struct stlink_usb_handle_s *h;
2109         enum stlink_jtag_api_version api;
2110
2111         LOG_DEBUG("stlink_usb_open");
2112
2113         h = calloc(1, sizeof(struct stlink_usb_handle_s));
2114
2115         if (h == 0) {
2116                 LOG_DEBUG("malloc failed");
2117                 return ERROR_FAIL;
2118         }
2119
2120         h->transport = param->transport;
2121
2122         for (unsigned i = 0; param->vid[i]; i++) {
2123                 LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
2124                           param->transport, param->vid[i], param->pid[i],
2125                           param->serial ? param->serial : "");
2126         }
2127
2128         /*
2129           On certain host USB configurations(e.g. MacBook Air)
2130           STLINKv2 dongle seems to have its FW in a funky state if,
2131           after plugging it in, you try to use openocd with it more
2132           then once (by launching and closing openocd). In cases like
2133           that initial attempt to read the FW info via
2134           stlink_usb_version will fail and the device has to be reset
2135           in order to become operational.
2136          */
2137         do {
2138                 if (jtag_libusb_open(param->vid, param->pid, param->serial, &h->fd) != ERROR_OK) {
2139                         LOG_ERROR("open failed");
2140                         goto error_open;
2141                 }
2142
2143                 jtag_libusb_set_configuration(h->fd, 0);
2144
2145                 if (jtag_libusb_claim_interface(h->fd, 0) != ERROR_OK) {
2146                         LOG_DEBUG("claim interface failed");
2147                         goto error_open;
2148                 }
2149
2150                 /* RX EP is common for all versions */
2151                 h->rx_ep = STLINK_RX_EP;
2152
2153                 uint16_t pid;
2154                 if (jtag_libusb_get_pid(jtag_libusb_get_device(h->fd), &pid) != ERROR_OK) {
2155                         LOG_DEBUG("libusb_get_pid failed");
2156                         goto error_open;
2157                 }
2158
2159                 /* wrap version for first read */
2160                 switch (pid) {
2161                         case STLINK_V1_PID:
2162                                 h->version.stlink = 1;
2163                                 h->tx_ep = STLINK_TX_EP;
2164                                 h->trace_ep = STLINK_TRACE_EP;
2165                                 break;
2166                         case STLINK_V2_1_PID:
2167                         case STLINK_V2_1_NO_MSD_PID:
2168                                 h->version.stlink = 2;
2169                                 h->tx_ep = STLINK_V2_1_TX_EP;
2170                                 h->trace_ep = STLINK_V2_1_TRACE_EP;
2171                                 break;
2172                         default:
2173                         /* fall through - we assume V2 to be the default version*/
2174                         case STLINK_V2_PID:
2175                                 h->version.stlink = 2;
2176                                 h->tx_ep = STLINK_TX_EP;
2177                                 h->trace_ep = STLINK_TRACE_EP;
2178                                 break;
2179                 }
2180
2181                 /* get the device version */
2182                 err = stlink_usb_version(h);
2183
2184                 if (err == ERROR_OK) {
2185                         break;
2186                 } else if (h->version.stlink == 1 ||
2187                            retry_count == 0) {
2188                         LOG_ERROR("read version failed");
2189                         goto error_open;
2190                 } else {
2191                         err = jtag_libusb_release_interface(h->fd, 0);
2192                         if (err != ERROR_OK) {
2193                                 LOG_ERROR("release interface failed");
2194                                 goto error_open;
2195                         }
2196
2197                         err = jtag_libusb_reset_device(h->fd);
2198                         if (err != ERROR_OK) {
2199                                 LOG_ERROR("reset device failed");
2200                                 goto error_open;
2201                         }
2202
2203                         jtag_libusb_close(h->fd);
2204                         /*
2205                           Give the device one second to settle down and
2206                           reenumerate.
2207                          */
2208                         usleep(1 * 1000 * 1000);
2209                         retry_count--;
2210                 }
2211         } while (1);
2212
2213         /* check if mode is supported */
2214         err = ERROR_OK;
2215
2216         switch (h->transport) {
2217                 case HL_TRANSPORT_SWD:
2218                 case HL_TRANSPORT_JTAG:
2219                         if (h->version.jtag == 0)
2220                                 err = ERROR_FAIL;
2221                         break;
2222                 case HL_TRANSPORT_SWIM:
2223                         if (h->version.swim == 0)
2224                                 err = ERROR_FAIL;
2225                         break;
2226                 default:
2227                         err = ERROR_FAIL;
2228                         break;
2229         }
2230
2231         if (err != ERROR_OK) {
2232                 LOG_ERROR("mode (transport) not supported by device");
2233                 goto error_open;
2234         }
2235
2236         api = h->version.jtag_api_max;
2237
2238         LOG_INFO("using stlink api v%d", api);
2239
2240         /* set the used jtag api, this will default to the newest supported version */
2241         h->jtag_api = api;
2242
2243         /* initialize the debug hardware */
2244         err = stlink_usb_init_mode(h, param->connect_under_reset);
2245
2246         if (err != ERROR_OK) {
2247                 LOG_ERROR("init mode failed (unable to connect to the target)");
2248                 goto error_open;
2249         }
2250
2251         if (h->transport == HL_TRANSPORT_SWIM) {
2252                 err = stlink_swim_enter(h);
2253                 if (err != ERROR_OK) {
2254                         LOG_ERROR("stlink_swim_enter_failed (unable to connect to the target)");
2255                         goto error_open;
2256                 }
2257                 *fd = h;
2258                 h->max_mem_packet = STLINK_DATA_SIZE;
2259                 return ERROR_OK;
2260         }
2261
2262         if (h->transport == HL_TRANSPORT_JTAG) {
2263                 /* jtag clock speed only supported by stlink/v2 and for firmware >= 24 */
2264                 if (h->version.stlink >= 2 && h->version.jtag >= 24) {
2265                         stlink_dump_speed_map(stlink_khz_to_speed_map_jtag, ARRAY_SIZE(stlink_khz_to_speed_map_jtag));
2266                         stlink_speed(h, param->initial_interface_speed, false);
2267                 }
2268         } else if (h->transport == HL_TRANSPORT_SWD) {
2269                 /* clock speed only supported by stlink/v2 and for firmware >= 22 */
2270                 if (h->version.stlink >= 2 && h->version.jtag >= 22) {
2271                         stlink_dump_speed_map(stlink_khz_to_speed_map_swd, ARRAY_SIZE(stlink_khz_to_speed_map_swd));
2272                         stlink_speed(h, param->initial_interface_speed, false);
2273                 }
2274         }
2275
2276         /* get cpuid, so we can determine the max page size
2277          * start with a safe default */
2278         h->max_mem_packet = (1 << 10);
2279
2280         uint8_t buffer[4];
2281         err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
2282         if (err == ERROR_OK) {
2283                 uint32_t cpuid = le_to_h_u32(buffer);
2284                 int i = (cpuid >> 4) & 0xf;
2285                 if (i == 4 || i == 3) {
2286                         /* Cortex-M3/M4 has 4096 bytes autoincrement range */
2287                         h->max_mem_packet = (1 << 12);
2288                 }
2289         }
2290
2291         LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
2292
2293         *fd = h;
2294
2295         return ERROR_OK;
2296
2297 error_open:
2298         stlink_usb_close(h);
2299
2300         return ERROR_FAIL;
2301 }
2302
2303 int stlink_config_trace(void *handle, bool enabled, enum tpiu_pin_protocol pin_protocol,
2304                         uint32_t port_size, unsigned int *trace_freq)
2305 {
2306         struct stlink_usb_handle_s *h = handle;
2307
2308         if (enabled && (h->jtag_api < 2 ||
2309                         pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART)) {
2310                 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
2311                 return ERROR_FAIL;
2312         }
2313
2314         if (!enabled) {
2315                 stlink_usb_trace_disable(h);
2316                 return ERROR_OK;
2317         }
2318
2319         if (*trace_freq > STLINK_TRACE_MAX_HZ) {
2320                 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
2321                           STLINK_TRACE_MAX_HZ);
2322                 return ERROR_FAIL;
2323         }
2324
2325         stlink_usb_trace_disable(h);
2326
2327         if (!*trace_freq)
2328                 *trace_freq = STLINK_TRACE_MAX_HZ;
2329         h->trace.source_hz = *trace_freq;
2330
2331         return stlink_usb_trace_enable(h);
2332 }
2333
2334 /** */
2335 struct hl_layout_api_s stlink_usb_layout_api = {
2336         /** */
2337         .open = stlink_usb_open,
2338         /** */
2339         .close = stlink_usb_close,
2340         /** */
2341         .idcode = stlink_usb_idcode,
2342         /** */
2343         .state = stlink_usb_state,
2344         /** */
2345         .reset = stlink_usb_reset,
2346         /** */
2347         .assert_srst = stlink_usb_assert_srst,
2348         /** */
2349         .run = stlink_usb_run,
2350         /** */
2351         .halt = stlink_usb_halt,
2352         /** */
2353         .step = stlink_usb_step,
2354         /** */
2355         .read_regs = stlink_usb_read_regs,
2356         /** */
2357         .read_reg = stlink_usb_read_reg,
2358         /** */
2359         .write_reg = stlink_usb_write_reg,
2360         /** */
2361         .read_mem = stlink_usb_read_mem,
2362         /** */
2363         .write_mem = stlink_usb_write_mem,
2364         /** */
2365         .write_debug_reg = stlink_usb_write_debug_reg,
2366         /** */
2367         .override_target = stlink_usb_override_target,
2368         /** */
2369         .speed = stlink_speed,
2370         /** */
2371         .config_trace = stlink_config_trace,
2372         /** */
2373         .poll_trace = stlink_usb_trace_read,
2374 };