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