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