649368d09faddb9870010fc4e32c5e99b852012f
[fw/openocd] / src / jtag / drivers / stlink_usb.c
1 /***************************************************************************
2  *   Copyright (C) 2011-2012 by Mathias Kuester                            *
3  *   Mathias Kuester <kesmtp@freenet.de>                                   *
4  *                                                                         *
5  *   Copyright (C) 2012 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   This code is based on https://github.com/texane/stlink                *
9  *                                                                         *
10  *   This program is free software; you can redistribute it and/or modify  *
11  *   it under the terms of the GNU General Public License as published by  *
12  *   the Free Software Foundation; either version 2 of the License, or     *
13  *   (at your option) any later version.                                   *
14  *                                                                         *
15  *   This program is distributed in the hope that it will be useful,       *
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
18  *   GNU General Public License for more details.                          *
19  *                                                                         *
20  *   You should have received a copy of the GNU General Public License     *
21  *   along with this program; if not, write to the                         *
22  *   Free Software Foundation, Inc.,                                       *
23  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
24  ***************************************************************************/
25
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 /* project specific includes */
31 #include <helper/binarybuffer.h>
32 #include <jtag/interface.h>
33 #include <jtag/hla/hla_layout.h>
34 #include <jtag/hla/hla_transport.h>
35 #include <jtag/hla/hla_interface.h>
36 #include <target/target.h>
37
38 #include <target/cortex_m.h>
39
40 #include "libusb_common.h"
41
42 #define ENDPOINT_IN  0x80
43 #define ENDPOINT_OUT 0x00
44
45 #define STLINK_WRITE_TIMEOUT 1000
46 #define STLINK_READ_TIMEOUT 1000
47
48 #define STLINK_NULL_EP        0
49 #define STLINK_RX_EP          (1|ENDPOINT_IN)
50 #define STLINK_TX_EP          (2|ENDPOINT_OUT)
51 #define STLINK_TRACE_EP       (3|ENDPOINT_IN)
52
53 #define STLINK_V2_1_TX_EP     (1|ENDPOINT_OUT)
54 #define STLINK_V2_1_TRACE_EP  (2|ENDPOINT_IN)
55
56 #define STLINK_SG_SIZE        (31)
57 #define STLINK_DATA_SIZE      (4096)
58 #define STLINK_CMD_SIZE_V2    (16)
59 #define STLINK_CMD_SIZE_V1    (10)
60
61 #define STLINK_V1_PID         (0x3744)
62 #define STLINK_V2_PID         (0x3748)
63 #define STLINK_V2_1_PID       (0x374B)
64
65 /* the current implementation of the stlink limits
66  * 8bit read/writes to max 64 bytes. */
67 #define STLINK_MAX_RW8          (64)
68
69 /* "WAIT" responses will be retried (with exponential backoff) at
70  * most this many times before failing to caller.
71  */
72 #define MAX_WAIT_RETRIES 8
73
74 enum stlink_jtag_api_version {
75         STLINK_JTAG_API_V1 = 1,
76         STLINK_JTAG_API_V2,
77 };
78
79 /** */
80 struct stlink_usb_version {
81         /** */
82         int stlink;
83         /** */
84         int jtag;
85         /** */
86         int swim;
87         /** highest supported jtag api version */
88         enum stlink_jtag_api_version jtag_api_max;
89 };
90
91 /** */
92 struct stlink_usb_handle_s {
93         /** */
94         struct jtag_libusb_device_handle *fd;
95         /** */
96         struct libusb_transfer *trans;
97         /** */
98         uint8_t rx_ep;
99         /** */
100         uint8_t tx_ep;
101         /** */
102         uint8_t trace_ep;
103         /** */
104         uint8_t cmdbuf[STLINK_SG_SIZE];
105         /** */
106         uint8_t cmdidx;
107         /** */
108         uint8_t direction;
109         /** */
110         uint8_t databuf[STLINK_DATA_SIZE];
111         /** */
112         uint32_t max_mem_packet;
113         /** */
114         enum hl_transports transport;
115         /** */
116         struct stlink_usb_version version;
117         /** */
118         uint16_t vid;
119         /** */
120         uint16_t pid;
121         /** this is the currently used jtag api */
122         enum stlink_jtag_api_version jtag_api;
123         /** */
124         struct {
125                 /** whether SWO tracing is enabled or not */
126                 bool enabled;
127                 /** trace module source clock */
128                 uint32_t source_hz;
129         } trace;
130         /** reconnect is needed next time we try to query the
131          * status */
132         bool reconnect_pending;
133 };
134
135 #define STLINK_DEBUG_ERR_OK            0x80
136 #define STLINK_DEBUG_ERR_FAULT         0x81
137 #define STLINK_SWD_AP_WAIT             0x10
138 #define STLINK_SWD_AP_FAULT            0x11
139 #define STLINK_SWD_AP_ERROR            0x12
140 #define STLINK_SWD_AP_PARITY_ERROR     0x13
141 #define STLINK_JTAG_WRITE_ERROR        0x0c
142 #define STLINK_JTAG_WRITE_VERIF_ERROR  0x0d
143 #define STLINK_SWD_DP_WAIT             0x14
144 #define STLINK_SWD_DP_FAULT            0x15
145 #define STLINK_SWD_DP_ERROR            0x16
146 #define STLINK_SWD_DP_PARITY_ERROR     0x17
147
148 #define STLINK_SWD_AP_WDATA_ERROR      0x18
149 #define STLINK_SWD_AP_STICKY_ERROR     0x19
150 #define STLINK_SWD_AP_STICKYORUN_ERROR 0x1a
151
152 #define STLINK_CORE_RUNNING            0x80
153 #define STLINK_CORE_HALTED             0x81
154 #define STLINK_CORE_STAT_UNKNOWN       -1
155
156 #define STLINK_GET_VERSION             0xF1
157 #define STLINK_DEBUG_COMMAND           0xF2
158 #define STLINK_DFU_COMMAND             0xF3
159 #define STLINK_SWIM_COMMAND            0xF4
160 #define STLINK_GET_CURRENT_MODE        0xF5
161 #define STLINK_GET_TARGET_VOLTAGE      0xF7
162
163 #define STLINK_DEV_DFU_MODE            0x00
164 #define STLINK_DEV_MASS_MODE           0x01
165 #define STLINK_DEV_DEBUG_MODE          0x02
166 #define STLINK_DEV_SWIM_MODE           0x03
167 #define STLINK_DEV_BOOTLOADER_MODE     0x04
168 #define STLINK_DEV_UNKNOWN_MODE        -1
169
170 #define STLINK_DFU_EXIT                0x07
171
172 #define STLINK_SWIM_ENTER              0x00
173 #define STLINK_SWIM_EXIT               0x01
174
175 #define STLINK_DEBUG_ENTER_JTAG            0x00
176 #define STLINK_DEBUG_GETSTATUS             0x01
177 #define STLINK_DEBUG_FORCEDEBUG            0x02
178 #define STLINK_DEBUG_APIV1_RESETSYS        0x03
179 #define STLINK_DEBUG_APIV1_READALLREGS     0x04
180 #define STLINK_DEBUG_APIV1_READREG         0x05
181 #define STLINK_DEBUG_APIV1_WRITEREG        0x06
182 #define STLINK_DEBUG_READMEM_32BIT         0x07
183 #define STLINK_DEBUG_WRITEMEM_32BIT        0x08
184 #define STLINK_DEBUG_RUNCORE               0x09
185 #define STLINK_DEBUG_STEPCORE              0x0a
186 #define STLINK_DEBUG_APIV1_SETFP           0x0b
187 #define STLINK_DEBUG_READMEM_8BIT          0x0c
188 #define STLINK_DEBUG_WRITEMEM_8BIT         0x0d
189 #define STLINK_DEBUG_APIV1_CLEARFP         0x0e
190 #define STLINK_DEBUG_APIV1_WRITEDEBUGREG   0x0f
191 #define STLINK_DEBUG_APIV1_SETWATCHPOINT   0x10
192
193 #define STLINK_DEBUG_ENTER_JTAG            0x00
194 #define STLINK_DEBUG_ENTER_SWD             0xa3
195
196 #define STLINK_DEBUG_APIV1_ENTER           0x20
197 #define STLINK_DEBUG_EXIT                  0x21
198 #define STLINK_DEBUG_READCOREID            0x22
199
200 #define STLINK_DEBUG_APIV2_ENTER           0x30
201 #define STLINK_DEBUG_APIV2_READ_IDCODES    0x31
202 #define STLINK_DEBUG_APIV2_RESETSYS        0x32
203 #define STLINK_DEBUG_APIV2_READREG         0x33
204 #define STLINK_DEBUG_APIV2_WRITEREG        0x34
205 #define STLINK_DEBUG_APIV2_WRITEDEBUGREG   0x35
206 #define STLINK_DEBUG_APIV2_READDEBUGREG    0x36
207
208 #define STLINK_DEBUG_APIV2_READALLREGS     0x3A
209 #define STLINK_DEBUG_APIV2_GETLASTRWSTATUS 0x3B
210 #define STLINK_DEBUG_APIV2_DRIVE_NRST      0x3C
211
212 #define STLINK_DEBUG_APIV2_START_TRACE_RX  0x40
213 #define STLINK_DEBUG_APIV2_STOP_TRACE_RX   0x41
214 #define STLINK_DEBUG_APIV2_GET_TRACE_NB    0x42
215 #define STLINK_DEBUG_APIV2_SWD_SET_FREQ    0x43
216
217 #define STLINK_DEBUG_APIV2_DRIVE_NRST_LOW   0x00
218 #define STLINK_DEBUG_APIV2_DRIVE_NRST_HIGH  0x01
219 #define STLINK_DEBUG_APIV2_DRIVE_NRST_PULSE 0x02
220
221 #define STLINK_TRACE_SIZE               1024
222 #define STLINK_TRACE_MAX_HZ             2000000
223 #define STLINK_TRACE_MIN_VERSION        13
224
225 /** */
226 enum stlink_mode {
227         STLINK_MODE_UNKNOWN = 0,
228         STLINK_MODE_DFU,
229         STLINK_MODE_MASS,
230         STLINK_MODE_DEBUG_JTAG,
231         STLINK_MODE_DEBUG_SWD,
232         STLINK_MODE_DEBUG_SWIM
233 };
234
235 #define REQUEST_SENSE        0x03
236 #define REQUEST_SENSE_LENGTH 18
237
238 static const struct {
239         int speed;
240         int speed_divisor;
241 } stlink_khz_to_speed_map[] = {
242         {4000, 0},
243         {1800, 1}, /* default */
244         {1200, 2},
245         {950,  3},
246         {480,  7},
247         {240, 15},
248         {125, 31},
249         {100, 40},
250         {50,  79},
251         {25, 158},
252         {15, 265},
253         {5,  798}
254 };
255
256 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size);
257
258 /** */
259 static int stlink_usb_xfer_v1_get_status(void *handle)
260 {
261         struct stlink_usb_handle_s *h = handle;
262
263         assert(handle != NULL);
264
265         /* read status */
266         memset(h->cmdbuf, 0, STLINK_SG_SIZE);
267
268         if (jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)h->cmdbuf,
269                         13, STLINK_READ_TIMEOUT) != 13)
270                 return ERROR_FAIL;
271
272         uint32_t t1;
273
274         t1 = buf_get_u32(h->cmdbuf, 0, 32);
275
276         /* check for USBS */
277         if (t1 != 0x53425355)
278                 return ERROR_FAIL;
279         /*
280          * CSW status:
281          * 0 success
282          * 1 command failure
283          * 2 phase error
284          */
285         if (h->cmdbuf[12] != 0)
286                 return ERROR_FAIL;
287
288         return ERROR_OK;
289 }
290
291 /** */
292 static int stlink_usb_xfer_rw(void *handle, int cmdsize, const uint8_t *buf, int size)
293 {
294         struct stlink_usb_handle_s *h = handle;
295
296         assert(handle != NULL);
297
298         if (jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)h->cmdbuf, cmdsize,
299                         STLINK_WRITE_TIMEOUT) != cmdsize) {
300                 return ERROR_FAIL;
301         }
302
303         if (h->direction == h->tx_ep && size) {
304                 if (jtag_libusb_bulk_write(h->fd, h->tx_ep, (char *)buf,
305                                 size, STLINK_WRITE_TIMEOUT) != size) {
306                         LOG_DEBUG("bulk write failed");
307                         return ERROR_FAIL;
308                 }
309         } else if (h->direction == h->rx_ep && size) {
310                 if (jtag_libusb_bulk_read(h->fd, h->rx_ep, (char *)buf,
311                                 size, STLINK_READ_TIMEOUT) != size) {
312                         LOG_DEBUG("bulk read failed");
313                         return ERROR_FAIL;
314                 }
315         }
316
317         return ERROR_OK;
318 }
319
320 /** */
321 static int stlink_usb_xfer_v1_get_sense(void *handle)
322 {
323         int res;
324         struct stlink_usb_handle_s *h = handle;
325
326         assert(handle != NULL);
327
328         stlink_usb_init_buffer(handle, h->rx_ep, 16);
329
330         h->cmdbuf[h->cmdidx++] = REQUEST_SENSE;
331         h->cmdbuf[h->cmdidx++] = 0;
332         h->cmdbuf[h->cmdidx++] = 0;
333         h->cmdbuf[h->cmdidx++] = 0;
334         h->cmdbuf[h->cmdidx++] = REQUEST_SENSE_LENGTH;
335
336         res = stlink_usb_xfer_rw(handle, REQUEST_SENSE_LENGTH, h->databuf, 16);
337
338         if (res != ERROR_OK)
339                 return res;
340
341         if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK)
342                 return ERROR_FAIL;
343
344         return ERROR_OK;
345 }
346
347 /** */
348 static int stlink_usb_xfer(void *handle, const uint8_t *buf, int size)
349 {
350         int err, cmdsize = STLINK_CMD_SIZE_V2;
351         struct stlink_usb_handle_s *h = handle;
352
353         assert(handle != NULL);
354
355         if (h->version.stlink == 1)
356                 cmdsize = STLINK_SG_SIZE;
357
358         err = stlink_usb_xfer_rw(handle, cmdsize, buf, size);
359
360         if (err != ERROR_OK)
361                 return err;
362
363         if (h->version.stlink == 1) {
364                 if (stlink_usb_xfer_v1_get_status(handle) != ERROR_OK) {
365                         /* check csw status */
366                         if (h->cmdbuf[12] == 1) {
367                                 LOG_DEBUG("get sense");
368                                 if (stlink_usb_xfer_v1_get_sense(handle) != ERROR_OK)
369                                         return ERROR_FAIL;
370                         }
371                         return ERROR_FAIL;
372                 }
373         }
374
375         return ERROR_OK;
376 }
377
378
379 /**
380     Converts an STLINK status code held in the first byte of a response
381     to an openocd error, logs any error/wait status as debug output.
382 */
383 static int stlink_usb_error_check(void *handle)
384 {
385         struct stlink_usb_handle_s *h = handle;
386
387         assert(handle != NULL);
388
389         /* TODO: no error checking yet on api V1 */
390         if (h->jtag_api == STLINK_JTAG_API_V1)
391                 h->databuf[0] = STLINK_DEBUG_ERR_OK;
392
393         switch (h->databuf[0]) {
394                 case STLINK_DEBUG_ERR_OK:
395                         return ERROR_OK;
396                 case STLINK_DEBUG_ERR_FAULT:
397                         LOG_DEBUG("SWD fault response (0x%x)", STLINK_DEBUG_ERR_FAULT);
398                         return ERROR_FAIL;
399                 case STLINK_SWD_AP_WAIT:
400                         LOG_DEBUG("wait status SWD_AP_WAIT (0x%x)", STLINK_SWD_AP_WAIT);
401                         return ERROR_WAIT;
402                 case STLINK_SWD_DP_WAIT:
403                         LOG_DEBUG("wait status SWD_DP_WAIT (0x%x)", STLINK_SWD_DP_WAIT);
404                         return ERROR_WAIT;
405                 case STLINK_JTAG_WRITE_ERROR:
406                         LOG_DEBUG("Write error");
407                         return ERROR_FAIL;
408                 case STLINK_JTAG_WRITE_VERIF_ERROR:
409                         LOG_DEBUG("Verify error");
410                         return ERROR_FAIL;
411                 case STLINK_SWD_AP_FAULT:
412                         /* git://git.ac6.fr/openocd commit 657e3e885b9ee10
413                          * returns ERROR_OK with the comment:
414                          * Change in error status when reading outside RAM.
415                          * This fix allows CDT plugin to visualize memory.
416                          */
417                         LOG_DEBUG("STLINK_SWD_AP_FAULT");
418                         return ERROR_FAIL;
419                 case STLINK_SWD_AP_ERROR:
420                         LOG_DEBUG("STLINK_SWD_AP_ERROR");
421                         return ERROR_FAIL;
422                 case STLINK_SWD_AP_PARITY_ERROR:
423                         LOG_DEBUG("STLINK_SWD_AP_PARITY_ERROR");
424                         return ERROR_FAIL;
425                 case STLINK_SWD_DP_FAULT:
426                         LOG_DEBUG("STLINK_SWD_DP_FAULT");
427                         return ERROR_FAIL;
428                 case STLINK_SWD_DP_ERROR:
429                         LOG_DEBUG("STLINK_SWD_DP_ERROR");
430                         return ERROR_FAIL;
431                 case STLINK_SWD_DP_PARITY_ERROR:
432                         LOG_DEBUG("STLINK_SWD_DP_PARITY_ERROR");
433                         return ERROR_FAIL;
434                 case STLINK_SWD_AP_WDATA_ERROR:
435                         LOG_DEBUG("STLINK_SWD_AP_WDATA_ERROR");
436                         return ERROR_FAIL;
437                 case STLINK_SWD_AP_STICKY_ERROR:
438                         LOG_DEBUG("STLINK_SWD_AP_STICKY_ERROR");
439                         return ERROR_FAIL;
440                 case STLINK_SWD_AP_STICKYORUN_ERROR:
441                         LOG_DEBUG("STLINK_SWD_AP_STICKYORUN_ERROR");
442                         return ERROR_FAIL;
443                 default:
444                         LOG_DEBUG("unknown/unexpected STLINK status code 0x%x", h->databuf[0]);
445                         return ERROR_FAIL;
446         }
447 }
448
449
450 /** Issue an STLINK command via USB transfer, with retries on any wait status responses.
451
452     Works for commands where the STLINK_DEBUG status is returned in the first
453     byte of the response packet.
454
455     Returns an openocd result code.
456 */
457 static int stlink_cmd_allow_retry(void *handle, const uint8_t *buf, int size)
458 {
459         int retries = 0;
460         int res;
461         while (1) {
462                 res = stlink_usb_xfer(handle, buf, size);
463                 if (res != ERROR_OK)
464                         return res;
465                 res = stlink_usb_error_check(handle);
466                 if (res == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
467                         usleep((1<<retries++) * 1000);
468                         continue;
469                 }
470                 return res;
471         }
472 }
473
474 /** */
475 static int stlink_usb_read_trace(void *handle, const uint8_t *buf, int size)
476 {
477         struct stlink_usb_handle_s *h = handle;
478
479         assert(handle != NULL);
480
481         assert(h->version.stlink >= 2);
482
483         if (jtag_libusb_bulk_read(h->fd, h->trace_ep, (char *)buf,
484                         size, STLINK_READ_TIMEOUT) != size) {
485                 LOG_ERROR("bulk trace read failed");
486                 return ERROR_FAIL;
487         }
488
489         return ERROR_OK;
490 }
491
492 /** */
493 static void stlink_usb_xfer_v1_create_cmd(void *handle, uint8_t direction, uint32_t size)
494 {
495         struct stlink_usb_handle_s *h = handle;
496
497         /* fill the send buffer */
498         strcpy((char *)h->cmdbuf, "USBC");
499         h->cmdidx += 4;
500         /* csw tag not used */
501         h->cmdidx += 4;
502         buf_set_u32(h->cmdbuf+h->cmdidx, 0, 32, size);
503         h->cmdidx += 4;
504         h->cmdbuf[h->cmdidx++] = (direction == h->rx_ep ? ENDPOINT_IN : ENDPOINT_OUT);
505         h->cmdbuf[h->cmdidx++] = 0; /* lun */
506         h->cmdbuf[h->cmdidx++] = STLINK_CMD_SIZE_V1;
507 }
508
509 /** */
510 static void stlink_usb_init_buffer(void *handle, uint8_t direction, uint32_t size)
511 {
512         struct stlink_usb_handle_s *h = handle;
513
514         h->direction = direction;
515
516         h->cmdidx = 0;
517
518         memset(h->cmdbuf, 0, STLINK_SG_SIZE);
519         memset(h->databuf, 0, STLINK_DATA_SIZE);
520
521         if (h->version.stlink == 1)
522                 stlink_usb_xfer_v1_create_cmd(handle, direction, size);
523 }
524
525 /** */
526 static int stlink_usb_version(void *handle)
527 {
528         int res;
529         uint16_t v;
530         struct stlink_usb_handle_s *h = handle;
531
532         assert(handle != NULL);
533
534         stlink_usb_init_buffer(handle, h->rx_ep, 6);
535
536         h->cmdbuf[h->cmdidx++] = STLINK_GET_VERSION;
537
538         res = stlink_usb_xfer(handle, h->databuf, 6);
539
540         if (res != ERROR_OK)
541                 return res;
542
543         v = (h->databuf[0] << 8) | h->databuf[1];
544
545         h->version.stlink = (v >> 12) & 0x0f;
546         h->version.jtag = (v >> 6) & 0x3f;
547         h->version.swim = v & 0x3f;
548         h->vid = buf_get_u32(h->databuf, 16, 16);
549         h->pid = buf_get_u32(h->databuf, 32, 16);
550
551         /* set the supported jtag api version
552          * API V2 is supported since JTAG V11
553          */
554         if (h->version.jtag >= 11)
555                 h->version.jtag_api_max = STLINK_JTAG_API_V2;
556         else
557                 h->version.jtag_api_max = STLINK_JTAG_API_V1;
558
559         LOG_INFO("STLINK v%d JTAG v%d API v%d SWIM v%d VID 0x%04X PID 0x%04X",
560                 h->version.stlink,
561                 h->version.jtag,
562                 (h->version.jtag_api_max == STLINK_JTAG_API_V1) ? 1 : 2,
563                 h->version.swim,
564                 h->vid,
565                 h->pid);
566
567         return ERROR_OK;
568 }
569
570 static int stlink_usb_check_voltage(void *handle, float *target_voltage)
571 {
572         struct stlink_usb_handle_s *h = handle;
573         uint32_t adc_results[2];
574
575         /* only supported by stlink/v2 and for firmware >= 13 */
576         if (h->version.stlink == 1 || h->version.jtag < 13)
577                 return ERROR_COMMAND_NOTFOUND;
578
579         stlink_usb_init_buffer(handle, h->rx_ep, 8);
580
581         h->cmdbuf[h->cmdidx++] = STLINK_GET_TARGET_VOLTAGE;
582
583         int result = stlink_usb_xfer(handle, h->databuf, 8);
584
585         if (result != ERROR_OK)
586                 return result;
587
588         /* convert result */
589         adc_results[0] = le_to_h_u32(h->databuf);
590         adc_results[1] = le_to_h_u32(h->databuf + 4);
591
592         *target_voltage = 0;
593
594         if (adc_results[0])
595                 *target_voltage = 2 * ((float)adc_results[1]) * (float)(1.2 / adc_results[0]);
596
597         LOG_INFO("Target voltage: %f", (double)*target_voltage);
598
599         return ERROR_OK;
600 }
601
602 static int stlink_usb_set_swdclk(void *handle, uint16_t clk_divisor)
603 {
604         struct stlink_usb_handle_s *h = handle;
605
606         assert(handle != NULL);
607
608         /* only supported by stlink/v2 and for firmware >= 22 */
609         if (h->version.stlink == 1 || h->version.jtag < 22)
610                 return ERROR_COMMAND_NOTFOUND;
611
612         stlink_usb_init_buffer(handle, h->rx_ep, 2);
613
614         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
615         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_SWD_SET_FREQ;
616         h_u16_to_le(h->cmdbuf+h->cmdidx, clk_divisor);
617         h->cmdidx += 2;
618
619         int result = stlink_cmd_allow_retry(handle, h->databuf, 2);
620
621         if (result != ERROR_OK)
622                 return result;
623
624         return ERROR_OK;
625 }
626
627 /** */
628 static int stlink_usb_current_mode(void *handle, uint8_t *mode)
629 {
630         int res;
631         struct stlink_usb_handle_s *h = handle;
632
633         assert(handle != NULL);
634
635         stlink_usb_init_buffer(handle, h->rx_ep, 2);
636
637         h->cmdbuf[h->cmdidx++] = STLINK_GET_CURRENT_MODE;
638
639         res = stlink_usb_xfer(handle, h->databuf, 2);
640
641         if (res != ERROR_OK)
642                 return res;
643
644         *mode = h->databuf[0];
645
646         return ERROR_OK;
647 }
648
649 /** */
650 static int stlink_usb_mode_enter(void *handle, enum stlink_mode type)
651 {
652         int rx_size = 0;
653         struct stlink_usb_handle_s *h = handle;
654
655         assert(handle != NULL);
656
657         /* on api V2 we are able the read the latest command
658          * status
659          * TODO: we need the test on api V1 too
660          */
661         if (h->jtag_api == STLINK_JTAG_API_V2)
662                 rx_size = 2;
663
664         stlink_usb_init_buffer(handle, h->rx_ep, rx_size);
665
666         switch (type) {
667                 case STLINK_MODE_DEBUG_JTAG:
668                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
669                         if (h->jtag_api == STLINK_JTAG_API_V1)
670                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
671                         else
672                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
673                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_JTAG;
674                         break;
675                 case STLINK_MODE_DEBUG_SWD:
676                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
677                         if (h->jtag_api == STLINK_JTAG_API_V1)
678                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_ENTER;
679                         else
680                                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_ENTER;
681                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_ENTER_SWD;
682                         break;
683                 case STLINK_MODE_DEBUG_SWIM:
684                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
685                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_ENTER;
686                         break;
687                 case STLINK_MODE_DFU:
688                 case STLINK_MODE_MASS:
689                 default:
690                         return ERROR_FAIL;
691         }
692
693         return stlink_cmd_allow_retry(handle, h->databuf, rx_size);
694 }
695
696 /** */
697 static int stlink_usb_mode_leave(void *handle, enum stlink_mode type)
698 {
699         int res;
700         struct stlink_usb_handle_s *h = handle;
701
702         assert(handle != NULL);
703
704         stlink_usb_init_buffer(handle, STLINK_NULL_EP, 0);
705
706         switch (type) {
707                 case STLINK_MODE_DEBUG_JTAG:
708                 case STLINK_MODE_DEBUG_SWD:
709                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
710                         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_EXIT;
711                         break;
712                 case STLINK_MODE_DEBUG_SWIM:
713                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_COMMAND;
714                         h->cmdbuf[h->cmdidx++] = STLINK_SWIM_EXIT;
715                         break;
716                 case STLINK_MODE_DFU:
717                         h->cmdbuf[h->cmdidx++] = STLINK_DFU_COMMAND;
718                         h->cmdbuf[h->cmdidx++] = STLINK_DFU_EXIT;
719                         break;
720                 case STLINK_MODE_MASS:
721                 default:
722                         return ERROR_FAIL;
723         }
724
725         res = stlink_usb_xfer(handle, 0, 0);
726
727         if (res != ERROR_OK)
728                 return res;
729
730         return ERROR_OK;
731 }
732
733 static int stlink_usb_assert_srst(void *handle, int srst);
734
735 static enum stlink_mode stlink_get_mode(enum hl_transports t)
736 {
737         switch (t) {
738         case HL_TRANSPORT_SWD:
739                 return STLINK_MODE_DEBUG_SWD;
740         case HL_TRANSPORT_JTAG:
741                 return STLINK_MODE_DEBUG_JTAG;
742         case HL_TRANSPORT_SWIM:
743                 return STLINK_MODE_DEBUG_SWIM;
744         default:
745                 return STLINK_MODE_UNKNOWN;
746         }
747 }
748
749 /** */
750 static int stlink_usb_init_mode(void *handle, bool connect_under_reset)
751 {
752         int res;
753         uint8_t mode;
754         enum stlink_mode emode;
755         struct stlink_usb_handle_s *h = handle;
756
757         assert(handle != NULL);
758
759         res = stlink_usb_current_mode(handle, &mode);
760
761         if (res != ERROR_OK)
762                 return res;
763
764         LOG_DEBUG("MODE: 0x%02X", mode);
765
766         /* try to exit current mode */
767         switch (mode) {
768                 case STLINK_DEV_DFU_MODE:
769                         emode = STLINK_MODE_DFU;
770                         break;
771                 case STLINK_DEV_DEBUG_MODE:
772                         emode = STLINK_MODE_DEBUG_SWD;
773                         break;
774                 case STLINK_DEV_SWIM_MODE:
775                         emode = STLINK_MODE_DEBUG_SWIM;
776                         break;
777                 case STLINK_DEV_BOOTLOADER_MODE:
778                 case STLINK_DEV_MASS_MODE:
779                 default:
780                         emode = STLINK_MODE_UNKNOWN;
781                         break;
782         }
783
784         if (emode != STLINK_MODE_UNKNOWN) {
785                 res = stlink_usb_mode_leave(handle, emode);
786
787                 if (res != ERROR_OK)
788                         return res;
789         }
790
791         res = stlink_usb_current_mode(handle, &mode);
792
793         if (res != ERROR_OK)
794                 return res;
795
796         /* we check the target voltage here as an aid to debugging connection problems.
797          * the stlink requires the target Vdd to be connected for reliable debugging.
798          * this cmd is supported in all modes except DFU
799          */
800         if (mode != STLINK_DEV_DFU_MODE) {
801
802                 float target_voltage;
803
804                 /* check target voltage (if supported) */
805                 res = stlink_usb_check_voltage(h, &target_voltage);
806
807                 if (res != ERROR_OK) {
808                         if (res != ERROR_COMMAND_NOTFOUND)
809                                 LOG_ERROR("voltage check failed");
810                         /* attempt to continue as it is not a catastrophic failure */
811                 } else {
812                         /* check for a sensible target voltage, operating range is 1.65-5.5v
813                          * according to datasheet */
814                         if (target_voltage < 1.5)
815                                 LOG_ERROR("target voltage may be too low for reliable debugging");
816                 }
817         }
818
819         LOG_DEBUG("MODE: 0x%02X", mode);
820
821         /* set selected mode */
822         emode = stlink_get_mode(h->transport);
823
824         if (emode == STLINK_MODE_UNKNOWN) {
825                 LOG_ERROR("selected mode (transport) not supported");
826                 return ERROR_FAIL;
827         }
828
829         if (connect_under_reset) {
830                 res = stlink_usb_assert_srst(handle, 0);
831                 if (res != ERROR_OK)
832                         return res;
833         }
834
835         res = stlink_usb_mode_enter(handle, emode);
836
837         if (res != ERROR_OK)
838                 return res;
839
840         res = stlink_usb_current_mode(handle, &mode);
841
842         if (res != ERROR_OK)
843                 return res;
844
845         LOG_DEBUG("MODE: 0x%02X", mode);
846
847         return ERROR_OK;
848 }
849
850 /** */
851 static int stlink_usb_idcode(void *handle, uint32_t *idcode)
852 {
853         int res;
854         struct stlink_usb_handle_s *h = handle;
855
856         assert(handle != NULL);
857
858         stlink_usb_init_buffer(handle, h->rx_ep, 4);
859
860         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
861         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READCOREID;
862
863         res = stlink_usb_xfer(handle, h->databuf, 4);
864
865         if (res != ERROR_OK)
866                 return res;
867
868         *idcode = le_to_h_u32(h->databuf);
869
870         LOG_DEBUG("IDCODE: 0x%08" PRIX32, *idcode);
871
872         return ERROR_OK;
873 }
874
875 static int stlink_usb_v2_read_debug_reg(void *handle, uint32_t addr, uint32_t *val)
876 {
877         struct stlink_usb_handle_s *h = handle;
878         int res;
879
880         assert(handle != NULL);
881
882         stlink_usb_init_buffer(handle, h->rx_ep, 8);
883
884         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
885         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READDEBUGREG;
886         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
887         h->cmdidx += 4;
888
889         res = stlink_cmd_allow_retry(handle, h->databuf, 8);
890         if (res != ERROR_OK)
891                 return res;
892
893         *val = le_to_h_u32(h->databuf + 4);
894         return ERROR_OK;
895 }
896
897 static int stlink_usb_write_debug_reg(void *handle, uint32_t addr, uint32_t val)
898 {
899         struct stlink_usb_handle_s *h = handle;
900
901         assert(handle != NULL);
902
903         stlink_usb_init_buffer(handle, h->rx_ep, 2);
904
905         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
906         if (h->jtag_api == STLINK_JTAG_API_V1)
907                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEDEBUGREG;
908         else
909                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEDEBUGREG;
910         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
911         h->cmdidx += 4;
912         h_u32_to_le(h->cmdbuf+h->cmdidx, val);
913         h->cmdidx += 4;
914
915         return stlink_cmd_allow_retry(handle, h->databuf, 2);
916 }
917
918 /** */
919 static int stlink_usb_trace_read(void *handle, uint8_t *buf, size_t *size)
920 {
921         struct stlink_usb_handle_s *h = handle;
922
923         assert(handle != NULL);
924
925         if (h->trace.enabled && h->version.jtag >= STLINK_TRACE_MIN_VERSION) {
926                 int res;
927
928                 stlink_usb_init_buffer(handle, h->rx_ep, 10);
929
930                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
931                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GET_TRACE_NB;
932
933                 res = stlink_usb_xfer(handle, h->databuf, 2);
934                 if (res != ERROR_OK)
935                         return res;
936
937                 size_t bytes_avail = le_to_h_u16(h->databuf);
938                 *size = bytes_avail < *size ? bytes_avail : *size - 1;
939
940                 if (*size > 0) {
941                         res = stlink_usb_read_trace(handle, buf, *size);
942                         if (res != ERROR_OK)
943                                 return res;
944                         return ERROR_OK;
945                 }
946         }
947         *size = 0;
948         return ERROR_OK;
949 }
950
951 static enum target_state stlink_usb_v2_get_status(void *handle)
952 {
953         int result;
954         uint32_t status;
955
956         result = stlink_usb_v2_read_debug_reg(handle, DCB_DHCSR, &status);
957         if  (result != ERROR_OK)
958                 return TARGET_UNKNOWN;
959
960         if (status & S_HALT)
961                 return TARGET_HALTED;
962         else if (status & S_RESET_ST)
963                 return TARGET_RESET;
964
965         return TARGET_RUNNING;
966 }
967
968 /** */
969 static enum target_state stlink_usb_state(void *handle)
970 {
971         int res;
972         struct stlink_usb_handle_s *h = handle;
973
974         assert(handle != NULL);
975
976         if (h->reconnect_pending) {
977                 LOG_INFO("Previous state query failed, trying to reconnect");
978                 res = stlink_usb_mode_enter(handle, stlink_get_mode(h->transport));
979
980                 if (res != ERROR_OK)
981                         return TARGET_UNKNOWN;
982
983                 h->reconnect_pending = false;
984         }
985
986         if (h->jtag_api == STLINK_JTAG_API_V2) {
987                 res = stlink_usb_v2_get_status(handle);
988                 if (res == TARGET_UNKNOWN)
989                         h->reconnect_pending = true;
990                 return res;
991         }
992
993         stlink_usb_init_buffer(handle, h->rx_ep, 2);
994
995         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
996         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_GETSTATUS;
997
998         res = stlink_usb_xfer(handle, h->databuf, 2);
999
1000         if (res != ERROR_OK)
1001                 return TARGET_UNKNOWN;
1002
1003         if (h->databuf[0] == STLINK_CORE_RUNNING)
1004                 return TARGET_RUNNING;
1005         if (h->databuf[0] == STLINK_CORE_HALTED)
1006                 return TARGET_HALTED;
1007
1008         h->reconnect_pending = true;
1009
1010         return TARGET_UNKNOWN;
1011 }
1012
1013 static int stlink_usb_assert_srst(void *handle, int srst)
1014 {
1015         struct stlink_usb_handle_s *h = handle;
1016
1017         assert(handle != NULL);
1018
1019         if (h->version.stlink == 1)
1020                 return ERROR_COMMAND_NOTFOUND;
1021
1022         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1023
1024         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1025         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_DRIVE_NRST;
1026         h->cmdbuf[h->cmdidx++] = srst;
1027
1028         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1029 }
1030
1031 /** */
1032 static void stlink_usb_trace_disable(void *handle)
1033 {
1034         int res = ERROR_OK;
1035         struct stlink_usb_handle_s *h = handle;
1036
1037         assert(handle != NULL);
1038
1039         assert(h->version.jtag >= STLINK_TRACE_MIN_VERSION);
1040
1041         LOG_DEBUG("Tracing: disable");
1042
1043         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1044         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1045         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_STOP_TRACE_RX;
1046         res = stlink_usb_xfer(handle, h->databuf, 2);
1047
1048         if (res == ERROR_OK)
1049                 h->trace.enabled = false;
1050 }
1051
1052
1053 /** */
1054 static int stlink_usb_trace_enable(void *handle)
1055 {
1056         int res;
1057         struct stlink_usb_handle_s *h = handle;
1058
1059         assert(handle != NULL);
1060
1061         if (h->version.jtag >= STLINK_TRACE_MIN_VERSION) {
1062                 stlink_usb_init_buffer(handle, h->rx_ep, 10);
1063
1064                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1065                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_START_TRACE_RX;
1066                 h_u16_to_le(h->cmdbuf+h->cmdidx, (uint16_t)STLINK_TRACE_SIZE);
1067                 h->cmdidx += 2;
1068                 h_u32_to_le(h->cmdbuf+h->cmdidx, h->trace.source_hz);
1069                 h->cmdidx += 4;
1070
1071                 res = stlink_usb_xfer(handle, h->databuf, 2);
1072
1073                 if (res == ERROR_OK)  {
1074                         h->trace.enabled = true;
1075                         LOG_DEBUG("Tracing: recording at %" PRIu32 "Hz", h->trace.source_hz);
1076                 }
1077         } else {
1078                 LOG_ERROR("Tracing is not supported by this version.");
1079                 res = ERROR_FAIL;
1080         }
1081
1082         return res;
1083 }
1084
1085 /** */
1086 static int stlink_usb_reset(void *handle)
1087 {
1088         struct stlink_usb_handle_s *h = handle;
1089         int retval;
1090
1091         assert(handle != NULL);
1092
1093         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1094
1095         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1096
1097         if (h->jtag_api == STLINK_JTAG_API_V1)
1098                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_RESETSYS;
1099         else
1100                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_RESETSYS;
1101
1102         retval = stlink_cmd_allow_retry(handle, h->databuf, 2);
1103         if (retval != ERROR_OK)
1104                 return retval;
1105
1106         if (h->trace.enabled) {
1107                 stlink_usb_trace_disable(h);
1108                 return stlink_usb_trace_enable(h);
1109         }
1110
1111         return ERROR_OK;
1112 }
1113
1114 /** */
1115 static int stlink_usb_run(void *handle)
1116 {
1117         int res;
1118         struct stlink_usb_handle_s *h = handle;
1119
1120         assert(handle != NULL);
1121
1122         if (h->jtag_api == STLINK_JTAG_API_V2) {
1123                 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_DEBUGEN);
1124
1125                 return res;
1126         }
1127
1128         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1129
1130         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1131         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_RUNCORE;
1132
1133         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1134 }
1135
1136 /** */
1137 static int stlink_usb_halt(void *handle)
1138 {
1139         int res;
1140         struct stlink_usb_handle_s *h = handle;
1141
1142         assert(handle != NULL);
1143
1144         if (h->jtag_api == STLINK_JTAG_API_V2) {
1145                 res = stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1146
1147                 return res;
1148         }
1149
1150         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1151
1152         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1153         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_FORCEDEBUG;
1154
1155         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1156 }
1157
1158 /** */
1159 static int stlink_usb_step(void *handle)
1160 {
1161         struct stlink_usb_handle_s *h = handle;
1162
1163         assert(handle != NULL);
1164
1165         if (h->jtag_api == STLINK_JTAG_API_V2) {
1166                 /* TODO: this emulates the v1 api, it should really use a similar auto mask isr
1167                  * that the cortex-m3 currently does. */
1168                 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_MASKINTS|C_DEBUGEN);
1169                 stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_STEP|C_MASKINTS|C_DEBUGEN);
1170                 return stlink_usb_write_debug_reg(handle, DCB_DHCSR, DBGKEY|C_HALT|C_DEBUGEN);
1171         }
1172
1173         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1174
1175         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1176         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_STEPCORE;
1177
1178         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1179 }
1180
1181 /** */
1182 static int stlink_usb_read_regs(void *handle)
1183 {
1184         int res;
1185         struct stlink_usb_handle_s *h = handle;
1186
1187         assert(handle != NULL);
1188
1189         stlink_usb_init_buffer(handle, h->rx_ep, 84);
1190
1191         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1192         if (h->jtag_api == STLINK_JTAG_API_V1)
1193                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READALLREGS;
1194         else
1195                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READALLREGS;
1196
1197         res = stlink_usb_xfer(handle, h->databuf, 84);
1198
1199         if (res != ERROR_OK)
1200                 return res;
1201
1202         return ERROR_OK;
1203 }
1204
1205 /** */
1206 static int stlink_usb_read_reg(void *handle, int num, uint32_t *val)
1207 {
1208         int res;
1209         struct stlink_usb_handle_s *h = handle;
1210
1211         assert(handle != NULL);
1212
1213         stlink_usb_init_buffer(handle, h->rx_ep, h->jtag_api == STLINK_JTAG_API_V1 ? 4 : 8);
1214
1215         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1216         if (h->jtag_api == STLINK_JTAG_API_V1)
1217                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_READREG;
1218         else
1219                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_READREG;
1220         h->cmdbuf[h->cmdidx++] = num;
1221
1222         if (h->jtag_api == STLINK_JTAG_API_V1) {
1223                 res = stlink_usb_xfer(handle, h->databuf, 4);
1224                 if (res != ERROR_OK)
1225                         return res;
1226                 *val = le_to_h_u32(h->databuf);
1227                 return ERROR_OK;
1228         } else {
1229                 res = stlink_cmd_allow_retry(handle, h->databuf, 8);
1230                 if (res != ERROR_OK)
1231                         return res;
1232                 *val = le_to_h_u32(h->databuf + 4);
1233                 return ERROR_OK;
1234         }
1235 }
1236
1237 /** */
1238 static int stlink_usb_write_reg(void *handle, int num, uint32_t val)
1239 {
1240         struct stlink_usb_handle_s *h = handle;
1241
1242         assert(handle != NULL);
1243
1244         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1245
1246         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1247         if (h->jtag_api == STLINK_JTAG_API_V1)
1248                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV1_WRITEREG;
1249         else
1250                 h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_WRITEREG;
1251         h->cmdbuf[h->cmdidx++] = num;
1252         h_u32_to_le(h->cmdbuf+h->cmdidx, val);
1253         h->cmdidx += 4;
1254
1255         return stlink_cmd_allow_retry(handle, h->databuf, 2);
1256 }
1257
1258 static int stlink_usb_get_rw_status(void *handle)
1259 {
1260         int res;
1261         struct stlink_usb_handle_s *h = handle;
1262
1263         assert(handle != NULL);
1264
1265         if (h->jtag_api == STLINK_JTAG_API_V1)
1266                 return ERROR_OK;
1267
1268         stlink_usb_init_buffer(handle, h->rx_ep, 2);
1269
1270         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1271         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_APIV2_GETLASTRWSTATUS;
1272
1273         res = stlink_usb_xfer(handle, h->databuf, 2);
1274
1275         if (res != ERROR_OK)
1276                 return res;
1277
1278         return stlink_usb_error_check(h);
1279 }
1280
1281 /** */
1282 static int stlink_usb_read_mem8(void *handle, uint32_t addr, uint16_t len,
1283                           uint8_t *buffer)
1284 {
1285         int res;
1286         uint16_t read_len = len;
1287         struct stlink_usb_handle_s *h = handle;
1288
1289         assert(handle != NULL);
1290
1291         /* max 8bit read/write is 64bytes */
1292         if (len > STLINK_MAX_RW8) {
1293                 LOG_DEBUG("max buffer length exceeded");
1294                 return ERROR_FAIL;
1295         }
1296
1297         stlink_usb_init_buffer(handle, h->rx_ep, read_len);
1298
1299         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1300         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_8BIT;
1301         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1302         h->cmdidx += 4;
1303         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
1304         h->cmdidx += 2;
1305
1306         /* we need to fix read length for single bytes */
1307         if (read_len == 1)
1308                 read_len++;
1309
1310         res = stlink_usb_xfer(handle, h->databuf, read_len);
1311
1312         if (res != ERROR_OK)
1313                 return res;
1314
1315         memcpy(buffer, h->databuf, len);
1316
1317         return stlink_usb_get_rw_status(handle);
1318 }
1319
1320 /** */
1321 static int stlink_usb_write_mem8(void *handle, uint32_t addr, uint16_t len,
1322                            const uint8_t *buffer)
1323 {
1324         int res;
1325         struct stlink_usb_handle_s *h = handle;
1326
1327         assert(handle != NULL);
1328
1329         /* max 8bit read/write is 64bytes */
1330         if (len > STLINK_MAX_RW8) {
1331                 LOG_DEBUG("max buffer length exceeded");
1332                 return ERROR_FAIL;
1333         }
1334
1335         stlink_usb_init_buffer(handle, h->tx_ep, len);
1336
1337         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1338         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_8BIT;
1339         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1340         h->cmdidx += 4;
1341         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
1342         h->cmdidx += 2;
1343
1344         res = stlink_usb_xfer(handle, buffer, len);
1345
1346         if (res != ERROR_OK)
1347                 return res;
1348
1349         return stlink_usb_get_rw_status(handle);
1350 }
1351
1352 /** */
1353 static int stlink_usb_read_mem32(void *handle, uint32_t addr, uint16_t len,
1354                           uint8_t *buffer)
1355 {
1356         int res;
1357         struct stlink_usb_handle_s *h = handle;
1358
1359         assert(handle != NULL);
1360
1361         /* data must be a multiple of 4 and word aligned */
1362         if (len % 4 || addr % 4) {
1363                 LOG_DEBUG("Invalid data alignment");
1364                 return ERROR_TARGET_UNALIGNED_ACCESS;
1365         }
1366
1367         stlink_usb_init_buffer(handle, h->rx_ep, len);
1368
1369         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1370         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_READMEM_32BIT;
1371         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1372         h->cmdidx += 4;
1373         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
1374         h->cmdidx += 2;
1375
1376         res = stlink_usb_xfer(handle, h->databuf, len);
1377
1378         if (res != ERROR_OK)
1379                 return res;
1380
1381         memcpy(buffer, h->databuf, len);
1382
1383         return stlink_usb_get_rw_status(handle);
1384 }
1385
1386 /** */
1387 static int stlink_usb_write_mem32(void *handle, uint32_t addr, uint16_t len,
1388                            const uint8_t *buffer)
1389 {
1390         int res;
1391         struct stlink_usb_handle_s *h = handle;
1392
1393         assert(handle != NULL);
1394
1395         /* data must be a multiple of 4 and word aligned */
1396         if (len % 4 || addr % 4) {
1397                 LOG_DEBUG("Invalid data alignment");
1398                 return ERROR_TARGET_UNALIGNED_ACCESS;
1399         }
1400
1401         stlink_usb_init_buffer(handle, h->tx_ep, len);
1402
1403         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_COMMAND;
1404         h->cmdbuf[h->cmdidx++] = STLINK_DEBUG_WRITEMEM_32BIT;
1405         h_u32_to_le(h->cmdbuf+h->cmdidx, addr);
1406         h->cmdidx += 4;
1407         h_u16_to_le(h->cmdbuf+h->cmdidx, len);
1408         h->cmdidx += 2;
1409
1410         res = stlink_usb_xfer(handle, buffer, len);
1411
1412         if (res != ERROR_OK)
1413                 return res;
1414
1415         return stlink_usb_get_rw_status(handle);
1416 }
1417
1418 static uint32_t stlink_max_block_size(uint32_t tar_autoincr_block, uint32_t address)
1419 {
1420         uint32_t max_tar_block = (tar_autoincr_block - ((tar_autoincr_block - 1) & address));
1421         if (max_tar_block == 0)
1422                 max_tar_block = 4;
1423         return max_tar_block;
1424 }
1425
1426 static int stlink_usb_read_mem(void *handle, uint32_t addr, uint32_t size,
1427                 uint32_t count, uint8_t *buffer)
1428 {
1429         int retval = ERROR_OK;
1430         uint32_t bytes_remaining;
1431         int retries = 0;
1432         struct stlink_usb_handle_s *h = handle;
1433
1434         /* calculate byte count */
1435         count *= size;
1436
1437         while (count) {
1438
1439                 bytes_remaining = (size == 4) ? \
1440                                 stlink_max_block_size(h->max_mem_packet, addr) : STLINK_MAX_RW8;
1441
1442                 if (count < bytes_remaining)
1443                         bytes_remaining = count;
1444
1445                 /* the stlink only supports 8/32bit memory read/writes
1446                  * honour 32bit, all others will be handled as 8bit access */
1447                 if (size == 4) {
1448
1449                         /* When in jtag mode the stlink uses the auto-increment functinality.
1450                          * However it expects us to pass the data correctly, this includes
1451                          * alignment and any page boundaries. We already do this as part of the
1452                          * adi_v5 implementation, but the stlink is a hla adapter and so this
1453                          * needs implementiong manually.
1454                          * currently this only affects jtag mode, according to ST they do single
1455                          * access in SWD mode - but this may change and so we do it for both modes */
1456
1457                         /* we first need to check for any unaligned bytes */
1458                         if (addr % 4) {
1459
1460                                 uint32_t head_bytes = 4 - (addr % 4);
1461                                 retval = stlink_usb_read_mem8(handle, addr, head_bytes, buffer);
1462                                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1463                                         usleep((1<<retries++) * 1000);
1464                                         continue;
1465                                 }
1466                                 if (retval != ERROR_OK)
1467                                         return retval;
1468                                 buffer += head_bytes;
1469                                 addr += head_bytes;
1470                                 count -= head_bytes;
1471                                 bytes_remaining -= head_bytes;
1472                         }
1473
1474                         if (bytes_remaining % 4)
1475                                 retval = stlink_usb_read_mem(handle, addr, 1, bytes_remaining, buffer);
1476                         else
1477                                 retval = stlink_usb_read_mem32(handle, addr, bytes_remaining, buffer);
1478                 } else
1479                         retval = stlink_usb_read_mem8(handle, addr, bytes_remaining, buffer);
1480
1481                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1482                         usleep((1<<retries++) * 1000);
1483                         continue;
1484                 }
1485                 if (retval != ERROR_OK)
1486                         return retval;
1487
1488                 buffer += bytes_remaining;
1489                 addr += bytes_remaining;
1490                 count -= bytes_remaining;
1491         }
1492
1493         return retval;
1494 }
1495
1496 static int stlink_usb_write_mem(void *handle, uint32_t addr, uint32_t size,
1497                 uint32_t count, const uint8_t *buffer)
1498 {
1499         int retval = ERROR_OK;
1500         uint32_t bytes_remaining;
1501         int retries = 0;
1502         struct stlink_usb_handle_s *h = handle;
1503
1504         /* calculate byte count */
1505         count *= size;
1506
1507         while (count) {
1508
1509                 bytes_remaining = (size == 4) ? \
1510                                 stlink_max_block_size(h->max_mem_packet, addr) : STLINK_MAX_RW8;
1511
1512                 if (count < bytes_remaining)
1513                         bytes_remaining = count;
1514
1515                 /* the stlink only supports 8/32bit memory read/writes
1516                  * honour 32bit, all others will be handled as 8bit access */
1517                 if (size == 4) {
1518
1519                         /* When in jtag mode the stlink uses the auto-increment functinality.
1520                          * However it expects us to pass the data correctly, this includes
1521                          * alignment and any page boundaries. We already do this as part of the
1522                          * adi_v5 implementation, but the stlink is a hla adapter and so this
1523                          * needs implementiong manually.
1524                          * currently this only affects jtag mode, according to ST they do single
1525                          * access in SWD mode - but this may change and so we do it for both modes */
1526
1527                         /* we first need to check for any unaligned bytes */
1528                         if (addr % 4) {
1529
1530                                 uint32_t head_bytes = 4 - (addr % 4);
1531                                 retval = stlink_usb_write_mem8(handle, addr, head_bytes, buffer);
1532                                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1533                                         usleep((1<<retries++) * 1000);
1534                                         continue;
1535                                 }
1536                                 if (retval != ERROR_OK)
1537                                         return retval;
1538                                 buffer += head_bytes;
1539                                 addr += head_bytes;
1540                                 count -= head_bytes;
1541                                 bytes_remaining -= head_bytes;
1542                         }
1543
1544                         if (bytes_remaining % 4)
1545                                 retval = stlink_usb_write_mem(handle, addr, 1, bytes_remaining, buffer);
1546                         else
1547                                 retval = stlink_usb_write_mem32(handle, addr, bytes_remaining, buffer);
1548
1549                 } else
1550                         retval = stlink_usb_write_mem8(handle, addr, bytes_remaining, buffer);
1551                 if (retval == ERROR_WAIT && retries < MAX_WAIT_RETRIES) {
1552                         usleep((1<<retries++) * 1000);
1553                         continue;
1554                 }
1555                 if (retval != ERROR_OK)
1556                         return retval;
1557
1558                 buffer += bytes_remaining;
1559                 addr += bytes_remaining;
1560                 count -= bytes_remaining;
1561         }
1562
1563         return retval;
1564 }
1565
1566 /** */
1567 static int stlink_usb_override_target(const char *targetname)
1568 {
1569         return !strcmp(targetname, "cortex_m");
1570 }
1571
1572 static int stlink_speed(void *handle, int khz, bool query)
1573 {
1574         unsigned i;
1575         int speed_index = -1;
1576         int speed_diff = INT_MAX;
1577         struct stlink_usb_handle_s *h = handle;
1578
1579         /* only supported by stlink/v2 and for firmware >= 22 */
1580         if (h && (h->version.stlink == 1 || h->version.jtag < 22))
1581                 return khz;
1582
1583         for (i = 0; i < ARRAY_SIZE(stlink_khz_to_speed_map); i++) {
1584                 if (khz == stlink_khz_to_speed_map[i].speed) {
1585                         speed_index = i;
1586                         break;
1587                 } else {
1588                         int current_diff = khz - stlink_khz_to_speed_map[i].speed;
1589                         /* get abs value for comparison */
1590                         current_diff = (current_diff > 0) ? current_diff : -current_diff;
1591                         if ((current_diff < speed_diff) && khz >= stlink_khz_to_speed_map[i].speed) {
1592                                 speed_diff = current_diff;
1593                                 speed_index = i;
1594                         }
1595                 }
1596         }
1597
1598         bool match = true;
1599
1600         if (speed_index == -1) {
1601                 /* this will only be here if we cannot match the slow speed.
1602                  * use the slowest speed we support.*/
1603                 speed_index = ARRAY_SIZE(stlink_khz_to_speed_map) - 1;
1604                 match = false;
1605         } else if (i == ARRAY_SIZE(stlink_khz_to_speed_map))
1606                 match = false;
1607
1608         if (!match && query) {
1609                 LOG_INFO("Unable to match requested speed %d kHz, using %d kHz", \
1610                                 khz, stlink_khz_to_speed_map[speed_index].speed);
1611         }
1612
1613         if (h && !query) {
1614                 int result = stlink_usb_set_swdclk(h, stlink_khz_to_speed_map[speed_index].speed_divisor);
1615                 if (result != ERROR_OK) {
1616                         LOG_ERROR("Unable to set adapter speed");
1617                         return khz;
1618                 }
1619         }
1620
1621         return stlink_khz_to_speed_map[speed_index].speed;
1622 }
1623
1624 /** */
1625 static int stlink_usb_close(void *handle)
1626 {
1627         struct stlink_usb_handle_s *h = handle;
1628
1629         if (h && h->fd)
1630                 jtag_libusb_close(h->fd);
1631
1632         free(h);
1633
1634         return ERROR_OK;
1635 }
1636
1637 /** */
1638 static int stlink_usb_open(struct hl_interface_param_s *param, void **fd)
1639 {
1640         int err, retry_count = 1;
1641         struct stlink_usb_handle_s *h;
1642         enum stlink_jtag_api_version api;
1643
1644         LOG_DEBUG("stlink_usb_open");
1645
1646         h = calloc(1, sizeof(struct stlink_usb_handle_s));
1647
1648         if (h == 0) {
1649                 LOG_DEBUG("malloc failed");
1650                 return ERROR_FAIL;
1651         }
1652
1653         h->transport = param->transport;
1654
1655         const uint16_t vids[] = { param->vid, 0 };
1656         const uint16_t pids[] = { param->pid, 0 };
1657         const char *serial = param->serial;
1658
1659         LOG_DEBUG("transport: %d vid: 0x%04x pid: 0x%04x serial: %s",
1660                         param->transport, param->vid, param->pid,
1661                         param->serial ? param->serial : "");
1662
1663         /*
1664           On certain host USB configurations(e.g. MacBook Air)
1665           STLINKv2 dongle seems to have its FW in a funky state if,
1666           after plugging it in, you try to use openocd with it more
1667           then once (by launching and closing openocd). In cases like
1668           that initial attempt to read the FW info via
1669           stlink_usb_version will fail and the device has to be reset
1670           in order to become operational.
1671          */
1672         do {
1673                 if (jtag_libusb_open(vids, pids, serial, &h->fd) != ERROR_OK) {
1674                         LOG_ERROR("open failed");
1675                         goto error_open;
1676                 }
1677
1678                 jtag_libusb_set_configuration(h->fd, 0);
1679
1680                 if (jtag_libusb_claim_interface(h->fd, 0) != ERROR_OK) {
1681                         LOG_DEBUG("claim interface failed");
1682                         goto error_open;
1683                 }
1684
1685                 /* RX EP is common for all versions */
1686                 h->rx_ep = STLINK_RX_EP;
1687
1688                 /* wrap version for first read */
1689                 switch (param->pid) {
1690                         case STLINK_V1_PID:
1691                                 h->version.stlink = 1;
1692                                 h->tx_ep = STLINK_TX_EP;
1693                                 h->trace_ep = STLINK_TRACE_EP;
1694                                 break;
1695                         case STLINK_V2_1_PID:
1696                                 h->version.stlink = 2;
1697                                 h->tx_ep = STLINK_V2_1_TX_EP;
1698                                 h->trace_ep = STLINK_V2_1_TRACE_EP;
1699                                 break;
1700                         default:
1701                         /* fall through - we assume V2 to be the default version*/
1702                         case STLINK_V2_PID:
1703                                 h->version.stlink = 2;
1704                                 h->tx_ep = STLINK_TX_EP;
1705                                 h->trace_ep = STLINK_TRACE_EP;
1706                                 break;
1707                 }
1708
1709                 /* get the device version */
1710                 err = stlink_usb_version(h);
1711
1712                 if (err == ERROR_OK) {
1713                         break;
1714                 } else if (h->version.stlink == 1 ||
1715                            retry_count == 0) {
1716                         LOG_ERROR("read version failed");
1717                         goto error_open;
1718                 } else {
1719                         err = jtag_libusb_release_interface(h->fd, 0);
1720                         if (err != ERROR_OK) {
1721                                 LOG_ERROR("release interface failed");
1722                                 goto error_open;
1723                         }
1724
1725                         err = jtag_libusb_reset_device(h->fd);
1726                         if (err != ERROR_OK) {
1727                                 LOG_ERROR("reset device failed");
1728                                 goto error_open;
1729                         }
1730
1731                         jtag_libusb_close(h->fd);
1732                         /*
1733                           Give the device one second to settle down and
1734                           reenumerate.
1735                          */
1736                         usleep(1 * 1000 * 1000);
1737                         retry_count--;
1738                 }
1739         } while (1);
1740
1741         /* compare usb vid/pid */
1742         if ((param->vid != h->vid) || (param->pid != h->pid))
1743                 LOG_INFO("vid/pid are not identical: 0x%04X/0x%04X 0x%04X/0x%04X",
1744                         param->vid, param->pid,
1745                         h->vid, h->pid);
1746
1747         /* check if mode is supported */
1748         err = ERROR_OK;
1749
1750         switch (h->transport) {
1751                 case HL_TRANSPORT_SWD:
1752                 case HL_TRANSPORT_JTAG:
1753                         if (h->version.jtag == 0)
1754                                 err = ERROR_FAIL;
1755                         break;
1756                 case HL_TRANSPORT_SWIM:
1757                         if (h->version.swim == 0)
1758                                 err = ERROR_FAIL;
1759                         break;
1760                 default:
1761                         err = ERROR_FAIL;
1762                         break;
1763         }
1764
1765         if (err != ERROR_OK) {
1766                 LOG_ERROR("mode (transport) not supported by device");
1767                 goto error_open;
1768         }
1769
1770         api = h->version.jtag_api_max;
1771
1772         LOG_INFO("using stlink api v%d", api);
1773
1774         /* set the used jtag api, this will default to the newest supported version */
1775         h->jtag_api = api;
1776
1777         /* initialize the debug hardware */
1778         err = stlink_usb_init_mode(h, param->connect_under_reset);
1779
1780         if (err != ERROR_OK) {
1781                 LOG_ERROR("init mode failed (unable to connect to the target)");
1782                 goto error_open;
1783         }
1784
1785         /* clock speed only supported by stlink/v2 and for firmware >= 22 */
1786         if (h->version.stlink >= 2 && h->version.jtag >= 22) {
1787                 LOG_DEBUG("Supported clock speeds are:");
1788
1789                 for (unsigned i = 0; i < ARRAY_SIZE(stlink_khz_to_speed_map); i++)
1790                         LOG_DEBUG("%d kHz", stlink_khz_to_speed_map[i].speed);
1791
1792                 stlink_speed(h, param->initial_interface_speed, false);
1793         }
1794
1795         /* get cpuid, so we can determine the max page size
1796          * start with a safe default */
1797         h->max_mem_packet = (1 << 10);
1798
1799         uint8_t buffer[4];
1800         err = stlink_usb_read_mem32(h, CPUID, 4, buffer);
1801         if (err == ERROR_OK) {
1802                 uint32_t cpuid = le_to_h_u32(buffer);
1803                 int i = (cpuid >> 4) & 0xf;
1804                 if (i == 4 || i == 3) {
1805                         /* Cortex-M3/M4 has 4096 bytes autoincrement range */
1806                         h->max_mem_packet = (1 << 12);
1807                 }
1808         }
1809
1810         LOG_DEBUG("Using TAR autoincrement: %" PRIu32, h->max_mem_packet);
1811
1812         *fd = h;
1813
1814         return ERROR_OK;
1815
1816 error_open:
1817         stlink_usb_close(h);
1818
1819         return ERROR_FAIL;
1820 }
1821
1822 int stlink_config_trace(void *handle, bool enabled, enum tpio_pin_protocol pin_protocol,
1823                         uint32_t port_size, unsigned int *trace_freq)
1824 {
1825         struct stlink_usb_handle_s *h = handle;
1826
1827         if (enabled && (h->jtag_api < 2 || pin_protocol != ASYNC_UART)) {
1828                 LOG_ERROR("The attached ST-LINK version doesn't support this trace mode");
1829                 return ERROR_FAIL;
1830         }
1831
1832         if (!enabled) {
1833                 stlink_usb_trace_disable(h);
1834                 return ERROR_OK;
1835         }
1836
1837         if (*trace_freq > STLINK_TRACE_MAX_HZ) {
1838                 LOG_ERROR("ST-LINK doesn't support SWO frequency higher than %u",
1839                           STLINK_TRACE_MAX_HZ);
1840                 return ERROR_FAIL;
1841         }
1842
1843         stlink_usb_trace_disable(h);
1844
1845         if (!*trace_freq)
1846                 *trace_freq = STLINK_TRACE_MAX_HZ;
1847         h->trace.source_hz = *trace_freq;
1848
1849         return stlink_usb_trace_enable(h);
1850 }
1851
1852 /** */
1853 struct hl_layout_api_s stlink_usb_layout_api = {
1854         /** */
1855         .open = stlink_usb_open,
1856         /** */
1857         .close = stlink_usb_close,
1858         /** */
1859         .idcode = stlink_usb_idcode,
1860         /** */
1861         .state = stlink_usb_state,
1862         /** */
1863         .reset = stlink_usb_reset,
1864         /** */
1865         .assert_srst = stlink_usb_assert_srst,
1866         /** */
1867         .run = stlink_usb_run,
1868         /** */
1869         .halt = stlink_usb_halt,
1870         /** */
1871         .step = stlink_usb_step,
1872         /** */
1873         .read_regs = stlink_usb_read_regs,
1874         /** */
1875         .read_reg = stlink_usb_read_reg,
1876         /** */
1877         .write_reg = stlink_usb_write_reg,
1878         /** */
1879         .read_mem = stlink_usb_read_mem,
1880         /** */
1881         .write_mem = stlink_usb_write_mem,
1882         /** */
1883         .write_debug_reg = stlink_usb_write_debug_reg,
1884         /** */
1885         .override_target = stlink_usb_override_target,
1886         /** */
1887         .speed = stlink_speed,
1888         /** */
1889         .config_trace = stlink_config_trace,
1890         /** */
1891         .poll_trace = stlink_usb_trace_read,
1892 };