rlink: fix indentation errors
[fw/openocd] / src / jtag / drivers / rlink.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007,2008 Ã˜yvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2008 Rob Brown, Lou Deluxe                              *
9  *   rob@cobbleware.com, lou.openocd012@fixit.nospammail.net               *
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program; if not, write to the                         *
23  *   Free Software Foundation, Inc.,                                       *
24  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
25  ***************************************************************************/
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 /* project specific includes */
31 #include <jtag/interface.h>
32 #include <jtag/commands.h>
33 #include "rlink.h"
34 #include "rlink_st7.h"
35 #include "rlink_ep1_cmd.h"
36 #include "rlink_dtc_cmd.h"
37 #include "usb_common.h"
38
39
40 /* This feature is made useless by running the DTC all the time.  When automatic, the LED is on whenever the DTC is running.  Otherwise, USB messages are sent to turn it on and off. */
41 #undef AUTOMATIC_BUSY_LED
42
43 /* This feature may require derating the speed due to reduced hold time. */
44 #undef USE_HARDWARE_SHIFTER_FOR_TMS
45
46
47 #define INTERFACE_NAME          "RLink"
48
49 #define USB_IDVENDOR            (0x138e)
50 #define USB_IDPRODUCT           (0x9000)
51
52 #define USB_EP1OUT_ADDR         (0x01)
53 #define USB_EP1OUT_SIZE         (16)
54 #define USB_EP1IN_ADDR          (USB_EP1OUT_ADDR | 0x80)
55 #define USB_EP1IN_SIZE          (USB_EP1OUT_SIZE)
56
57 #define USB_EP2OUT_ADDR         (0x02)
58 #define USB_EP2OUT_SIZE         (64)
59 #define USB_EP2IN_ADDR          (USB_EP2OUT_ADDR | 0x80)
60 #define USB_EP2IN_SIZE          (USB_EP2OUT_SIZE)
61 #define USB_EP2BANK_SIZE        (512)
62
63 #define USB_TIMEOUT_MS          (3 * 1000)
64
65 #define DTC_STATUS_POLL_BYTE    (ST7_USB_BUF_EP0OUT + 0xff)
66
67
68 #define ST7_PD_NBUSY_LED                ST7_PD0
69 #define ST7_PD_NRUN_LED                 ST7_PD1
70 /* low enables VPP at adapter header, high connects it to GND instead */
71 #define ST7_PD_VPP_SEL                  ST7_PD6
72 /* low: VPP = 12v, high: VPP <= 5v */
73 #define ST7_PD_VPP_SHDN                 ST7_PD7
74
75 /* These pins are connected together */
76 #define ST7_PE_ADAPTER_SENSE_IN         ST7_PE3
77 #define ST7_PE_ADAPTER_SENSE_OUT        ST7_PE4
78
79 /* Symbolic mapping between port pins and numbered IO lines */
80 #define ST7_PA_IO1      ST7_PA1
81 #define ST7_PA_IO2      ST7_PA2
82 #define ST7_PA_IO4      ST7_PA4
83 #define ST7_PA_IO8      ST7_PA6
84 #define ST7_PA_IO10     ST7_PA7
85 #define ST7_PB_IO5      ST7_PB5
86 #define ST7_PC_IO9      ST7_PC1
87 #define ST7_PC_IO3      ST7_PC2
88 #define ST7_PC_IO7      ST7_PC3
89 #define ST7_PE_IO6      ST7_PE5
90
91 /* Symbolic mapping between numbered IO lines and adapter signals */
92 #define ST7_PA_RTCK     ST7_PA_IO0
93 #define ST7_PA_NTRST    ST7_PA_IO1
94 #define ST7_PC_TDI      ST7_PC_IO3
95 #define ST7_PA_DBGRQ    ST7_PA_IO4
96 #define ST7_PB_NSRST    ST7_PB_IO5
97 #define ST7_PE_TMS      ST7_PE_IO6
98 #define ST7_PC_TCK      ST7_PC_IO7
99 #define ST7_PC_TDO      ST7_PC_IO9
100 #define ST7_PA_DBGACK   ST7_PA_IO10
101
102 static usb_dev_handle *pHDev;
103
104
105 /*
106  * ep1 commands are up to USB_EP1OUT_SIZE bytes in length.
107  * This function takes care of zeroing the unused bytes before sending the packet.
108  * Any reply packet is not handled by this function.
109  */
110 static
111 int
112 ep1_generic_commandl(
113                 usb_dev_handle  *pHDev_param,
114                 size_t          length,
115                 ...
116 ) {
117         uint8_t         usb_buffer[USB_EP1OUT_SIZE];
118         uint8_t         *usb_buffer_p;
119         va_list         ap;
120         int             usb_ret;
121
122         if (length > sizeof(usb_buffer)) {
123                 length = sizeof(usb_buffer);
124         }
125
126         usb_buffer_p = usb_buffer;
127
128         va_start(ap, length);
129         while (length > 0) {
130                 *usb_buffer_p++ = va_arg(ap, int);
131                 length--;
132         }
133
134         memset(
135                         usb_buffer_p,
136                         0,
137                         sizeof(usb_buffer) - (usb_buffer_p - usb_buffer)
138         );
139
140         usb_ret = usb_bulk_write(
141                         pHDev_param,
142                         USB_EP1OUT_ADDR,
143                         (char *)usb_buffer, sizeof(usb_buffer),
144                         USB_TIMEOUT_MS
145         );
146
147         return(usb_ret);
148 }
149
150
151
152 #if 0
153 static
154 ssize_t
155 ep1_memory_read(
156                 usb_dev_handle  *pHDev,
157                 uint16_t        addr,
158                 size_t          length,
159                 uint8_t         *buffer
160 ) {
161         uint8_t         usb_buffer[USB_EP1OUT_SIZE];
162         int             usb_ret;
163         size_t          remain;
164         ssize_t         count;
165
166         usb_buffer[0] = EP1_CMD_MEMORY_READ;
167         memset(
168                         usb_buffer + 4,
169                         0,
170                         sizeof(usb_buffer) - 4
171         );
172
173         remain = length;
174         count = 0;
175
176         while (remain) {
177                 if (remain > sizeof(usb_buffer)) {
178                         length = sizeof(usb_buffer);
179                 } else {
180                         length = remain;
181                 }
182
183                 usb_buffer[1] = addr >> 8;
184                 usb_buffer[2] = addr;
185                 usb_buffer[3] = length;
186
187                 usb_ret = usb_bulk_write(
188                                 pHDev, USB_EP1OUT_ADDR,
189                                 usb_buffer, sizeof(usb_buffer),
190                                 USB_TIMEOUT_MS
191                 );
192
193                 if (usb_ret < sizeof(usb_buffer)) {
194                         break;
195                 }
196
197                 usb_ret = usb_bulk_read(
198                                 pHDev, USB_EP1IN_ADDR,
199                                 buffer, length,
200                                 USB_TIMEOUT_MS
201                 );
202
203                 if (usb_ret < length) {
204                         break;
205                 }
206
207                 addr += length;
208                 buffer += length;
209                 count += length;
210                 remain -= length;
211         }
212
213         return(count);
214 }
215 #endif
216
217
218
219 static
220 ssize_t
221 ep1_memory_write(
222                 usb_dev_handle  *pHDev_param,
223                 uint16_t        addr,
224                 size_t          length,
225                 uint8_t const   *buffer
226 ) {
227         uint8_t         usb_buffer[USB_EP1OUT_SIZE];
228         int             usb_ret;
229         size_t          remain;
230         ssize_t         count;
231
232         usb_buffer[0] = EP1_CMD_MEMORY_WRITE;
233
234         remain = length;
235         count = 0;
236
237         while (remain) {
238                 if (remain > (sizeof(usb_buffer) - 4)) {
239                         length = (sizeof(usb_buffer) - 4);
240                 } else {
241                         length = remain;
242                 }
243
244                 usb_buffer[1] = addr >> 8;
245                 usb_buffer[2] = addr;
246                 usb_buffer[3] = length;
247                 memcpy(
248                                 usb_buffer + 4,
249                                 buffer,
250                                 length
251                 );
252                 memset(
253                                 usb_buffer + 4 + length,
254                                 0,
255                                 sizeof(usb_buffer) - 4 - length
256                 );
257
258                 usb_ret = usb_bulk_write(
259                                 pHDev_param, USB_EP1OUT_ADDR,
260                                 (char *)usb_buffer, sizeof(usb_buffer),
261                                 USB_TIMEOUT_MS
262                 );
263
264                 if ((size_t)usb_ret < sizeof(usb_buffer)) {
265                         break;
266                 }
267
268                 addr += length;
269                 buffer += length;
270                 count += length;
271                 remain -= length;
272         }
273
274         return(count);
275 }
276
277
278 #if 0
279 static
280 ssize_t
281 ep1_memory_writel(
282                 usb_dev_handle  *pHDev,
283                 uint16_t        addr,
284                 size_t          length,
285                 ...
286 ) {
287         uint8_t         buffer[USB_EP1OUT_SIZE - 4];
288         uint8_t         *buffer_p;
289         va_list         ap;
290         size_t          remain;
291
292         if (length > sizeof(buffer)) {
293                 length = sizeof(buffer);
294         }
295
296         remain = length;
297         buffer_p = buffer;
298
299         va_start(ap, length);
300         while (remain > 0) {
301                 *buffer_p++ = va_arg(ap, int);
302                 remain--;
303         }
304
305         return(ep1_memory_write(pHDev, addr, length, buffer));
306 }
307 #endif
308
309
310 #define DTCLOAD_COMMENT         (0)
311 #define DTCLOAD_ENTRY           (1)
312 #define DTCLOAD_LOAD            (2)
313 #define DTCLOAD_RUN                     (3)
314 #define DTCLOAD_LUT_START       (4)
315 #define DTCLOAD_LUT                     (5)
316
317 #define DTC_LOAD_BUFFER         ST7_USB_BUF_EP2UIDO
318
319 /* This gets set by the DTC loader */
320 static uint8_t dtc_entry_download;
321
322
323 /* The buffer is specially formatted to represent a valid image to load into the DTC. */
324 static
325 int
326 dtc_load_from_buffer(
327                 usb_dev_handle  *pHDev_param,
328                 const uint8_t           *buffer,
329                 size_t                  length
330 ) {
331         struct header_s {
332                 uint8_t type;
333                 uint8_t length;
334         };
335
336         int                             usb_err;
337         struct header_s *header;
338         uint8_t                         lut_start = 0xc0;
339
340         dtc_entry_download = 0;
341
342         /* Stop the DTC before loading anything. */
343         usb_err = ep1_generic_commandl(
344                         pHDev_param, 1,
345                         EP1_CMD_DTC_STOP
346         );
347         if (usb_err < 0) return(usb_err);
348
349         while (length) {
350                 if (length < sizeof(*header)) {
351                         LOG_ERROR("Malformed DTC image");
352                         exit(1);
353                 }
354
355                 header = (struct header_s *)buffer;
356                 buffer += sizeof(*header);
357                 length -= sizeof(*header);
358
359                 if (length < (size_t)header->length + 1) {
360                         LOG_ERROR("Malformed DTC image");
361                         exit(1);
362                 }
363
364                 switch (header->type) {
365                 case DTCLOAD_COMMENT:
366                         break;
367
368                 case DTCLOAD_ENTRY:
369                         /* store entry addresses somewhere */
370                         if (!strncmp("download", (char *)buffer + 1, 8)) {
371                                 dtc_entry_download = buffer[0];
372                         }
373                         break;
374
375                 case DTCLOAD_LOAD:
376                         /* Send the DTC program to ST7 RAM. */
377                         usb_err = ep1_memory_write(
378                                         pHDev_param,
379                                         DTC_LOAD_BUFFER,
380                                         header->length + 1, buffer
381                         );
382                         if (usb_err < 0) return(usb_err);
383
384                         /* Load it into the DTC. */
385                         usb_err = ep1_generic_commandl(
386                                         pHDev_param, 3,
387                                         EP1_CMD_DTC_LOAD,
388                                         (DTC_LOAD_BUFFER >> 8),
389                                         DTC_LOAD_BUFFER
390                         );
391                         if (usb_err < 0) return(usb_err);
392
393                         break;
394
395                 case DTCLOAD_RUN:
396                         usb_err = ep1_generic_commandl(
397                                         pHDev_param, 3,
398                                         EP1_CMD_DTC_CALL,
399                                         buffer[0],
400                                         EP1_CMD_DTC_WAIT
401                         );
402                         if (usb_err < 0) return(usb_err);
403
404                         break;
405
406                 case DTCLOAD_LUT_START:
407                         lut_start = buffer[0];
408                         break;
409
410                 case DTCLOAD_LUT:
411                         usb_err = ep1_memory_write(
412                                         pHDev_param,
413                                         ST7_USB_BUF_EP0OUT + lut_start,
414                                         header->length + 1, buffer
415                         );
416                         if (usb_err < 0) return(usb_err);
417                         break;
418
419                 default:
420                         LOG_ERROR("Invalid DTC image record type: 0x%02x", header->type);
421                         exit(1);
422                         break;
423                 }
424
425                 buffer += (header->length + 1);
426                 length -= (header->length + 1);
427         }
428
429         return(0);
430 }
431
432
433 /*
434  * Start the DTC running in download mode (waiting for 512 byte command packets on ep2).
435  */
436 static
437 int
438 dtc_start_download(void) {
439         int     usb_err;
440         uint8_t ep2txr;
441
442         /* set up for download mode and make sure EP2 is set up to transmit */
443         usb_err = ep1_generic_commandl(
444                         pHDev, 7,
445
446                         EP1_CMD_DTC_STOP,
447                         EP1_CMD_SET_UPLOAD,
448                         EP1_CMD_SET_DOWNLOAD,
449                         EP1_CMD_MEMORY_READ,    /* read EP2TXR for its data toggle */
450                         ST7_EP2TXR >> 8,
451                         ST7_EP2TXR,
452                         1
453         );
454         if (usb_err < 0) return(usb_err);
455
456         /* read back ep2txr */
457         usb_err = usb_bulk_read(
458                         pHDev, USB_EP1IN_ADDR,
459                         (char *)&ep2txr, 1,
460                         USB_TIMEOUT_MS
461         );
462         if (usb_err < 0) return(usb_err);
463
464         usb_err = ep1_generic_commandl(
465                         pHDev, 13,
466
467                         EP1_CMD_MEMORY_WRITE,   /* preinitialize poll byte */
468                         DTC_STATUS_POLL_BYTE >> 8,
469                         DTC_STATUS_POLL_BYTE,
470                         1,
471                         0x00,
472                         EP1_CMD_MEMORY_WRITE,   /* set EP2IN to return data */
473                         ST7_EP2TXR >> 8,
474                         ST7_EP2TXR,
475                         1,
476                         (ep2txr & ST7_EP2TXR_DTOG_TX) | ST7_EP2TXR_STAT_VALID,
477                         EP1_CMD_DTC_CALL,       /* start running the DTC */
478                         dtc_entry_download,
479                         EP1_CMD_DTC_GET_CACHED_STATUS
480         );
481         if (usb_err < 0) return(usb_err);
482
483         /* wait for completion */
484         usb_err = usb_bulk_read(
485                         pHDev, USB_EP1IN_ADDR,
486                         (char *)&ep2txr, 1,
487                         USB_TIMEOUT_MS
488         );
489
490         return(usb_err);
491 }
492
493
494 static
495 int
496 dtc_run_download(
497                 usb_dev_handle  *pHDev_param,
498                 uint8_t *command_buffer,
499                 int     command_buffer_size,
500                 uint8_t *reply_buffer,
501                 int     reply_buffer_size
502 ) {
503         uint8_t ep2_buffer[USB_EP2IN_SIZE];
504         int     usb_err;
505         int     i;
506
507         LOG_DEBUG(": %d/%d", command_buffer_size, reply_buffer_size);
508
509         usb_err = usb_bulk_write(
510                         pHDev_param,
511                         USB_EP2OUT_ADDR,
512                         (char *)command_buffer, USB_EP2BANK_SIZE,
513                         USB_TIMEOUT_MS
514         );
515         if (usb_err < 0) return(usb_err);
516
517
518         /* Wait for DTC to finish running command buffer */
519         for (i = 10;;) {
520                 usb_err = ep1_generic_commandl(
521                                 pHDev_param, 4,
522
523                                 EP1_CMD_MEMORY_READ,
524                                 DTC_STATUS_POLL_BYTE >> 8,
525                                 DTC_STATUS_POLL_BYTE,
526                                 1
527                 );
528                 if (usb_err < 0) return(usb_err);
529
530                 usb_err = usb_bulk_read(
531                                 pHDev_param,
532                                 USB_EP1IN_ADDR,
533                                 (char *)ep2_buffer, 1,
534                                 USB_TIMEOUT_MS
535                 );
536                 if (usb_err < 0) return(usb_err);
537
538                 if (ep2_buffer[0] & 0x01) break;
539
540                 if (!--i) {
541                         LOG_ERROR("%s, %d: too many retries waiting for DTC status",
542                                         __FILE__, __LINE__
543                         );
544                         return(-ETIMEDOUT);
545                 }
546         }
547
548
549         if (!reply_buffer) reply_buffer_size = 0;
550         if (reply_buffer_size) {
551                 usb_err = usb_bulk_read(
552                                 pHDev_param,
553                                 USB_EP2IN_ADDR,
554                                 (char *)ep2_buffer, sizeof(ep2_buffer),
555                                 USB_TIMEOUT_MS
556                 );
557
558                 if (usb_err < (int)sizeof(ep2_buffer)) {
559                         LOG_ERROR("%s, %d: Read of endpoint 2 returned %d",
560                                         __FILE__, __LINE__, usb_err
561                         );
562                         return(usb_err);
563                 }
564
565                 memcpy(reply_buffer, ep2_buffer, reply_buffer_size);
566
567         }
568
569         return(usb_err);
570 }
571
572
573 /*
574  * The dtc reply queue is a singly linked list that describes what to do with the reply packet that comes from the DTC.  Only SCAN_IN and SCAN_IO generate these entries.
575  */
576
577 struct dtc_reply_queue_entry {
578         struct dtc_reply_queue_entry    *next;
579         struct jtag_command     *cmd;   /* the command that resulted in this entry */
580
581         struct {
582                 uint8_t         *buffer;        /* the scan buffer */
583                 int             size;           /* size of the scan buffer in bits */
584                 int             offset;         /* how many bits were already done before this? */
585                 int             length;         /* how many bits are processed in this operation? */
586                 enum scan_type  type;           /* SCAN_IN/SCAN_OUT/SCAN_IO */
587         } scan;
588 };
589
590
591 /*
592  * The dtc_queue consists of a buffer of pending commands and a reply queue.
593  * rlink_scan and tap_state_run add to the command buffer and maybe to the reply queue.
594  */
595
596 static
597 struct {
598         struct dtc_reply_queue_entry    *rq_head;
599         struct dtc_reply_queue_entry    *rq_tail;
600         uint32_t                        cmd_index;
601         uint32_t                        reply_index;
602         uint8_t                 cmd_buffer[USB_EP2BANK_SIZE];
603 } dtc_queue;
604
605
606 /*
607  * The tap state queue is for accumulating TAP state changes wiithout needlessly flushing the dtc_queue.  When it fills or is run, it adds the accumulated bytes to the dtc_queue.
608  */
609
610 static
611 struct {
612         uint32_t        length;
613         uint32_t        buffer;
614 } tap_state_queue;
615
616
617
618 static
619 int
620 dtc_queue_init(void) {
621         dtc_queue.rq_head = NULL;
622         dtc_queue.rq_tail = NULL;
623         dtc_queue.cmd_index = 0;
624         dtc_queue.reply_index = 0;
625         return(0);
626 }
627
628
629 static
630 inline
631 struct dtc_reply_queue_entry *
632 dtc_queue_enqueue_reply(
633                 enum scan_type  type,
634                 uint8_t                         *buffer,
635                 int                             size,
636                 int                             offset,
637                 int                             length,
638                 struct jtag_command     *cmd
639 ) {
640         struct dtc_reply_queue_entry    *rq_entry;
641
642         rq_entry = malloc(sizeof(struct dtc_reply_queue_entry));
643         if (rq_entry != NULL) {
644                 rq_entry->scan.type = type;
645                 rq_entry->scan.buffer = buffer;
646                 rq_entry->scan.size = size;
647                 rq_entry->scan.offset = offset;
648                 rq_entry->scan.length = length;
649                 rq_entry->cmd = cmd;
650                 rq_entry->next = NULL;
651
652                 if (dtc_queue.rq_head == NULL)
653                         dtc_queue.rq_head = rq_entry;
654                 else
655                         dtc_queue.rq_tail->next = rq_entry;
656
657                 dtc_queue.rq_tail = rq_entry;
658         }
659
660         return(rq_entry);
661 }
662
663
664 /*
665  * Running the queue means that any pending command buffer is run and any reply data dealt with.  The command buffer is then cleared for subsequent processing.
666  * The queue is automatically run by append when it is necessary to get space for the append.
667  */
668
669 static
670 int
671 dtc_queue_run(void) {
672         struct dtc_reply_queue_entry    *rq_p, *rq_next;
673         int                     retval;
674         int                     usb_err;
675         int                     bit_cnt;
676         int                     x;
677         uint8_t                 *dtc_p, *tdo_p;
678         uint8_t                 dtc_mask, tdo_mask;
679         uint8_t                 reply_buffer[USB_EP2IN_SIZE];
680
681         retval = ERROR_OK;
682
683         if (dtc_queue.cmd_index < 1) return(retval);
684
685         dtc_queue.cmd_buffer[dtc_queue.cmd_index++] = DTC_CMD_STOP;
686
687         /* run the cmd */
688         if (dtc_queue.rq_head == NULL) {
689                 usb_err = dtc_run_download(pHDev,
690                                 dtc_queue.cmd_buffer, dtc_queue.cmd_index,
691                                 NULL, 0
692                 );
693                 if (usb_err < 0) {
694                         LOG_ERROR("dtc_run_download: %s", usb_strerror());
695                         exit(1);
696                 }
697         } else {
698                 usb_err = dtc_run_download(pHDev,
699                                 dtc_queue.cmd_buffer, dtc_queue.cmd_index,
700                                 reply_buffer, dtc_queue.reply_index
701                 );
702                 if (usb_err < 0) {
703                         LOG_ERROR("dtc_run_download: %s", usb_strerror());
704                         exit(1);
705                 } else {
706                         /* process the reply, which empties the reply queue and frees its entries */
707                         dtc_p = reply_buffer;
708
709                         /* The rigamarole with the masks and doing it bit-by-bit is due to the fact that the scan buffer is LSb-first and the DTC code is MSb-first for hardware reasons.   It was that or craft a function to do the reversal, and that wouldn't work with bit-stuffing (supplying extra bits to use mostly byte operations), or any other scheme which would throw the byte alignment off. */
710
711                         for (
712                                         rq_p = dtc_queue.rq_head;
713                                         rq_p != NULL;
714                                         rq_p = rq_next
715                         ) {
716                                 tdo_p = rq_p->scan.buffer + (rq_p->scan.offset / 8);
717                                 tdo_mask = 1 << (rq_p->scan.offset % 8);
718
719
720                                 bit_cnt = rq_p->scan.length;
721                                 if (bit_cnt >= 8) {
722                                         /* bytes */
723
724                                         dtc_mask = 1 << (8 - 1);
725
726                                         for (
727                                                         ;
728                                                         bit_cnt;
729                                                         bit_cnt--
730                                         ) {
731                                                 if (*dtc_p & dtc_mask) {
732                                                         *tdo_p |= tdo_mask;
733                                                 } else {
734                                                         *tdo_p &=~ tdo_mask;
735                                                 }
736
737                                                 dtc_mask >>= 1;
738                                                 if (dtc_mask == 0) {
739                                                         dtc_p++;
740                                                         dtc_mask = 1 << (8 - 1);
741                                                 }
742
743                                                 tdo_mask <<= 1;
744                                                 if (tdo_mask == 0) {
745                                                         tdo_p++;
746                                                         tdo_mask = 1;
747                                                 }
748                                         }
749                                 } else {
750                                         /*  extra bits or last bit */
751
752                                         x = *dtc_p++;
753                                         if ((
754                                                         rq_p->scan.type == SCAN_IN
755                                         ) && (
756                                                         rq_p->scan.offset != rq_p->scan.size - 1
757                                         )) {
758                                                 /* extra bits were sent as a full byte with padding on the end */
759                                                 dtc_mask = 1 << (8 - 1);
760                                         } else {
761                                                 dtc_mask = 1 << (bit_cnt - 1);
762                                         }
763
764                                         for (
765                                                         ;
766                                                         bit_cnt;
767                                                         bit_cnt--
768                                         ) {
769                                                 if (x & dtc_mask) {
770                                                         *tdo_p |= tdo_mask;
771                                                 } else {
772                                                         *tdo_p &=~ tdo_mask;
773                                                 }
774
775                                                 dtc_mask >>= 1;
776
777                                                 tdo_mask <<= 1;
778                                                 if (tdo_mask == 0) {
779                                                         tdo_p++;
780                                                         tdo_mask = 1;
781                                                 }
782
783                                         }
784                                 }
785
786                                 if ((rq_p->scan.offset + rq_p->scan.length) >= rq_p->scan.size) {
787                                         /* feed scan buffer back into openocd and free it */
788                                         if (jtag_read_buffer(rq_p->scan.buffer, rq_p->cmd->cmd.scan) != ERROR_OK) {
789                                                 retval = ERROR_JTAG_QUEUE_FAILED;
790                                         }
791                                         free(rq_p->scan.buffer);
792                                 }
793
794                                 rq_next = rq_p->next;
795                                 free(rq_p);
796                         }
797                         dtc_queue.rq_head = NULL;
798                         dtc_queue.rq_tail = NULL;
799                 }
800
801         }
802
803
804         /* reset state for new appends */
805         dtc_queue.cmd_index = 0;
806         dtc_queue.reply_index = 0;
807
808         return(retval);
809 }
810
811
812
813 static
814 int
815 tap_state_queue_init(void) {
816         tap_state_queue.length = 0;
817         tap_state_queue.buffer = 0;
818         return(0);
819 }
820
821
822 static
823 int
824 tap_state_queue_run(void) {
825         int     i;
826         int     bits;
827         uint8_t byte_param;
828         int     retval;
829
830         retval = 0;
831         if (!tap_state_queue.length) return(retval);
832         bits = 1;
833         byte_param = 0;
834         for (i = tap_state_queue.length; i--;) {
835
836                 byte_param <<= 1;
837                 if (tap_state_queue.buffer & 1) {
838                         byte_param |= 1;
839                 }
840                 if ((bits >= 8) || !i) {
841                         byte_param <<= (8 - bits);
842
843                         /* make sure there's room for stop, byte op, and one byte */
844                         if (dtc_queue.cmd_index >= (sizeof(dtc_queue.cmd_buffer) - (1 + 1 + 1))) {
845                                 dtc_queue.cmd_buffer[dtc_queue.cmd_index++] =
846                                                 DTC_CMD_STOP;
847                                 dtc_queue_run();
848                         }
849
850 #ifdef USE_HARDWARE_SHIFTER_FOR_TMS
851                         if (bits == 8) {
852                                 dtc_queue.cmd_buffer[dtc_queue.cmd_index++] =
853                                                 DTC_CMD_SHIFT_TMS_BYTES(1);
854                         } else {
855 #endif
856                                 dtc_queue.cmd_buffer[dtc_queue.cmd_index++] =
857                                                 DTC_CMD_SHIFT_TMS_BITS(bits);
858 #ifdef USE_HARDWARE_SHIFTER_FOR_TMS
859                         }
860 #endif
861
862                         dtc_queue.cmd_buffer[dtc_queue.cmd_index++] =
863                                         byte_param;
864
865                         byte_param = 0;
866                         bits = 1;
867                 } else {
868                         bits++;
869                 }
870
871                 tap_state_queue.buffer >>= 1;
872         }
873         retval = tap_state_queue_init();
874         return(retval);
875 }
876
877
878 static
879 int
880 tap_state_queue_append(
881                 uint8_t tms
882 ) {
883         int     retval;
884
885         if (tap_state_queue.length >= sizeof(tap_state_queue.buffer) * 8) {
886                 retval = tap_state_queue_run();
887                 if (retval != 0) return(retval);
888         }
889
890         if (tms) {
891                 tap_state_queue.buffer |= (1 << tap_state_queue.length);
892         }
893         tap_state_queue.length++;
894
895         return(0);
896 }
897
898
899 static
900 void rlink_end_state(tap_state_t state)
901 {
902         if (tap_is_state_stable(state))
903                 tap_set_end_state(state);
904         else
905         {
906                 LOG_ERROR("BUG: %i is not a valid end state", state);
907                 exit(-1);
908         }
909 }
910
911
912 static
913 void rlink_state_move(void) {
914
915         int i = 0, tms = 0;
916         uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
917         int tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
918
919         for (i = 0; i < tms_count; i++)
920         {
921                 tms = (tms_scan >> i) & 1;
922                 tap_state_queue_append(tms);
923         }
924
925         tap_set_state(tap_get_end_state());
926 }
927
928 static
929 void rlink_path_move(struct pathmove_command *cmd)
930 {
931         int num_states = cmd->num_states;
932         int state_count;
933         int tms = 0;
934
935         state_count = 0;
936         while (num_states)
937         {
938                 if (tap_state_transition(tap_get_state(), false) == cmd->path[state_count])
939                 {
940                         tms = 0;
941                 }
942                 else if (tap_state_transition(tap_get_state(), true) == cmd->path[state_count])
943                 {
944                         tms = 1;
945                 }
946                 else
947                 {
948                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition", tap_state_name(tap_get_state()), tap_state_name(cmd->path[state_count]));
949                         exit(-1);
950                 }
951
952                 tap_state_queue_append(tms);
953
954                 tap_set_state(cmd->path[state_count]);
955                 state_count++;
956                 num_states--;
957         }
958
959         tap_set_end_state(tap_get_state());
960 }
961
962
963 static
964 void rlink_runtest(int num_cycles)
965 {
966         int i;
967
968         tap_state_t saved_end_state = tap_get_end_state();
969
970         /* only do a state_move when we're not already in RTI */
971         if (tap_get_state() != TAP_IDLE)
972         {
973                 rlink_end_state(TAP_IDLE);
974                 rlink_state_move();
975         }
976
977         /* execute num_cycles */
978         for (i = 0; i < num_cycles; i++)
979         {
980                 tap_state_queue_append(0);
981         }
982
983         /* finish in end_state */
984         rlink_end_state(saved_end_state);
985         if (tap_get_state() != tap_get_end_state())
986                 rlink_state_move();
987 }
988
989
990 /* (1) assert or (0) deassert reset lines */
991 static
992 void rlink_reset(int trst, int srst)
993 {
994         uint8_t                 bitmap;
995         int                     usb_err;
996
997         /* Read port A for bit op */
998         usb_err = ep1_generic_commandl(
999                         pHDev, 4,
1000                         EP1_CMD_MEMORY_READ,
1001                         ST7_PADR >> 8,
1002                         ST7_PADR,
1003                         1
1004         );
1005         if (usb_err < 0) {
1006                 LOG_ERROR("%s", usb_strerror());
1007                 exit(1);
1008         }
1009
1010         usb_err = usb_bulk_read(
1011                         pHDev, USB_EP1IN_ADDR,
1012                         (char *)&bitmap, 1,
1013                         USB_TIMEOUT_MS
1014         );
1015         if (usb_err < 1) {
1016                 LOG_ERROR("%s", usb_strerror());
1017                 exit(1);
1018         }
1019
1020         if (trst) {
1021                 bitmap &= ~ST7_PA_NTRST;
1022         } else {
1023                 bitmap |= ST7_PA_NTRST;
1024         }
1025
1026         /* Write port A and read port B for bit op */
1027         /* port B has no OR, and we want to emulate open drain on NSRST, so we initialize DR to 0 and assert NSRST by setting DDR to 1. */
1028         usb_err = ep1_generic_commandl(
1029                         pHDev, 9,
1030                         EP1_CMD_MEMORY_WRITE,
1031                         ST7_PADR >> 8,
1032                         ST7_PADR,
1033                         1,
1034                         bitmap,
1035                         EP1_CMD_MEMORY_READ,
1036                         ST7_PBDDR >> 8,
1037                         ST7_PBDDR,
1038                         1
1039         );
1040         if (usb_err < 0) {
1041                 LOG_ERROR("%s", usb_strerror());
1042                 exit(1);
1043         }
1044
1045         usb_err = usb_bulk_read(
1046                         pHDev, USB_EP1IN_ADDR,
1047                         (char *)&bitmap, 1,
1048                         USB_TIMEOUT_MS
1049         );
1050         if (usb_err < 1) {
1051                 LOG_ERROR("%s", usb_strerror());
1052                 exit(1);
1053         }
1054
1055         if (srst) {
1056                 bitmap |= ST7_PB_NSRST;
1057         } else {
1058                 bitmap &= ~ST7_PB_NSRST;
1059         }
1060
1061         /* write port B and read dummy to ensure completion before returning */
1062         usb_err = ep1_generic_commandl(
1063                         pHDev, 6,
1064                         EP1_CMD_MEMORY_WRITE,
1065                         ST7_PBDDR >> 8,
1066                         ST7_PBDDR,
1067                         1,
1068                         bitmap,
1069                         EP1_CMD_DTC_GET_CACHED_STATUS
1070         );
1071         if (usb_err < 0) {
1072                 LOG_ERROR("%s", usb_strerror());
1073                 exit(1);
1074         }
1075
1076         usb_err = usb_bulk_read(
1077                         pHDev, USB_EP1IN_ADDR,
1078                         (char *)&bitmap, 1,
1079                         USB_TIMEOUT_MS
1080         );
1081         if (usb_err < 1) {
1082                 LOG_ERROR("%s", usb_strerror());
1083                 exit(1);
1084         }
1085 }
1086
1087
1088 static
1089 int
1090 rlink_scan(
1091                 struct jtag_command     *cmd,
1092                 enum scan_type  type,
1093                 uint8_t                 *buffer,
1094                 int                     scan_size
1095 ) {
1096         bool            ir_scan;
1097         tap_state_t     saved_end_state;
1098         int                     byte_bits;
1099         int                     extra_bits;
1100         int                     chunk_bits;
1101         int                     chunk_bytes;
1102         int                     x;
1103
1104         int                     tdi_bit_offset;
1105         uint8_t                 tdi_mask, *tdi_p;
1106         uint8_t                 dtc_mask;
1107
1108         if (scan_size < 1) {
1109                 LOG_ERROR("scan_size cannot be less than 1 bit");
1110                 exit(1);
1111         }
1112
1113         ir_scan = cmd->cmd.scan->ir_scan;
1114
1115         /* Move to the proper state before starting to shift TDI/TDO. */
1116         if (!(
1117                         (!ir_scan && (tap_get_state() == TAP_DRSHIFT))
1118                         ||
1119                         (ir_scan && (tap_get_state() == TAP_IRSHIFT))
1120         )) {
1121                 saved_end_state = tap_get_end_state();
1122                 rlink_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
1123                 rlink_state_move();
1124                 rlink_end_state(saved_end_state);
1125         }
1126
1127         tap_state_queue_run();
1128
1129
1130 #if 0
1131         printf("scan_size = %d, type = 0x%x\n", scan_size, type);
1132         {
1133                 int   i;
1134
1135                 /* clear unused bits in scan buffer for ease of debugging */
1136                 /* (it makes diffing output easier) */
1137                 buffer[scan_size / 8] &= ((1 << ((scan_size - 1) % 8) + 1) - 1);
1138
1139                 printf("before scan:");
1140                 for (i = 0; i < (scan_size + 7) / 8; i++) {
1141                         printf(" %02x", buffer[i]);
1142                 }
1143                 printf("\n");
1144         }
1145 #endif
1146
1147         /* The number of bits that can be shifted as complete bytes */
1148         byte_bits = (int)(scan_size - 1) / 8 * 8;
1149         /* The number of bits left over, not counting the last bit */
1150         extra_bits = (scan_size - 1) - byte_bits;
1151
1152         tdi_bit_offset = 0;
1153         tdi_p = buffer;
1154         tdi_mask = 1;
1155
1156         if (extra_bits && (type == SCAN_OUT)) {
1157                 /* Schedule any extra bits into the DTC command buffer, padding as needed */
1158                 /* For SCAN_OUT, this comes before the full bytes so the (leading) padding bits will fall off the end */
1159                 /* make sure there's room for stop, byte op, and one byte */
1160                 if (
1161                                 (dtc_queue.cmd_index >= sizeof(dtc_queue.cmd_buffer) - (1 + 1 + 1))
1162                 ) {
1163                         dtc_queue_run();
1164                 }
1165
1166                 x = 0;
1167                 dtc_mask = 1 << (extra_bits - 1);
1168
1169                 while (extra_bits--) {
1170                         if (*tdi_p & tdi_mask) {
1171                                 x |= dtc_mask;
1172                         }
1173
1174                         dtc_mask >>= 1;
1175
1176                         tdi_mask <<= 1;
1177                         if (tdi_mask == 0) {
1178                                 tdi_p++;
1179                                 tdi_mask = 1;
1180                         }
1181                 }
1182
1183                 dtc_queue.cmd_buffer[dtc_queue.cmd_index++] =
1184                                 DTC_CMD_SHIFT_TDI_BYTES(1);
1185
1186                 dtc_queue.cmd_buffer[dtc_queue.cmd_index++] = x;
1187         }
1188
1189         /* Loop scheduling full bytes into the DTC command buffer */
1190         while (byte_bits) {
1191                 if (type == SCAN_IN) {
1192                         /* make sure there's room for stop and byte op */
1193                         x = (dtc_queue.cmd_index >= sizeof(dtc_queue.cmd_buffer) - (1 + 1));
1194                 } else {
1195                         /* make sure there's room for stop, byte op, and at least one byte */
1196                         x = (dtc_queue.cmd_index >= sizeof(dtc_queue.cmd_buffer) - (1 + 1 + 1));
1197                 }
1198
1199                 if (type != SCAN_OUT) {
1200                         /* make sure there's room for at least one reply byte */
1201                         x |= (dtc_queue.reply_index >= USB_EP2IN_SIZE - (1));
1202                 }
1203
1204                 if (x) {
1205                         dtc_queue_run();
1206                 }
1207
1208                 chunk_bits = byte_bits;
1209                 /* we can only use up to 16 bytes at a time */
1210                 if (chunk_bits > (16 * 8)) chunk_bits = (16 * 8);
1211
1212                 if (type != SCAN_IN) {
1213                         /* how much is there room for, considering stop and byte op? */
1214                         x = (sizeof(dtc_queue.cmd_buffer) - (dtc_queue.cmd_index + 1 + 1)) * 8;
1215                         if (chunk_bits > x) chunk_bits = x;
1216                 }
1217
1218                 if (type != SCAN_OUT) {
1219                         /* how much is there room for in the reply buffer? */
1220                         x = (USB_EP2IN_SIZE - dtc_queue.reply_index) * 8;
1221                         if (chunk_bits > x) chunk_bits = x;
1222                 }
1223
1224                 /* so the loop will end */
1225                 byte_bits -= chunk_bits;
1226
1227                 if (type != SCAN_OUT) {
1228                         if (dtc_queue_enqueue_reply(
1229                                         type, buffer, scan_size, tdi_bit_offset,
1230                                         chunk_bits,
1231                                         cmd
1232                         ) == NULL) {
1233                                 LOG_ERROR("enqueuing DTC reply entry: %s", strerror(errno));
1234                                 exit(1);
1235                         }
1236
1237                         tdi_bit_offset += chunk_bits;
1238                 }
1239
1240                 /* chunk_bits is a multiple of 8, so there are no rounding issues. */
1241                 chunk_bytes = chunk_bits / 8;
1242
1243                 switch (type) {
1244                 case SCAN_IN:
1245                         x = DTC_CMD_SHIFT_TDO_BYTES(chunk_bytes);
1246                         break;
1247                 case SCAN_OUT:
1248                         x = DTC_CMD_SHIFT_TDI_BYTES(chunk_bytes);
1249                         break;
1250                 default:
1251                         x = DTC_CMD_SHIFT_TDIO_BYTES(chunk_bytes);
1252                         break;
1253                 }
1254                 dtc_queue.cmd_buffer[dtc_queue.cmd_index++] = x;
1255
1256                 if (type != SCAN_IN) {
1257                         x = 0;
1258                         dtc_mask = 1 << (8 - 1);
1259
1260                         while (chunk_bits--) {
1261                                 if (*tdi_p & tdi_mask) {
1262                                         x |= dtc_mask;
1263                                 }
1264
1265                                 dtc_mask >>= 1;
1266                                 if (dtc_mask == 0) {
1267                                         dtc_queue.cmd_buffer[dtc_queue.cmd_index++] = x;
1268                                         dtc_queue.reply_index++;
1269                                         x = 0;
1270                                         dtc_mask = 1 << (8 - 1);
1271                                 }
1272
1273                                 tdi_mask <<= 1;
1274                                 if (tdi_mask == 0) {
1275                                         tdi_p++;
1276                                         tdi_mask = 1;
1277                                 }
1278                         }
1279                 }
1280         }
1281
1282         if (extra_bits && (type != SCAN_OUT)) {
1283                 /* Schedule any extra bits into the DTC command buffer */
1284                 /* make sure there's room for stop, byte op, and one byte */
1285                 if (
1286                                 (dtc_queue.cmd_index >= sizeof(dtc_queue.cmd_buffer) - (1 + 1 + 1))
1287                                 ||
1288                                 (dtc_queue.reply_index >= USB_EP2IN_SIZE - (1))
1289                 ) {
1290                         dtc_queue_run();
1291                 }
1292
1293                 if (dtc_queue_enqueue_reply(
1294                                 type, buffer, scan_size, tdi_bit_offset,
1295                                 extra_bits,
1296                                 cmd
1297                 ) == NULL) {
1298                         LOG_ERROR("enqueuing DTC reply entry: %s", strerror(errno));
1299                         exit(1);
1300                 }
1301
1302                 tdi_bit_offset += extra_bits;
1303
1304                 if (type == SCAN_IN) {
1305                         dtc_queue.cmd_buffer[dtc_queue.cmd_index++] =
1306                                         DTC_CMD_SHIFT_TDO_BYTES(1);
1307
1308                 } else {
1309                         dtc_queue.cmd_buffer[dtc_queue.cmd_index++] =
1310                                         DTC_CMD_SHIFT_TDIO_BITS(extra_bits);
1311
1312                         x = 0;
1313                         dtc_mask = 1 << (8 - 1);
1314
1315                         while (extra_bits--) {
1316                                 if (*tdi_p & tdi_mask) {
1317                                         x |= dtc_mask;
1318                                 }
1319
1320                                 dtc_mask >>= 1;
1321
1322                                 tdi_mask <<= 1;
1323                                 if (tdi_mask == 0) {
1324                                         tdi_p++;
1325                                         tdi_mask = 1;
1326                                 }
1327                         }
1328
1329                         dtc_queue.cmd_buffer[dtc_queue.cmd_index++] = x;
1330                 }
1331
1332                 dtc_queue.reply_index++;
1333         }
1334
1335         /* Schedule the last bit into the DTC command buffer */
1336         {
1337                 /* make sure there's room for stop, and bit pair command */
1338                 if (
1339                                 (dtc_queue.cmd_index >= sizeof(dtc_queue.cmd_buffer) - (1 + 1))
1340                                 ||
1341                                 (dtc_queue.reply_index >= USB_EP2IN_SIZE - (1))
1342                 ) {
1343                         dtc_queue_run();
1344                 }
1345
1346                 if (type == SCAN_OUT) {
1347                         dtc_queue.cmd_buffer[dtc_queue.cmd_index++] =
1348                                         DTC_CMD_SHIFT_TMS_TDI_BIT_PAIR(1, (*tdi_p & tdi_mask), 0);
1349
1350                 } else {
1351                         if (dtc_queue_enqueue_reply(
1352                                         type, buffer, scan_size, tdi_bit_offset,
1353                                         1,
1354                                         cmd
1355                         ) == NULL) {
1356                                 LOG_ERROR("enqueuing DTC reply entry: %s", strerror(errno));
1357                                 exit(1);
1358                         }
1359
1360                         dtc_queue.cmd_buffer[dtc_queue.cmd_index++] =
1361                                         DTC_CMD_SHIFT_TMS_TDI_BIT_PAIR(1, (*tdi_p & tdi_mask), 1);
1362
1363                         dtc_queue.reply_index++;
1364                 }
1365         }
1366
1367         /* Move to pause state */
1368         tap_state_queue_append(0);
1369         tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
1370         if (tap_get_state() != tap_get_end_state()) rlink_state_move();
1371
1372         return(0);
1373 }
1374
1375
1376 static
1377 int rlink_execute_queue(void)
1378 {
1379         struct jtag_command *cmd = jtag_command_queue; /* currently processed command */
1380         int scan_size;
1381         enum scan_type type;
1382         uint8_t *buffer;
1383         int retval, tmp_retval;
1384
1385         /* return ERROR_OK, unless something goes wrong */
1386         retval = ERROR_OK;
1387
1388 #ifndef AUTOMATIC_BUSY_LED
1389         /* turn LED on */
1390         ep1_generic_commandl(pHDev, 2,
1391                         EP1_CMD_SET_PORTD_LEDS,
1392                         ~(ST7_PD_NBUSY_LED)
1393         );
1394 #endif
1395
1396         while (cmd)
1397         {
1398                 switch (cmd->type)
1399                 {
1400                 case JTAG_RUNTEST:
1401                 case JTAG_TLR_RESET:
1402                 case JTAG_PATHMOVE:
1403                 case JTAG_SCAN:
1404                         break;
1405
1406                 default:
1407                         /* some events, such as resets, need a queue flush to ensure consistency */
1408                         tap_state_queue_run();
1409                         dtc_queue_run();
1410                         break;
1411                 }
1412
1413                 switch (cmd->type)
1414                 {
1415                 case JTAG_RESET:
1416 #ifdef _DEBUG_JTAG_IO_
1417                         LOG_DEBUG("reset trst: %i srst %i", cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1418 #endif
1419                         if ((cmd->cmd.reset->trst == 1) || (cmd->cmd.reset->srst && (jtag_get_reset_config() & RESET_SRST_PULLS_TRST)))
1420                         {
1421                                 tap_set_state(TAP_RESET);
1422                         }
1423                         rlink_reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1424                         break;
1425                 case JTAG_RUNTEST:
1426 #ifdef _DEBUG_JTAG_IO_
1427                         LOG_DEBUG("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles, cmd->cmd.runtest->end_state);
1428 #endif
1429                         if (cmd->cmd.runtest->end_state != -1)
1430                                 rlink_end_state(cmd->cmd.runtest->end_state);
1431                         rlink_runtest(cmd->cmd.runtest->num_cycles);
1432                         break;
1433                 case JTAG_TLR_RESET:
1434 #ifdef _DEBUG_JTAG_IO_
1435                         LOG_DEBUG("statemove end in %i", cmd->cmd.statemove->end_state);
1436 #endif
1437                         if (cmd->cmd.statemove->end_state != -1)
1438                                 rlink_end_state(cmd->cmd.statemove->end_state);
1439                         rlink_state_move();
1440                         break;
1441                 case JTAG_PATHMOVE:
1442 #ifdef _DEBUG_JTAG_IO_
1443                         LOG_DEBUG("pathmove: %i states, end in %i", cmd->cmd.pathmove->num_states, cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
1444 #endif
1445                         rlink_path_move(cmd->cmd.pathmove);
1446                         break;
1447                 case JTAG_SCAN:
1448 #ifdef _DEBUG_JTAG_IO_
1449                         LOG_DEBUG("%s scan end in %i",  (cmd->cmd.scan->ir_scan) ? "IR" : "DR", cmd->cmd.scan->end_state);
1450 #endif
1451                         if (cmd->cmd.scan->end_state != -1)
1452                                 rlink_end_state(cmd->cmd.scan->end_state);
1453                         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
1454                         type = jtag_scan_type(cmd->cmd.scan);
1455                         if (rlink_scan(cmd, type, buffer, scan_size) != ERROR_OK) {
1456                                 retval = ERROR_FAIL;
1457                         }
1458                         break;
1459                 case JTAG_SLEEP:
1460 #ifdef _DEBUG_JTAG_IO_
1461                         LOG_DEBUG("sleep %i", cmd->cmd.sleep->us);
1462 #endif
1463                         jtag_sleep(cmd->cmd.sleep->us);
1464                         break;
1465                 default:
1466                         LOG_ERROR("BUG: unknown JTAG command type encountered");
1467                         exit(-1);
1468                 }
1469                 cmd = cmd->next;
1470         }
1471
1472         /* Flush the DTC queue to make sure any pending reads have been done before exiting this function */
1473         tap_state_queue_run();
1474         tmp_retval = dtc_queue_run();
1475         if (tmp_retval != ERROR_OK) {
1476                 retval = tmp_retval;
1477         }
1478
1479 #ifndef AUTOMATIC_BUSY_LED
1480         /* turn LED onff */
1481         ep1_generic_commandl(pHDev, 2,
1482                         EP1_CMD_SET_PORTD_LEDS,
1483                         ~0
1484         );
1485 #endif
1486
1487         return retval;
1488 }
1489
1490
1491 /* Using an unindexed table because it is infrequently accessed and it is short.  The table must be in order of ascending speed (and descending prescaler), as it is scanned in reverse. */
1492
1493 static
1494 int rlink_speed(int speed)
1495 {
1496         int             i;
1497
1498         if (speed == 0) {
1499                 /* fastest speed */
1500                 speed = rlink_speed_table[rlink_speed_table_size - 1].prescaler;
1501         }
1502
1503         for (i = rlink_speed_table_size; i--;) {
1504                 if (rlink_speed_table[i].prescaler == speed) {
1505                         if (dtc_load_from_buffer(pHDev, rlink_speed_table[i].dtc, rlink_speed_table[i].dtc_size) != 0) {
1506                                 LOG_ERROR("An error occurred while trying to load DTC code for speed \"%d\".", speed);
1507                                 exit(1);
1508                         }
1509
1510                         if (dtc_start_download() < 0) {
1511                                 LOG_ERROR("%s, %d: starting DTC: %s",
1512                                                 __FILE__, __LINE__,
1513                                                 usb_strerror()
1514                                 );
1515                                 exit(1);
1516                         }
1517
1518                         return ERROR_OK;
1519                 }
1520         }
1521
1522         LOG_ERROR("%d is not a supported speed", speed);
1523         return(ERROR_FAIL);
1524 }
1525
1526
1527 static
1528 int rlink_speed_div(
1529                 int speed,
1530                 int *khz
1531 ) {
1532         int     i;
1533
1534         for (i = rlink_speed_table_size; i--;) {
1535                 if (rlink_speed_table[i].prescaler == speed) {
1536                         *khz = rlink_speed_table[i].khz;
1537                         return(ERROR_OK);
1538                 }
1539         }
1540
1541         LOG_ERROR("%d is not a supported speed", speed);
1542         return(ERROR_FAIL);
1543 }
1544
1545
1546 static
1547 int rlink_khz(
1548                 int khz,
1549                 int *speed
1550 ) {
1551         int     i;
1552
1553         if (khz == 0) {
1554                 LOG_ERROR("RCLK not supported");
1555                 return ERROR_FAIL;
1556         }
1557
1558         for (i = rlink_speed_table_size; i--;) {
1559                 if (rlink_speed_table[i].khz <= khz) {
1560                         *speed = rlink_speed_table[i].prescaler;
1561                         return(ERROR_OK);
1562                 }
1563         }
1564
1565         LOG_WARNING("The lowest supported JTAG speed is %d KHz", rlink_speed_table[0].khz);
1566         *speed = rlink_speed_table[0].prescaler;
1567         return(ERROR_OK);
1568 }
1569
1570
1571 static
1572 int rlink_init(void)
1573 {
1574         int i, j, retries;
1575         uint8_t reply_buffer[USB_EP1IN_SIZE];
1576
1577         usb_init();
1578         const uint16_t vids[] = { USB_IDVENDOR, 0 };
1579         const uint16_t pids[] = { USB_IDPRODUCT, 0 };
1580         if (jtag_usb_open(vids, pids, &pHDev) != ERROR_OK)
1581                 return ERROR_FAIL;
1582
1583         struct usb_device *dev = usb_device(pHDev);
1584         if (dev->descriptor.bNumConfigurations > 1)
1585         {
1586                 LOG_ERROR("Whoops! NumConfigurations is not 1, don't know what to do...");
1587                 return ERROR_FAIL;
1588         }
1589         if (dev->config->bNumInterfaces > 1)
1590         {
1591                 LOG_ERROR("Whoops! NumInterfaces is not 1, don't know what to do...");
1592                 return ERROR_FAIL;
1593         }
1594
1595         LOG_DEBUG("Opened device, pHDev = %p", pHDev);
1596
1597         /* usb_set_configuration required under win32 */
1598         usb_set_configuration(pHDev, dev->config[0].bConfigurationValue);
1599
1600         retries = 3;
1601         do
1602         {
1603                 i = usb_claim_interface(pHDev,0);
1604                 if (i)
1605                 {
1606                         LOG_ERROR("usb_claim_interface: %s", usb_strerror());
1607 #ifdef LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP
1608                         j = usb_detach_kernel_driver_np(pHDev, 0);
1609                         if (j)
1610                                 LOG_ERROR("detach kernel driver: %s", usb_strerror());
1611 #endif
1612                 }
1613                 else
1614                 {
1615                         LOG_DEBUG("interface claimed!");
1616                         break;
1617                 }
1618         } while (--retries);
1619
1620         if (i)
1621         {
1622                 LOG_ERROR("Initialisation failed.");
1623                 return ERROR_FAIL;
1624         }
1625         if (usb_set_altinterface(pHDev,0) != 0)
1626         {
1627                 LOG_ERROR("Failed to set interface.");
1628                 return ERROR_FAIL;
1629         }
1630
1631         /* The device starts out in an unknown state on open.  As such,
1632          * result reads time out, and it's not even known whether the
1633          * command was accepted.  So, for this first command, we issue
1634          * it repeatedly until its response doesn't time out.  Also, if
1635          * sending a command is going to time out, we find that out here.
1636          *
1637          * It must be possible to open the device in such a way that
1638          * this special magic isn't needed, but, so far, it escapes us.
1639          */
1640         for (i = 0; i < 5; i++) {
1641                 j = ep1_generic_commandl(
1642                                 pHDev, 1,
1643                                 EP1_CMD_GET_FWREV
1644                 );
1645                 if (j < USB_EP1OUT_SIZE) {
1646                         LOG_ERROR("USB write error: %s", usb_strerror());
1647                         return(ERROR_FAIL);
1648                 }
1649                 j = usb_bulk_read(
1650                                 pHDev, USB_EP1IN_ADDR,
1651                                 (char *)reply_buffer, sizeof(reply_buffer),
1652                                 200
1653                 );
1654                 if (j != -ETIMEDOUT) break;
1655         }
1656
1657         if (j < (int)sizeof(reply_buffer)) {
1658                 LOG_ERROR("USB read error: %s", usb_strerror());
1659                 return(ERROR_FAIL);
1660         }
1661         LOG_DEBUG(INTERFACE_NAME" firmware version: %d.%d.%d", reply_buffer[0], reply_buffer[1], reply_buffer[2]);
1662
1663         if ((reply_buffer[0] != 0) || (reply_buffer[1] != 0) || (reply_buffer[2] != 3)) {
1664                 LOG_WARNING("The rlink device is not of the version that the developers have played with.  It may or may not work.");
1665         }
1666
1667         /* Probe port E for adapter presence */
1668         ep1_generic_commandl(
1669                         pHDev, 16,
1670                         EP1_CMD_MEMORY_WRITE,   /* Drive sense pin with 0 */
1671                         ST7_PEDR >> 8,
1672                         ST7_PEDR,
1673                         3,
1674                         0x00,                                           /* DR */
1675                         ST7_PE_ADAPTER_SENSE_OUT,       /* DDR */
1676                         ST7_PE_ADAPTER_SENSE_OUT,       /* OR */
1677                         EP1_CMD_MEMORY_READ,    /* Read back */
1678                         ST7_PEDR >> 8,
1679                         ST7_PEDR,
1680                         1,
1681                         EP1_CMD_MEMORY_WRITE,   /* Drive sense pin with 1 */
1682                         ST7_PEDR >> 8,
1683                         ST7_PEDR,
1684                         1,
1685                         ST7_PE_ADAPTER_SENSE_OUT
1686         );
1687
1688         usb_bulk_read(
1689                         pHDev, USB_EP1IN_ADDR,
1690                         (char *)reply_buffer, 1,
1691                         USB_TIMEOUT_MS
1692         );
1693
1694         if ((reply_buffer[0] & ST7_PE_ADAPTER_SENSE_IN) != 0) {
1695                 LOG_WARNING("target detection problem");
1696         }
1697
1698         ep1_generic_commandl(
1699                         pHDev, 11,
1700                         EP1_CMD_MEMORY_READ,    /* Read back */
1701                         ST7_PEDR >> 8,
1702                         ST7_PEDR,
1703                         1,
1704                         EP1_CMD_MEMORY_WRITE,   /* float port E */
1705                         ST7_PEDR >> 8,
1706                         ST7_PEDR,
1707                         3,
1708                         0x00,   /* DR */
1709                         0x00,   /* DDR */
1710                         0x00    /* OR */
1711         );
1712
1713         usb_bulk_read(
1714                         pHDev, USB_EP1IN_ADDR,
1715                         (char *)reply_buffer, 1,
1716                         USB_TIMEOUT_MS
1717         );
1718
1719
1720         if ((reply_buffer[0] & ST7_PE_ADAPTER_SENSE_IN) == 0) {
1721                 LOG_WARNING("target not plugged in");
1722         }
1723
1724         /* float ports A and B */
1725         ep1_generic_commandl(
1726                         pHDev, 11,
1727                         EP1_CMD_MEMORY_WRITE,
1728                         ST7_PADDR >> 8,
1729                         ST7_PADDR,
1730                         2,
1731                         0x00,
1732                         0x00,
1733                         EP1_CMD_MEMORY_WRITE,
1734                         ST7_PBDDR >> 8,
1735                         ST7_PBDDR,
1736                         1,
1737                         0x00
1738         );
1739
1740         /* make sure DTC is stopped, set VPP control, set up ports A and B */
1741         ep1_generic_commandl(
1742                         pHDev, 14,
1743                         EP1_CMD_DTC_STOP,
1744                         EP1_CMD_SET_PORTD_VPP,
1745                         ~(ST7_PD_VPP_SHDN),
1746                         EP1_CMD_MEMORY_WRITE,
1747                         ST7_PADR >> 8,
1748                         ST7_PADR,
1749                         2,
1750                         ((~(0)) & (ST7_PA_NTRST)),
1751                         (ST7_PA_NTRST),
1752                         /* port B has no OR, and we want to emulate open drain on NSRST, so we set DR to 0 here and later assert NSRST by setting DDR bit to 1. */
1753                         EP1_CMD_MEMORY_WRITE,
1754                         ST7_PBDR >> 8,
1755                         ST7_PBDR,
1756                         1,
1757                         0x00
1758         );
1759
1760         /* set LED updating mode and make sure they're unlit */
1761         ep1_generic_commandl(
1762                         pHDev, 3,
1763 #ifdef AUTOMATIC_BUSY_LED
1764                         EP1_CMD_LEDUE_BUSY,
1765 #else
1766                         EP1_CMD_LEDUE_NONE,
1767 #endif
1768                         EP1_CMD_SET_PORTD_LEDS,
1769                         ~0
1770         );
1771
1772         tap_state_queue_init();
1773         dtc_queue_init();
1774         rlink_reset(0, 0);
1775
1776         return ERROR_OK;
1777 }
1778
1779
1780 static
1781 int rlink_quit(void)
1782 {
1783         /* stop DTC and make sure LEDs are off */
1784         ep1_generic_commandl(
1785                         pHDev, 6,
1786                         EP1_CMD_DTC_STOP,
1787                         EP1_CMD_LEDUE_NONE,
1788                         EP1_CMD_SET_PORTD_LEDS,
1789                         ~0,
1790                         EP1_CMD_SET_PORTD_VPP,
1791                         ~0
1792         );
1793
1794         usb_release_interface(pHDev,0);
1795         usb_close(pHDev);
1796
1797
1798         return ERROR_OK;
1799 }
1800
1801
1802 struct jtag_interface rlink_interface =
1803 {
1804                 .name = "rlink",
1805                 .init = rlink_init,
1806                 .quit = rlink_quit,
1807                 .speed = rlink_speed,
1808                 .speed_div = rlink_speed_div,
1809                 .khz = rlink_khz,
1810                 .execute_queue = rlink_execute_queue,
1811 };