jtag/drivers/kitprog: use HID read timeout
[fw/openocd] / src / jtag / drivers / kitprog.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 /***************************************************************************
4  *   Copyright (C) 2007 by Juergen Stuber <juergen@jstuber.net>            *
5  *   based on Dominic Rath's and Benedikt Sauter's usbprog.c               *
6  *                                                                         *
7  *   Copyright (C) 2008 by Spencer Oliver                                  *
8  *   spen@spen-soft.co.uk                                                  *
9  *                                                                         *
10  *   Copyright (C) 2011 by Jean-Christophe PLAGNIOL-VIILARD                *
11  *   plagnioj@jcrosoft.com                                                 *
12  *                                                                         *
13  *   Copyright (C) 2015 by Marc Schink                                     *
14  *   openocd-dev@marcschink.de                                             *
15  *                                                                         *
16  *   Copyright (C) 2015 by Paul Fertser                                    *
17  *   fercerpav@gmail.com                                                   *
18  *                                                                         *
19  *   Copyright (C) 2015-2017 by Forest Crossman                            *
20  *   cyrozap@gmail.com                                                     *
21  ***************************************************************************/
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <stdint.h>
28
29 #include <hidapi.h>
30
31 #include <jtag/interface.h>
32 #include <jtag/swd.h>
33 #include <jtag/commands.h>
34
35 #include "libusb_helper.h"
36
37 #define VID 0x04b4
38 #define PID 0xf139
39
40 #define BULK_EP_IN  1
41 #define BULK_EP_OUT 2
42
43 #define CONTROL_TYPE_READ  0x01
44 #define CONTROL_TYPE_WRITE 0x02
45
46 #define CONTROL_COMMAND_PROGRAM 0x07
47
48 #define CONTROL_MODE_POLL_PROGRAMMER_STATUS  0x01
49 #define CONTROL_MODE_RESET_TARGET            0x04
50 #define CONTROL_MODE_SET_PROGRAMMER_PROTOCOL 0x40
51 #define CONTROL_MODE_SYNCHRONIZE_TRANSFER    0x41
52 #define CONTROL_MODE_ACQUIRE_SWD_TARGET      0x42
53 #define CONTROL_MODE_SEND_SWD_SEQUENCE       0x43
54
55 #define PROTOCOL_JTAG 0x00
56 #define PROTOCOL_SWD  0x01
57
58 #define DEVICE_PSOC4   0x00
59 #define DEVICE_PSOC3   0x01
60 #define DEVICE_UNKNOWN 0x02
61 #define DEVICE_PSOC5   0x03
62
63 #define ACQUIRE_MODE_RESET       0x00
64 #define ACQUIRE_MODE_POWER_CYCLE 0x01
65
66 #define SEQUENCE_LINE_RESET  0x00
67 #define SEQUENCE_JTAG_TO_SWD 0x01
68
69 #define PROGRAMMER_NOK_NACK 0x00
70 #define PROGRAMMER_OK_ACK   0x01
71
72 #define HID_TYPE_WRITE 0x00
73 #define HID_TYPE_READ  0x01
74 #define HID_TYPE_START 0x02
75
76 #define HID_COMMAND_POWER      0x80
77 #define HID_COMMAND_VERSION    0x81
78 #define HID_COMMAND_RESET      0x82
79 #define HID_COMMAND_CONFIGURE  0x8f
80 #define HID_COMMAND_BOOTLOADER 0xa0
81
82 /* 512 bytes seems to work reliably */
83 #define SWD_MAX_BUFFER_LENGTH 512
84
85 struct kitprog {
86         hid_device *hid_handle;
87         struct libusb_device_handle *usb_handle;
88         uint16_t packet_size;
89         uint16_t packet_index;
90         uint8_t *packet_buffer;
91         char *serial;
92         uint8_t hardware_version;
93         uint8_t minor_version;
94         uint8_t major_version;
95         uint16_t millivolts;
96
97         bool supports_jtag_to_swd;
98 };
99
100 struct pending_transfer_result {
101         uint8_t cmd;
102         uint32_t data;
103         void *buffer;
104 };
105
106 static bool kitprog_init_acquire_psoc;
107
108 static int pending_transfer_count, pending_queue_len;
109 static struct pending_transfer_result *pending_transfers;
110
111 static int queued_retval;
112
113 static struct kitprog *kitprog_handle;
114
115 static int kitprog_usb_open(void);
116 static void kitprog_usb_close(void);
117
118 static int kitprog_hid_command(uint8_t *command, size_t command_length,
119                 uint8_t *data, size_t data_length);
120 static int kitprog_get_version(void);
121 static int kitprog_get_millivolts(void);
122 static int kitprog_get_info(void);
123 static int kitprog_set_protocol(uint8_t protocol);
124 static int kitprog_get_status(void);
125 static int kitprog_set_unknown(void);
126 static int kitprog_acquire_psoc(uint8_t psoc_type, uint8_t acquire_mode,
127                 uint8_t max_attempts);
128 static int kitprog_reset_target(void);
129 static int kitprog_swd_sync(void);
130 static int kitprog_swd_seq(uint8_t seq_type);
131
132 static int kitprog_generic_acquire(void);
133
134 static int kitprog_swd_run_queue(void);
135 static void kitprog_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data);
136 static int kitprog_swd_switch_seq(enum swd_special_seq seq);
137
138
139 static inline int mm_to_version(uint8_t major, uint8_t minor)
140 {
141         return (major << 8) | minor;
142 }
143
144 static int kitprog_init(void)
145 {
146         int retval;
147
148         kitprog_handle = malloc(sizeof(struct kitprog));
149         if (!kitprog_handle) {
150                 LOG_ERROR("Failed to allocate memory");
151                 return ERROR_FAIL;
152         }
153
154         if (kitprog_usb_open() != ERROR_OK) {
155                 LOG_ERROR("Can't find a KitProg device! Please check device connections and permissions.");
156                 return ERROR_JTAG_INIT_FAILED;
157         }
158
159         /* Get the current KitProg version and target voltage */
160         if (kitprog_get_info() != ERROR_OK)
161                 return ERROR_FAIL;
162
163         /* Compatibility check */
164         kitprog_handle->supports_jtag_to_swd = true;
165         int kitprog_version = mm_to_version(kitprog_handle->major_version, kitprog_handle->minor_version);
166         if (kitprog_version < mm_to_version(2, 14)) {
167                 LOG_WARNING("KitProg firmware versions below v2.14 do not support sending JTAG to SWD sequences. These sequences will be substituted with SWD line resets.");
168                 kitprog_handle->supports_jtag_to_swd = false;
169         }
170
171         /* I have no idea what this does */
172         if (kitprog_set_unknown() != ERROR_OK)
173                 return ERROR_FAIL;
174
175         /* SWD won't work unless we do this */
176         if (kitprog_swd_sync() != ERROR_OK)
177                 return ERROR_FAIL;
178
179         /* Set the protocol to SWD */
180         if (kitprog_set_protocol(PROTOCOL_SWD) != ERROR_OK)
181                 return ERROR_FAIL;
182
183         /* Reset the SWD bus */
184         if (kitprog_swd_seq(SEQUENCE_LINE_RESET) != ERROR_OK)
185                 return ERROR_FAIL;
186
187         if (kitprog_init_acquire_psoc) {
188                 /* Try to acquire any device that will respond */
189                 retval = kitprog_generic_acquire();
190                 if (retval != ERROR_OK) {
191                         LOG_ERROR("No PSoC devices found");
192                         return retval;
193                 }
194         }
195
196         /* Allocate packet buffers and queues */
197         kitprog_handle->packet_size = SWD_MAX_BUFFER_LENGTH;
198         kitprog_handle->packet_buffer = malloc(SWD_MAX_BUFFER_LENGTH);
199         if (!kitprog_handle->packet_buffer) {
200                 LOG_ERROR("Failed to allocate memory for the packet buffer");
201                 return ERROR_FAIL;
202         }
203
204         pending_queue_len = SWD_MAX_BUFFER_LENGTH / 5;
205         pending_transfers = malloc(pending_queue_len * sizeof(*pending_transfers));
206         if (!pending_transfers) {
207                 LOG_ERROR("Failed to allocate memory for the SWD transfer queue");
208                 return ERROR_FAIL;
209         }
210
211         return ERROR_OK;
212 }
213
214 static int kitprog_quit(void)
215 {
216         kitprog_usb_close();
217
218         free(kitprog_handle->packet_buffer);
219         free(kitprog_handle->serial);
220         free(kitprog_handle);
221         free(pending_transfers);
222
223         return ERROR_OK;
224 }
225
226 /*************** kitprog usb functions *********************/
227
228 static int kitprog_get_usb_serial(void)
229 {
230         int retval;
231         const uint8_t str_index = 128; /* This seems to be a constant */
232         char desc_string[256+1]; /* Max size of string descriptor */
233
234         retval = libusb_get_string_descriptor_ascii(kitprog_handle->usb_handle,
235                         str_index, (unsigned char *)desc_string, sizeof(desc_string)-1);
236         if (retval < 0) {
237                 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %d", retval);
238                 return ERROR_FAIL;
239         }
240
241         /* Null terminate descriptor string */
242         desc_string[retval] = '\0';
243
244         /* Allocate memory for the serial number */
245         kitprog_handle->serial = calloc(retval + 1, sizeof(char));
246         if (!kitprog_handle->serial) {
247                 LOG_ERROR("Failed to allocate memory for the serial number");
248                 return ERROR_FAIL;
249         }
250
251         /* Store the serial number */
252         strncpy(kitprog_handle->serial, desc_string, retval + 1);
253
254         return ERROR_OK;
255 }
256
257 static int kitprog_usb_open(void)
258 {
259         const uint16_t vids[] = { VID, 0 };
260         const uint16_t pids[] = { PID, 0 };
261
262         if (jtag_libusb_open(vids, pids, &kitprog_handle->usb_handle, NULL) != ERROR_OK) {
263                 LOG_ERROR("Failed to open or find the device");
264                 return ERROR_FAIL;
265         }
266
267         /* Get the serial number for the device */
268         if (kitprog_get_usb_serial() != ERROR_OK)
269                 LOG_WARNING("Failed to get KitProg serial number");
270
271         /* Convert the ASCII serial number into a (wchar_t *) */
272         size_t len = strlen(kitprog_handle->serial);
273         wchar_t *hid_serial = calloc(len + 1, sizeof(wchar_t));
274         if (!hid_serial) {
275                 LOG_ERROR("Failed to allocate memory for the serial number");
276                 return ERROR_FAIL;
277         }
278         if (mbstowcs(hid_serial, kitprog_handle->serial, len + 1) == (size_t)-1) {
279                 free(hid_serial);
280                 LOG_ERROR("Failed to convert serial number");
281                 return ERROR_FAIL;
282         }
283
284         /* Use HID for the KitBridge interface */
285         kitprog_handle->hid_handle = hid_open(VID, PID, hid_serial);
286         free(hid_serial);
287         if (!kitprog_handle->hid_handle) {
288                 LOG_ERROR("Failed to open KitBridge (HID) interface");
289                 return ERROR_FAIL;
290         }
291
292         /* Claim the KitProg Programmer (bulk transfer) interface */
293         if (libusb_claim_interface(kitprog_handle->usb_handle, 1) != ERROR_OK) {
294                 LOG_ERROR("Failed to claim KitProg Programmer (bulk transfer) interface");
295                 return ERROR_FAIL;
296         }
297
298         return ERROR_OK;
299 }
300
301 static void kitprog_usb_close(void)
302 {
303         if (kitprog_handle->hid_handle) {
304                 hid_close(kitprog_handle->hid_handle);
305                 hid_exit();
306         }
307
308         jtag_libusb_close(kitprog_handle->usb_handle);
309 }
310
311 /*************** kitprog lowlevel functions *********************/
312
313 static int kitprog_hid_command(uint8_t *command, size_t command_length,
314                 uint8_t *data, size_t data_length)
315 {
316         int ret;
317
318         ret = hid_write(kitprog_handle->hid_handle, command, command_length);
319         if (ret < 0) {
320                 LOG_DEBUG("HID write returned %i", ret);
321                 return ERROR_FAIL;
322         }
323
324         ret = hid_read_timeout(kitprog_handle->hid_handle,
325                                                         data, data_length, LIBUSB_TIMEOUT_MS);
326         if (ret == 0) {
327                 LOG_ERROR("HID read timed out");
328                 return ERROR_TIMEOUT_REACHED;
329         } else if (ret < 0) {
330                 LOG_ERROR("HID read error %ls", hid_error(kitprog_handle->hid_handle));
331                 return ERROR_FAIL;
332         }
333
334         return ERROR_OK;
335 }
336
337 static int kitprog_get_version(void)
338 {
339         int ret;
340
341         unsigned char command[3] = {HID_TYPE_START | HID_TYPE_WRITE, 0x00, HID_COMMAND_VERSION};
342         unsigned char data[64];
343
344         ret = kitprog_hid_command(command, sizeof(command), data, sizeof(data));
345         if (ret != ERROR_OK)
346                 return ret;
347
348         kitprog_handle->hardware_version = data[1];
349         kitprog_handle->minor_version = data[2];
350         kitprog_handle->major_version = data[3];
351
352         return ERROR_OK;
353 }
354
355 static int kitprog_get_millivolts(void)
356 {
357         int ret;
358
359         unsigned char command[3] = {HID_TYPE_START | HID_TYPE_READ, 0x00, HID_COMMAND_POWER};
360         unsigned char data[64];
361
362         ret = kitprog_hid_command(command, sizeof(command), data, sizeof(data));
363         if (ret != ERROR_OK)
364                 return ret;
365
366         kitprog_handle->millivolts = (data[4] << 8) | data[3];
367
368         return ERROR_OK;
369 }
370
371 static int kitprog_get_info(void)
372 {
373         /* Get the device version information */
374         if (kitprog_get_version() == ERROR_OK) {
375                 LOG_INFO("KitProg v%u.%02u",
376                         kitprog_handle->major_version, kitprog_handle->minor_version);
377                 LOG_INFO("Hardware version: %u",
378                         kitprog_handle->hardware_version);
379         } else {
380                 LOG_ERROR("Failed to get KitProg version");
381                 return ERROR_FAIL;
382         }
383
384         /* Get the current reported target voltage */
385         if (kitprog_get_millivolts() == ERROR_OK) {
386                 LOG_INFO("VTARG = %u.%03u V",
387                         kitprog_handle->millivolts / 1000, kitprog_handle->millivolts % 1000);
388         } else {
389                 LOG_ERROR("Failed to get target voltage");
390                 return ERROR_FAIL;
391         }
392
393         return ERROR_OK;
394 }
395
396 static int kitprog_set_protocol(uint8_t protocol)
397 {
398         int transferred;
399         char status = PROGRAMMER_NOK_NACK;
400
401         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
402                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
403                 CONTROL_TYPE_WRITE,
404                 (CONTROL_MODE_SET_PROGRAMMER_PROTOCOL << 8) | CONTROL_COMMAND_PROGRAM,
405                 protocol, &status, 1, 0);
406
407         if (transferred == 0) {
408                 LOG_DEBUG("Zero bytes transferred");
409                 return ERROR_FAIL;
410         }
411
412         if (status != PROGRAMMER_OK_ACK) {
413                 LOG_DEBUG("Programmer did not respond OK");
414                 return ERROR_FAIL;
415         }
416
417         return ERROR_OK;
418 }
419
420 static int kitprog_get_status(void)
421 {
422         int transferred = 0;
423         char status = PROGRAMMER_NOK_NACK;
424
425         /* Try a maximum of three times */
426         for (int i = 0; (i < 3) && (transferred == 0); i++) {
427                 transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
428                         LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
429                         CONTROL_TYPE_READ,
430                         (CONTROL_MODE_POLL_PROGRAMMER_STATUS << 8) | CONTROL_COMMAND_PROGRAM,
431                         0, &status, 1, 0);
432                 jtag_sleep(1000);
433         }
434
435         if (transferred == 0) {
436                 LOG_DEBUG("Zero bytes transferred");
437                 return ERROR_FAIL;
438         }
439
440         if (status != PROGRAMMER_OK_ACK) {
441                 LOG_DEBUG("Programmer did not respond OK");
442                 return ERROR_FAIL;
443         }
444
445         return ERROR_OK;
446 }
447
448 static int kitprog_set_unknown(void)
449 {
450         int transferred;
451         char status = PROGRAMMER_NOK_NACK;
452
453         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
454                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
455                 CONTROL_TYPE_WRITE,
456                 (0x03 << 8) | 0x04,
457                 0, &status, 1, 0);
458
459         if (transferred == 0) {
460                 LOG_DEBUG("Zero bytes transferred");
461                 return ERROR_FAIL;
462         }
463
464         if (status != PROGRAMMER_OK_ACK) {
465                 LOG_DEBUG("Programmer did not respond OK");
466                 return ERROR_FAIL;
467         }
468
469         return ERROR_OK;
470 }
471
472 static int kitprog_acquire_psoc(uint8_t psoc_type, uint8_t acquire_mode,
473                 uint8_t max_attempts)
474 {
475         int transferred;
476         char status = PROGRAMMER_NOK_NACK;
477
478         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
479                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
480                 CONTROL_TYPE_WRITE,
481                 (CONTROL_MODE_ACQUIRE_SWD_TARGET << 8) | CONTROL_COMMAND_PROGRAM,
482                 (max_attempts << 8) | (acquire_mode << 4) | psoc_type, &status, 1, 0);
483
484         if (transferred == 0) {
485                 LOG_DEBUG("Zero bytes transferred");
486                 return ERROR_FAIL;
487         }
488
489         if (status != PROGRAMMER_OK_ACK) {
490                 LOG_DEBUG("Programmer did not respond OK");
491                 return ERROR_FAIL;
492         }
493
494         return ERROR_OK;
495 }
496
497 static int kitprog_reset_target(void)
498 {
499         int transferred;
500         char status = PROGRAMMER_NOK_NACK;
501
502         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
503                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
504                 CONTROL_TYPE_WRITE,
505                 (CONTROL_MODE_RESET_TARGET << 8) | CONTROL_COMMAND_PROGRAM,
506                 0, &status, 1, 0);
507
508         if (transferred == 0) {
509                 LOG_DEBUG("Zero bytes transferred");
510                 return ERROR_FAIL;
511         }
512
513         if (status != PROGRAMMER_OK_ACK) {
514                 LOG_DEBUG("Programmer did not respond OK");
515                 return ERROR_FAIL;
516         }
517
518         return ERROR_OK;
519 }
520
521 static int kitprog_swd_sync(void)
522 {
523         int transferred;
524         char status = PROGRAMMER_NOK_NACK;
525
526         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
527                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
528                 CONTROL_TYPE_WRITE,
529                 (CONTROL_MODE_SYNCHRONIZE_TRANSFER << 8) | CONTROL_COMMAND_PROGRAM,
530                 0, &status, 1, 0);
531
532         if (transferred == 0) {
533                 LOG_DEBUG("Zero bytes transferred");
534                 return ERROR_FAIL;
535         }
536
537         if (status != PROGRAMMER_OK_ACK) {
538                 LOG_DEBUG("Programmer did not respond OK");
539                 return ERROR_FAIL;
540         }
541
542         return ERROR_OK;
543 }
544
545 static int kitprog_swd_seq(uint8_t seq_type)
546 {
547         int transferred;
548         char status = PROGRAMMER_NOK_NACK;
549
550         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
551                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
552                 CONTROL_TYPE_WRITE,
553                 (CONTROL_MODE_SEND_SWD_SEQUENCE << 8) | CONTROL_COMMAND_PROGRAM,
554                 seq_type, &status, 1, 0);
555
556         if (transferred == 0) {
557                 LOG_DEBUG("Zero bytes transferred");
558                 return ERROR_FAIL;
559         }
560
561         if (status != PROGRAMMER_OK_ACK) {
562                 LOG_DEBUG("Programmer did not respond OK");
563                 return ERROR_FAIL;
564         }
565
566         return ERROR_OK;
567 }
568
569 static int kitprog_generic_acquire(void)
570 {
571         const uint8_t devices[] = {DEVICE_PSOC4, DEVICE_PSOC3, DEVICE_PSOC5};
572
573         int retval;
574         int acquire_count = 0;
575
576         /* Due to the way the SWD port is shared between the Test Controller (TC)
577          * and the Cortex-M3 DAP on the PSoC 5LP, the TC is the default SWD target
578          * after power is applied. To access the DAP, the PSoC 5LP requires at least
579          * one acquisition sequence to be run (which switches the SWD mux from the
580          * TC to the DAP). However, after the mux is switched, the Cortex-M3 will be
581          * held in reset until a series of registers are written to (see section 5.2
582          * of the PSoC 5LP Device Programming Specifications for details).
583          *
584          * Instead of writing the registers in this function, we just do what the
585          * Cypress tools do and run the acquisition sequence a second time. This
586          * will take the Cortex-M3 out of reset and enable debugging.
587          */
588         for (int i = 0; i < 2; i++) {
589                 for (uint8_t j = 0; j < sizeof(devices) && acquire_count == i; j++) {
590                         retval = kitprog_acquire_psoc(devices[j], ACQUIRE_MODE_RESET, 3);
591                         if (retval != ERROR_OK) {
592                                 LOG_DEBUG("Acquisition function failed for device 0x%02x.", devices[j]);
593                                 return retval;
594                         }
595
596                         if (kitprog_get_status() == ERROR_OK)
597                                 acquire_count++;
598                 }
599
600                 jtag_sleep(10);
601         }
602
603         if (acquire_count < 2)
604                 return ERROR_FAIL;
605
606         return ERROR_OK;
607 }
608
609 /*************** swd wrapper functions *********************/
610
611 static int kitprog_swd_init(void)
612 {
613         return ERROR_OK;
614 }
615
616 static void kitprog_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
617 {
618         assert(!(cmd & SWD_CMD_RNW));
619         kitprog_swd_queue_cmd(cmd, NULL, value);
620 }
621
622 static void kitprog_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
623 {
624         assert(cmd & SWD_CMD_RNW);
625         kitprog_swd_queue_cmd(cmd, value, 0);
626 }
627
628 /*************** swd lowlevel functions ********************/
629
630 static int kitprog_swd_switch_seq(enum swd_special_seq seq)
631 {
632         switch (seq) {
633                 case JTAG_TO_SWD:
634                         if (kitprog_handle->supports_jtag_to_swd) {
635                                 LOG_DEBUG("JTAG to SWD");
636                                 if (kitprog_swd_seq(SEQUENCE_JTAG_TO_SWD) != ERROR_OK)
637                                         return ERROR_FAIL;
638                                 break;
639                         } else {
640                                 LOG_DEBUG("JTAG to SWD not supported");
641                                 /* Fall through to fix target reset issue */
642                         }
643                         /* fallthrough */
644                 case LINE_RESET:
645                         LOG_DEBUG("SWD line reset");
646                         if (kitprog_swd_seq(SEQUENCE_LINE_RESET) != ERROR_OK)
647                                 return ERROR_FAIL;
648                         break;
649                 default:
650                         LOG_ERROR("Sequence %d not supported.", seq);
651                         return ERROR_FAIL;
652         }
653
654         return ERROR_OK;
655 }
656
657 static int kitprog_swd_run_queue(void)
658 {
659         int ret;
660
661         size_t read_count = 0;
662         size_t read_index = 0;
663         size_t write_count = 0;
664         uint8_t *buffer = kitprog_handle->packet_buffer;
665
666         do {
667                 LOG_DEBUG_IO("Executing %d queued transactions", pending_transfer_count);
668
669                 if (queued_retval != ERROR_OK) {
670                         LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
671                         break;
672                 }
673
674                 if (!pending_transfer_count)
675                         break;
676
677                 for (int i = 0; i < pending_transfer_count; i++) {
678                         uint8_t cmd = pending_transfers[i].cmd;
679                         uint32_t data = pending_transfers[i].data;
680
681                         /* When proper WAIT handling is implemented in the
682                          * common SWD framework, this kludge can be
683                          * removed. However, this might lead to minor
684                          * performance degradation as the adapter wouldn't be
685                          * able to automatically retry anything (because ARM
686                          * has forgotten to implement sticky error flags
687                          * clearing). See also comments regarding
688                          * cmsis_dap_cmd_DAP_TFER_Configure() and
689                          * cmsis_dap_cmd_DAP_SWD_Configure() in
690                          * cmsis_dap_init().
691                          */
692                         if (!(cmd & SWD_CMD_RNW) &&
693                                 !(cmd & SWD_CMD_APNDP) &&
694                                 (cmd & SWD_CMD_A32) >> 1 == DP_CTRL_STAT &&
695                                 (data & CORUNDETECT)) {
696                                 LOG_DEBUG("refusing to enable sticky overrun detection");
697                                 data &= ~CORUNDETECT;
698                         }
699
700                         LOG_DEBUG_IO("%s %s reg %x %"PRIx32,
701                                         cmd & SWD_CMD_APNDP ? "AP" : "DP",
702                                         cmd & SWD_CMD_RNW ? "read" : "write",
703                                   (cmd & SWD_CMD_A32) >> 1, data);
704
705                         buffer[write_count++] = (cmd | SWD_CMD_START | SWD_CMD_PARK) & ~SWD_CMD_STOP;
706                         read_count++;
707                         if (!(cmd & SWD_CMD_RNW)) {
708                                 buffer[write_count++] = (data) & 0xff;
709                                 buffer[write_count++] = (data >> 8) & 0xff;
710                                 buffer[write_count++] = (data >> 16) & 0xff;
711                                 buffer[write_count++] = (data >> 24) & 0xff;
712                         } else {
713                                 read_count += 4;
714                         }
715                 }
716
717                 if (jtag_libusb_bulk_write(kitprog_handle->usb_handle,
718                                            BULK_EP_OUT, (char *)buffer,
719                                            write_count, 0, &ret)) {
720                         LOG_ERROR("Bulk write failed");
721                         queued_retval = ERROR_FAIL;
722                         break;
723                 } else {
724                         queued_retval = ERROR_OK;
725                 }
726
727                 /* KitProg firmware does not send a zero length packet
728                  * after the bulk-in transmission of a length divisible by bulk packet
729                  * size (64 bytes) as required by the USB specification.
730                  * Therefore libusb would wait for continuation of transmission.
731                  * Workaround: Limit bulk read size to expected number of bytes
732                  * for problematic transfer sizes. Otherwise use the maximum buffer
733                  * size here because the KitProg sometimes doesn't like bulk reads
734                  * of fewer than 62 bytes. (?!?!)
735                  */
736                 size_t read_count_workaround = SWD_MAX_BUFFER_LENGTH;
737                 if (read_count % 64 == 0)
738                         read_count_workaround = read_count;
739
740                 if (jtag_libusb_bulk_read(kitprog_handle->usb_handle,
741                                 BULK_EP_IN | LIBUSB_ENDPOINT_IN, (char *)buffer,
742                                 read_count_workaround, 1000, &ret)) {
743                         LOG_ERROR("Bulk read failed");
744                         queued_retval = ERROR_FAIL;
745                         break;
746                 } else {
747                         /* Handle garbage data by offsetting the initial read index */
748                         if ((unsigned int)ret > read_count)
749                                 read_index = ret - read_count;
750                         queued_retval = ERROR_OK;
751                 }
752
753                 for (int i = 0; i < pending_transfer_count; i++) {
754                         if (pending_transfers[i].cmd & SWD_CMD_RNW) {
755                                 uint32_t data = le_to_h_u32(&buffer[read_index]);
756
757                                 LOG_DEBUG_IO("Read result: %"PRIx32, data);
758
759                                 if (pending_transfers[i].buffer)
760                                         *(uint32_t *)pending_transfers[i].buffer = data;
761
762                                 read_index += 4;
763                         }
764
765                         uint8_t ack = buffer[read_index] & 0x07;
766                         if (ack != SWD_ACK_OK || (buffer[read_index] & 0x08)) {
767                                 LOG_DEBUG("SWD ack not OK: %d %s", i,
768                                           ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
769                                 queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
770                                 break;
771                         }
772                         read_index++;
773                 }
774         } while (0);
775
776         pending_transfer_count = 0;
777         int retval = queued_retval;
778         queued_retval = ERROR_OK;
779
780         return retval;
781 }
782
783 static void kitprog_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data)
784 {
785         if (pending_transfer_count == pending_queue_len) {
786                 /* Not enough room in the queue. Run the queue. */
787                 queued_retval = kitprog_swd_run_queue();
788         }
789
790         if (queued_retval != ERROR_OK)
791                 return;
792
793         pending_transfers[pending_transfer_count].data = data;
794         pending_transfers[pending_transfer_count].cmd = cmd;
795         if (cmd & SWD_CMD_RNW) {
796                 /* Queue a read transaction */
797                 pending_transfers[pending_transfer_count].buffer = dst;
798         }
799         pending_transfer_count++;
800 }
801
802 /*************** jtag lowlevel functions ********************/
803
804 static int kitprog_reset(int trst, int srst)
805 {
806         int retval = ERROR_OK;
807
808         if (trst == 1) {
809                 LOG_ERROR("KitProg: Interface has no TRST");
810                 return ERROR_FAIL;
811         }
812
813         if (srst == 1) {
814                 retval = kitprog_reset_target();
815                 /* Since the previous command also disables SWCLK output, we need to send an
816                  * SWD bus reset command to re-enable it. For some reason, running
817                  * kitprog_swd_seq() immediately after kitprog_reset_target() won't
818                  * actually fix this. Instead, kitprog_swd_seq() will be run once OpenOCD
819                  * tries to send a JTAG-to-SWD sequence, which should happen during
820                  * swd_check_reconnect (see the JTAG_TO_SWD case in kitprog_swd_switch_seq).
821                  */
822         }
823
824         if (retval != ERROR_OK)
825                 LOG_ERROR("KitProg: Interface reset failed");
826         return retval;
827 }
828
829 COMMAND_HANDLER(kitprog_handle_info_command)
830 {
831         int retval = kitprog_get_info();
832
833         return retval;
834 }
835
836
837 COMMAND_HANDLER(kitprog_handle_acquire_psoc_command)
838 {
839         int retval = kitprog_generic_acquire();
840
841         return retval;
842 }
843
844 COMMAND_HANDLER(kitprog_handle_init_acquire_psoc_command)
845 {
846         kitprog_init_acquire_psoc = true;
847
848         return ERROR_OK;
849 }
850
851 static const struct command_registration kitprog_subcommand_handlers[] = {
852         {
853                 .name = "info",
854                 .handler = &kitprog_handle_info_command,
855                 .mode = COMMAND_EXEC,
856                 .usage = "",
857                 .help = "show KitProg info",
858         },
859         {
860                 .name = "acquire_psoc",
861                 .handler = &kitprog_handle_acquire_psoc_command,
862                 .mode = COMMAND_EXEC,
863                 .usage = "",
864                 .help = "try to acquire a PSoC",
865         },
866         COMMAND_REGISTRATION_DONE
867 };
868
869 static const struct command_registration kitprog_command_handlers[] = {
870         {
871                 .name = "kitprog",
872                 .mode = COMMAND_ANY,
873                 .help = "perform KitProg management",
874                 .usage = "<cmd>",
875                 .chain = kitprog_subcommand_handlers,
876         },
877         {
878                 .name = "kitprog_init_acquire_psoc",
879                 .handler = &kitprog_handle_init_acquire_psoc_command,
880                 .mode = COMMAND_CONFIG,
881                 .help = "try to acquire a PSoC during init",
882                 .usage = "",
883         },
884         COMMAND_REGISTRATION_DONE
885 };
886
887 static const struct swd_driver kitprog_swd = {
888         .init = kitprog_swd_init,
889         .switch_seq = kitprog_swd_switch_seq,
890         .read_reg = kitprog_swd_read_reg,
891         .write_reg = kitprog_swd_write_reg,
892         .run = kitprog_swd_run_queue,
893 };
894
895 static const char * const kitprog_transports[] = { "swd", NULL };
896
897 struct adapter_driver kitprog_adapter_driver = {
898         .name = "kitprog",
899         .transports = kitprog_transports,
900         .commands = kitprog_command_handlers,
901
902         .init = kitprog_init,
903         .quit = kitprog_quit,
904         .reset = kitprog_reset,
905
906         .swd_ops = &kitprog_swd,
907 };