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