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