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