]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/kitprog.c
522eb17bb735e35fbd6c925ce7cf5b9eff3b2363
[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_common.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 jtag_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 == NULL) {
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 == NULL) {
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 == NULL) {
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         if (kitprog_handle->packet_buffer != NULL)
231                 free(kitprog_handle->packet_buffer);
232         if (kitprog_handle->serial != NULL)
233                 free(kitprog_handle->serial);
234         if (kitprog_handle != NULL)
235                 free(kitprog_handle);
236
237         if (kitprog_serial != NULL)
238                 free(kitprog_serial);
239
240         if (pending_transfers != NULL)
241                 free(pending_transfers);
242
243         return ERROR_OK;
244 }
245
246 /*************** kitprog usb functions *********************/
247
248 static int kitprog_get_usb_serial(void)
249 {
250         int retval;
251         const uint8_t str_index = 128; /* This seems to be a constant */
252         char desc_string[256+1]; /* Max size of string descriptor */
253
254         retval = libusb_get_string_descriptor_ascii(kitprog_handle->usb_handle,
255                         str_index, (unsigned char *)desc_string, sizeof(desc_string)-1);
256         if (retval < 0) {
257                 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %d", retval);
258                 return ERROR_FAIL;
259         }
260
261         /* Null terminate descriptor string */
262         desc_string[retval] = '\0';
263
264         /* Allocate memory for the serial number */
265         kitprog_handle->serial = calloc(retval + 1, sizeof(char));
266         if (kitprog_handle->serial == NULL) {
267                 LOG_ERROR("Failed to allocate memory for the serial number");
268                 return ERROR_FAIL;
269         }
270
271         /* Store the serial number */
272         strncpy(kitprog_handle->serial, desc_string, retval + 1);
273
274         return ERROR_OK;
275 }
276
277 static int kitprog_usb_open(void)
278 {
279         const uint16_t vids[] = { VID, 0 };
280         const uint16_t pids[] = { PID, 0 };
281
282         if (jtag_libusb_open(vids, pids, kitprog_serial,
283                         &kitprog_handle->usb_handle) != ERROR_OK) {
284                 LOG_ERROR("Failed to open or find the device");
285                 return ERROR_FAIL;
286         }
287
288         /* Get the serial number for the device */
289         if (kitprog_get_usb_serial() != ERROR_OK)
290                 LOG_WARNING("Failed to get KitProg serial number");
291
292         /* Convert the ASCII serial number into a (wchar_t *) */
293         size_t len = strlen(kitprog_handle->serial);
294         wchar_t *hid_serial = calloc(len + 1, sizeof(wchar_t));
295         if (hid_serial == NULL) {
296                 LOG_ERROR("Failed to allocate memory for the serial number");
297                 return ERROR_FAIL;
298         }
299         if (mbstowcs(hid_serial, kitprog_handle->serial, len + 1) == (size_t)-1) {
300                 free(hid_serial);
301                 LOG_ERROR("Failed to convert serial number");
302                 return ERROR_FAIL;
303         }
304
305         /* Use HID for the KitBridge interface */
306         kitprog_handle->hid_handle = hid_open(VID, PID, hid_serial);
307         free(hid_serial);
308         if (kitprog_handle->hid_handle == NULL) {
309                 LOG_ERROR("Failed to open KitBridge (HID) interface");
310                 return ERROR_FAIL;
311         }
312
313         /* Claim the KitProg Programmer (bulk transfer) interface */
314         if (jtag_libusb_claim_interface(kitprog_handle->usb_handle, 1) != ERROR_OK) {
315                 LOG_ERROR("Failed to claim KitProg Programmer (bulk transfer) interface");
316                 return ERROR_FAIL;
317         }
318
319         return ERROR_OK;
320 }
321
322 static void kitprog_usb_close(void)
323 {
324         if (kitprog_handle->hid_handle != NULL) {
325                 hid_close(kitprog_handle->hid_handle);
326                 hid_exit();
327         }
328
329         jtag_libusb_close(kitprog_handle->usb_handle);
330 }
331
332 /*************** kitprog lowlevel functions *********************/
333
334 static int kitprog_hid_command(uint8_t *command, size_t command_length,
335                 uint8_t *data, size_t data_length)
336 {
337         int ret;
338
339         ret = hid_write(kitprog_handle->hid_handle, command, command_length);
340         if (ret < 0) {
341                 LOG_DEBUG("HID write returned %i", ret);
342                 return ERROR_FAIL;
343         }
344
345         ret = hid_read(kitprog_handle->hid_handle, data, data_length);
346         if (ret < 0) {
347                 LOG_DEBUG("HID read returned %i", ret);
348                 return ERROR_FAIL;
349         }
350
351         return ERROR_OK;
352 }
353
354 static int kitprog_get_version(void)
355 {
356         int ret;
357
358         unsigned char command[3] = {HID_TYPE_START | HID_TYPE_WRITE, 0x00, HID_COMMAND_VERSION};
359         unsigned char data[64];
360
361         ret = kitprog_hid_command(command, sizeof command, data, sizeof data);
362         if (ret != ERROR_OK)
363                 return ret;
364
365         kitprog_handle->hardware_version = data[1];
366         kitprog_handle->minor_version = data[2];
367         kitprog_handle->major_version = data[3];
368
369         return ERROR_OK;
370 }
371
372 static int kitprog_get_millivolts(void)
373 {
374         int ret;
375
376         unsigned char command[3] = {HID_TYPE_START | HID_TYPE_READ, 0x00, HID_COMMAND_POWER};
377         unsigned char data[64];
378
379         ret = kitprog_hid_command(command, sizeof command, data, sizeof data);
380         if (ret != ERROR_OK)
381                 return ret;
382
383         kitprog_handle->millivolts = (data[4] << 8) | data[3];
384
385         return ERROR_OK;
386 }
387
388 static int kitprog_get_info(void)
389 {
390         /* Get the device version information */
391         if (kitprog_get_version() == ERROR_OK) {
392                 LOG_INFO("KitProg v%u.%02u",
393                         kitprog_handle->major_version, kitprog_handle->minor_version);
394                 LOG_INFO("Hardware version: %u",
395                         kitprog_handle->hardware_version);
396         } else {
397                 LOG_ERROR("Failed to get KitProg version");
398                 return ERROR_FAIL;
399         }
400
401         /* Get the current reported target voltage */
402         if (kitprog_get_millivolts() == ERROR_OK) {
403                 LOG_INFO("VTARG = %u.%03u V",
404                         kitprog_handle->millivolts / 1000, kitprog_handle->millivolts % 1000);
405         } else {
406                 LOG_ERROR("Failed to get target voltage");
407                 return ERROR_FAIL;
408         }
409
410         return ERROR_OK;
411 }
412
413 static int kitprog_set_protocol(uint8_t protocol)
414 {
415         int transferred;
416         char status = PROGRAMMER_NOK_NACK;
417
418         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
419                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
420                 CONTROL_TYPE_WRITE,
421                 (CONTROL_MODE_SET_PROGRAMMER_PROTOCOL << 8) | CONTROL_COMMAND_PROGRAM,
422                 protocol, &status, 1, 0);
423
424         if (transferred == 0) {
425                 LOG_DEBUG("Zero bytes transferred");
426                 return ERROR_FAIL;
427         }
428
429         if (status != PROGRAMMER_OK_ACK) {
430                 LOG_DEBUG("Programmer did not respond OK");
431                 return ERROR_FAIL;
432         }
433
434         return ERROR_OK;
435 }
436
437 static int kitprog_get_status(void)
438 {
439         int transferred = 0;
440         char status = PROGRAMMER_NOK_NACK;
441
442         /* Try a maximum of three times */
443         for (int i = 0; (i < 3) && (transferred == 0); i++) {
444                 transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
445                         LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
446                         CONTROL_TYPE_READ,
447                         (CONTROL_MODE_POLL_PROGRAMMER_STATUS << 8) | CONTROL_COMMAND_PROGRAM,
448                         0, &status, 1, 0);
449                 jtag_sleep(1000);
450         }
451
452         if (transferred == 0) {
453                 LOG_DEBUG("Zero bytes transferred");
454                 return ERROR_FAIL;
455         }
456
457         if (status != PROGRAMMER_OK_ACK) {
458                 LOG_DEBUG("Programmer did not respond OK");
459                 return ERROR_FAIL;
460         }
461
462         return ERROR_OK;
463 }
464
465 static int kitprog_set_unknown(void)
466 {
467         int transferred;
468         char status = PROGRAMMER_NOK_NACK;
469
470         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
471                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
472                 CONTROL_TYPE_WRITE,
473                 (0x03 << 8) | 0x04,
474                 0, &status, 1, 0);
475
476         if (transferred == 0) {
477                 LOG_DEBUG("Zero bytes transferred");
478                 return ERROR_FAIL;
479         }
480
481         if (status != PROGRAMMER_OK_ACK) {
482                 LOG_DEBUG("Programmer did not respond OK");
483                 return ERROR_FAIL;
484         }
485
486         return ERROR_OK;
487 }
488
489 static int kitprog_acquire_psoc(uint8_t psoc_type, uint8_t acquire_mode,
490                 uint8_t max_attempts)
491 {
492         int transferred;
493         char status = PROGRAMMER_NOK_NACK;
494
495         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
496                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
497                 CONTROL_TYPE_WRITE,
498                 (CONTROL_MODE_ACQUIRE_SWD_TARGET << 8) | CONTROL_COMMAND_PROGRAM,
499                 (max_attempts << 8) | (acquire_mode << 4) | psoc_type, &status, 1, 0);
500
501         if (transferred == 0) {
502                 LOG_DEBUG("Zero bytes transferred");
503                 return ERROR_FAIL;
504         }
505
506         if (status != PROGRAMMER_OK_ACK) {
507                 LOG_DEBUG("Programmer did not respond OK");
508                 return ERROR_FAIL;
509         }
510
511         return ERROR_OK;
512 }
513
514 static int kitprog_reset_target(void)
515 {
516         int transferred;
517         char status = PROGRAMMER_NOK_NACK;
518
519         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
520                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
521                 CONTROL_TYPE_WRITE,
522                 (CONTROL_MODE_RESET_TARGET << 8) | CONTROL_COMMAND_PROGRAM,
523                 0, &status, 1, 0);
524
525         if (transferred == 0) {
526                 LOG_DEBUG("Zero bytes transferred");
527                 return ERROR_FAIL;
528         }
529
530         if (status != PROGRAMMER_OK_ACK) {
531                 LOG_DEBUG("Programmer did not respond OK");
532                 return ERROR_FAIL;
533         }
534
535         return ERROR_OK;
536 }
537
538 static int kitprog_swd_sync(void)
539 {
540         int transferred;
541         char status = PROGRAMMER_NOK_NACK;
542
543         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
544                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
545                 CONTROL_TYPE_WRITE,
546                 (CONTROL_MODE_SYNCHRONIZE_TRANSFER << 8) | CONTROL_COMMAND_PROGRAM,
547                 0, &status, 1, 0);
548
549         if (transferred == 0) {
550                 LOG_DEBUG("Zero bytes transferred");
551                 return ERROR_FAIL;
552         }
553
554         if (status != PROGRAMMER_OK_ACK) {
555                 LOG_DEBUG("Programmer did not respond OK");
556                 return ERROR_FAIL;
557         }
558
559         return ERROR_OK;
560 }
561
562 static int kitprog_swd_seq(uint8_t seq_type)
563 {
564         int transferred;
565         char status = PROGRAMMER_NOK_NACK;
566
567         transferred = jtag_libusb_control_transfer(kitprog_handle->usb_handle,
568                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
569                 CONTROL_TYPE_WRITE,
570                 (CONTROL_MODE_SEND_SWD_SEQUENCE << 8) | CONTROL_COMMAND_PROGRAM,
571                 seq_type, &status, 1, 0);
572
573         if (transferred == 0) {
574                 LOG_DEBUG("Zero bytes transferred");
575                 return ERROR_FAIL;
576         }
577
578         if (status != PROGRAMMER_OK_ACK) {
579                 LOG_DEBUG("Programmer did not respond OK");
580                 return ERROR_FAIL;
581         }
582
583         return ERROR_OK;
584 }
585
586 static int kitprog_generic_acquire(void)
587 {
588         const uint8_t devices[] = {DEVICE_PSOC4, DEVICE_PSOC3, DEVICE_PSOC5};
589
590         int retval;
591         int acquire_count = 0;
592
593         /* Due to the way the SWD port is shared between the Test Controller (TC)
594          * and the Cortex-M3 DAP on the PSoC 5LP, the TC is the default SWD target
595          * after power is applied. To access the DAP, the PSoC 5LP requires at least
596          * one acquisition sequence to be run (which switches the SWD mux from the
597          * TC to the DAP). However, after the mux is switched, the Cortex-M3 will be
598          * held in reset until a series of registers are written to (see section 5.2
599          * of the PSoC 5LP Device Programming Specifications for details).
600          *
601          * Instead of writing the registers in this function, we just do what the
602          * Cypress tools do and run the acquisition sequence a second time. This
603          * will take the Cortex-M3 out of reset and enable debugging.
604          */
605         for (int i = 0; i < 2; i++) {
606                 for (uint8_t j = 0; j < sizeof devices && acquire_count == i; j++) {
607                         retval = kitprog_acquire_psoc(devices[j], ACQUIRE_MODE_RESET, 3);
608                         if (retval != ERROR_OK) {
609                                 LOG_DEBUG("Aquisition function failed for device 0x%02x.", devices[j]);
610                                 return retval;
611                         }
612
613                         if (kitprog_get_status() == ERROR_OK)
614                                 acquire_count++;
615                 }
616
617                 jtag_sleep(10);
618         }
619
620         if (acquire_count < 2)
621                 return ERROR_FAIL;
622
623         return ERROR_OK;
624 }
625
626 /*************** swd wrapper functions *********************/
627
628 static int kitprog_swd_init(void)
629 {
630         return ERROR_OK;
631 }
632
633 static void kitprog_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
634 {
635         assert(!(cmd & SWD_CMD_RnW));
636         kitprog_swd_queue_cmd(cmd, NULL, value);
637 }
638
639 static void kitprog_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
640 {
641         assert(cmd & SWD_CMD_RnW);
642         kitprog_swd_queue_cmd(cmd, value, 0);
643 }
644
645 /*************** swd lowlevel functions ********************/
646
647 static int kitprog_swd_switch_seq(enum swd_special_seq seq)
648 {
649         switch (seq) {
650                 case JTAG_TO_SWD:
651                         if (kitprog_handle->supports_jtag_to_swd) {
652                                 LOG_DEBUG("JTAG to SWD");
653                                 if (kitprog_swd_seq(SEQUENCE_JTAG_TO_SWD) != ERROR_OK)
654                                         return ERROR_FAIL;
655                                 break;
656                         } else {
657                                 LOG_DEBUG("JTAG to SWD not supported");
658                                 /* Fall through to fix target reset issue */
659                         }
660                         /* fallthrough */
661                 case LINE_RESET:
662                         LOG_DEBUG("SWD line reset");
663                         if (kitprog_swd_seq(SEQUENCE_LINE_RESET) != ERROR_OK)
664                                 return ERROR_FAIL;
665                         break;
666                 default:
667                         LOG_ERROR("Sequence %d not supported.", seq);
668                         return ERROR_FAIL;
669         }
670
671         return ERROR_OK;
672 }
673
674 static int kitprog_swd_run_queue(void)
675 {
676         int ret;
677
678         size_t read_count = 0;
679         size_t read_index = 0;
680         size_t write_count = 0;
681         uint8_t *buffer = kitprog_handle->packet_buffer;
682
683         do {
684                 LOG_DEBUG_IO("Executing %d queued transactions", pending_transfer_count);
685
686                 if (queued_retval != ERROR_OK) {
687                         LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
688                         break;
689                 }
690
691                 if (!pending_transfer_count)
692                         break;
693
694                 for (int i = 0; i < pending_transfer_count; i++) {
695                         uint8_t cmd = pending_transfers[i].cmd;
696                         uint32_t data = pending_transfers[i].data;
697
698                         /* When proper WAIT handling is implemented in the
699                          * common SWD framework, this kludge can be
700                          * removed. However, this might lead to minor
701                          * performance degradation as the adapter wouldn't be
702                          * able to automatically retry anything (because ARM
703                          * has forgotten to implement sticky error flags
704                          * clearing). See also comments regarding
705                          * cmsis_dap_cmd_DAP_TFER_Configure() and
706                          * cmsis_dap_cmd_DAP_SWD_Configure() in
707                          * cmsis_dap_init().
708                          */
709                         if (!(cmd & SWD_CMD_RnW) &&
710                                 !(cmd & SWD_CMD_APnDP) &&
711                                 (cmd & SWD_CMD_A32) >> 1 == DP_CTRL_STAT &&
712                                 (data & CORUNDETECT)) {
713                                 LOG_DEBUG("refusing to enable sticky overrun detection");
714                                 data &= ~CORUNDETECT;
715                         }
716
717                         LOG_DEBUG_IO("%s %s reg %x %"PRIx32,
718                                         cmd & SWD_CMD_APnDP ? "AP" : "DP",
719                                         cmd & SWD_CMD_RnW ? "read" : "write",
720                                   (cmd & SWD_CMD_A32) >> 1, data);
721
722                         buffer[write_count++] = (cmd | SWD_CMD_START | SWD_CMD_PARK) & ~SWD_CMD_STOP;
723                         read_count++;
724                         if (!(cmd & SWD_CMD_RnW)) {
725                                 buffer[write_count++] = (data) & 0xff;
726                                 buffer[write_count++] = (data >> 8) & 0xff;
727                                 buffer[write_count++] = (data >> 16) & 0xff;
728                                 buffer[write_count++] = (data >> 24) & 0xff;
729                         } else {
730                                 read_count += 4;
731                         }
732                 }
733
734                 ret = jtag_libusb_bulk_write(kitprog_handle->usb_handle,
735                                 BULK_EP_OUT, (char *)buffer, write_count, 0);
736                 if (ret > 0) {
737                         queued_retval = ERROR_OK;
738                 } else {
739                         LOG_ERROR("Bulk write failed");
740                         queued_retval = ERROR_FAIL;
741                         break;
742                 }
743
744                 /* KitProg firmware does not send a zero length packet
745                  * after the bulk-in transmission of a length divisible by bulk packet
746                  * size (64 bytes) as required by the USB specification.
747                  * Therefore libusb would wait for continuation of transmission.
748                  * Workaround: Limit bulk read size to expected number of bytes
749                  * for problematic tranfer sizes. Otherwise use the maximum buffer
750                  * size here because the KitProg sometimes doesn't like bulk reads
751                  * of fewer than 62 bytes. (?!?!)
752                  */
753                 size_t read_count_workaround = SWD_MAX_BUFFER_LENGTH;
754                 if (read_count % 64 == 0)
755                         read_count_workaround = read_count;
756
757                 ret = jtag_libusb_bulk_read(kitprog_handle->usb_handle,
758                                 BULK_EP_IN | LIBUSB_ENDPOINT_IN, (char *)buffer,
759                                 read_count_workaround, 1000);
760                 if (ret > 0) {
761                         /* Handle garbage data by offsetting the initial read index */
762                         if ((unsigned int)ret > read_count)
763                                 read_index = ret - read_count;
764                         queued_retval = ERROR_OK;
765                 } else {
766                         LOG_ERROR("Bulk read failed");
767                         queued_retval = ERROR_FAIL;
768                         break;
769                 }
770
771                 for (int i = 0; i < pending_transfer_count; i++) {
772                         if (pending_transfers[i].cmd & SWD_CMD_RnW) {
773                                 uint32_t data = le_to_h_u32(&buffer[read_index]);
774
775                                 LOG_DEBUG_IO("Read result: %"PRIx32, data);
776
777                                 if (pending_transfers[i].buffer)
778                                         *(uint32_t *)pending_transfers[i].buffer = data;
779
780                                 read_index += 4;
781                         }
782
783                         uint8_t ack = buffer[read_index] & 0x07;
784                         if (ack != SWD_ACK_OK || (buffer[read_index] & 0x08)) {
785                                 LOG_DEBUG("SWD ack not OK: %d %s", i,
786                                           ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
787                                 queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
788                                 break;
789                         }
790                         read_index++;
791                 }
792         } while (0);
793
794         pending_transfer_count = 0;
795         int retval = queued_retval;
796         queued_retval = ERROR_OK;
797
798         return retval;
799 }
800
801 static void kitprog_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data)
802 {
803         if (pending_transfer_count == pending_queue_len) {
804                 /* Not enough room in the queue. Run the queue. */
805                 queued_retval = kitprog_swd_run_queue();
806         }
807
808         if (queued_retval != ERROR_OK)
809                 return;
810
811         pending_transfers[pending_transfer_count].data = data;
812         pending_transfers[pending_transfer_count].cmd = cmd;
813         if (cmd & SWD_CMD_RnW) {
814                 /* Queue a read transaction */
815                 pending_transfers[pending_transfer_count].buffer = dst;
816         }
817         pending_transfer_count++;
818 }
819
820 /*************** jtag lowlevel functions ********************/
821
822 static void kitprog_execute_reset(struct jtag_command *cmd)
823 {
824         int retval = ERROR_OK;
825
826         if (cmd->cmd.reset->srst == 1) {
827                 retval = kitprog_reset_target();
828                 /* Since the previous command also disables SWCLK output, we need to send an
829                  * SWD bus reset command to re-enable it. For some reason, running
830                  * kitprog_swd_seq() immediately after kitprog_reset_target() won't
831                  * actually fix this. Instead, kitprog_swd_seq() will be run once OpenOCD
832                  * tries to send a JTAG-to-SWD sequence, which should happen during
833                  * swd_check_reconnect (see the JTAG_TO_SWD case in kitprog_swd_switch_seq).
834                  */
835         }
836
837         if (retval != ERROR_OK)
838                 LOG_ERROR("KitProg: Interface reset failed");
839 }
840
841 static void kitprog_execute_sleep(struct jtag_command *cmd)
842 {
843         jtag_sleep(cmd->cmd.sleep->us);
844 }
845
846 static void kitprog_execute_command(struct jtag_command *cmd)
847 {
848         switch (cmd->type) {
849                 case JTAG_RESET:
850                         kitprog_execute_reset(cmd);
851                         break;
852                 case JTAG_SLEEP:
853                         kitprog_execute_sleep(cmd);
854                         break;
855                 default:
856                         LOG_ERROR("BUG: unknown JTAG command type encountered");
857                         exit(-1);
858         }
859 }
860
861 static int kitprog_execute_queue(void)
862 {
863         struct jtag_command *cmd = jtag_command_queue;
864
865         while (cmd != NULL) {
866                 kitprog_execute_command(cmd);
867                 cmd = cmd->next;
868         }
869
870         return ERROR_OK;
871 }
872
873 COMMAND_HANDLER(kitprog_handle_info_command)
874 {
875         int retval = kitprog_get_info();
876
877         return retval;
878 }
879
880
881 COMMAND_HANDLER(kitprog_handle_acquire_psoc_command)
882 {
883         int retval = kitprog_generic_acquire();
884
885         return retval;
886 }
887
888 COMMAND_HANDLER(kitprog_handle_serial_command)
889 {
890         if (CMD_ARGC == 1) {
891                 size_t len = strlen(CMD_ARGV[0]);
892                 kitprog_serial = calloc(len + 1, sizeof(char));
893                 if (kitprog_serial == NULL) {
894                         LOG_ERROR("Failed to allocate memory for the serial number");
895                         return ERROR_FAIL;
896                 }
897                 strncpy(kitprog_serial, CMD_ARGV[0], len + 1);
898         } else {
899                 LOG_ERROR("expected exactly one argument to kitprog_serial <serial-number>");
900                 return ERROR_FAIL;
901         }
902
903         return ERROR_OK;
904 }
905
906 COMMAND_HANDLER(kitprog_handle_init_acquire_psoc_command)
907 {
908         kitprog_init_acquire_psoc = true;
909
910         return ERROR_OK;
911 }
912
913 static const struct command_registration kitprog_subcommand_handlers[] = {
914         {
915                 .name = "info",
916                 .handler = &kitprog_handle_info_command,
917                 .mode = COMMAND_EXEC,
918                 .usage = "",
919                 .help = "show KitProg info",
920         },
921         {
922                 .name = "acquire_psoc",
923                 .handler = &kitprog_handle_acquire_psoc_command,
924                 .mode = COMMAND_EXEC,
925                 .usage = "",
926                 .help = "try to acquire a PSoC",
927         },
928         COMMAND_REGISTRATION_DONE
929 };
930
931 static const struct command_registration kitprog_command_handlers[] = {
932         {
933                 .name = "kitprog",
934                 .mode = COMMAND_ANY,
935                 .help = "perform KitProg management",
936                 .usage = "<cmd>",
937                 .chain = kitprog_subcommand_handlers,
938         },
939         {
940                 .name = "kitprog_serial",
941                 .handler = &kitprog_handle_serial_command,
942                 .mode = COMMAND_CONFIG,
943                 .help = "set the serial number of the adapter",
944                 .usage = "serial_string",
945         },
946         {
947                 .name = "kitprog_init_acquire_psoc",
948                 .handler = &kitprog_handle_init_acquire_psoc_command,
949                 .mode = COMMAND_CONFIG,
950                 .help = "try to acquire a PSoC during init",
951                 .usage = "",
952         },
953         COMMAND_REGISTRATION_DONE
954 };
955
956 static const struct swd_driver kitprog_swd = {
957         .init = kitprog_swd_init,
958         .switch_seq = kitprog_swd_switch_seq,
959         .read_reg = kitprog_swd_read_reg,
960         .write_reg = kitprog_swd_write_reg,
961         .run = kitprog_swd_run_queue,
962 };
963
964 static const char * const kitprog_transports[] = { "swd", NULL };
965
966 struct jtag_interface kitprog_interface = {
967         .name = "kitprog",
968         .commands = kitprog_command_handlers,
969         .transports = kitprog_transports,
970         .swd = &kitprog_swd,
971         .execute_queue = kitprog_execute_queue,
972         .init = kitprog_init,
973         .quit = kitprog_quit
974 };