ft2232: implement TMS sequence command
[fw/openocd] / src / jtag / drivers / ft2232.c
1 /***************************************************************************
2 *   Copyright (C) 2009 by Øyvind Harboe                                   *
3 *       Øyvind Harboe <oyvind.harboe@zylin.com>                               *
4 *                                                                         *
5 *   Copyright (C) 2009 by SoftPLC Corporation.  http://softplc.com        *
6 *       Dick Hollenbeck <dick@softplc.com>                                    *
7 *                                                                         *
8 *   Copyright (C) 2004, 2006 by Dominic Rath                              *
9 *   Dominic.Rath@gmx.de                                                   *
10 *                                                                         *
11 *   Copyright (C) 2008 by Spencer Oliver                                  *
12 *   spen@spen-soft.co.uk                                                  *
13 *                                                                         *
14 *   This program is free software; you can redistribute it and/or modify  *
15 *   it under the terms of the GNU General Public License as published by  *
16 *   the Free Software Foundation; either version 2 of the License, or     *
17 *   (at your option) any later version.                                   *
18 *                                                                         *
19 *   This program is distributed in the hope that it will be useful,       *
20 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
21 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
22 *   GNU General Public License for more details.                          *
23 *                                                                         *
24 *   You should have received a copy of the GNU General Public License     *
25 *   along with this program; if not, write to the                         *
26 *   Free Software Foundation, Inc.,                                       *
27 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
28 ***************************************************************************/
29
30 /**
31  * @file
32  * JTAG adapters based on the FT2232 full and high speed USB parts are
33  * popular low cost JTAG debug solutions.  Many FT2232 based JTAG adapters
34  * are discrete, but development boards may integrate them as alternatives
35  * to more capable (and expensive) third party JTAG pods.  Since JTAG uses
36  * only one of the two ports on these devices, on integrated boards the
37  * second port often serves as a USB-to-serial adapter for the target's
38  * console UART even when the JTAG port is not in use.  (Systems which
39  * support ARM's SWD in addition to JTAG, or instead of it, may use that
40  * second port for reading SWV trace data.)
41  *
42  * FT2232 based JTAG adapters are "dumb" not "smart", because most JTAG
43  * request/response interactions involve round trips over the USB link.
44  * A "smart" JTAG adapter has intelligence close to the scan chain, so it
45  * can for example poll quickly for a status change (usually taking on the
46  * order of microseconds not milliseconds) before beginning a queued
47  * transaction which require the previous one to have completed.
48  *
49  * There are dozens of adapters of this type, differing in details which
50  * this driver needs to understand.  Those "layout" details are required
51  * as part of FT2232 driver configuration.
52  *
53  * This code uses information contained in the MPSSE specification which was
54  * found here:
55  * http://www.ftdichip.com/Documents/AppNotes/AN2232C-01_MPSSE_Cmnd.pdf
56  * Hereafter this is called the "MPSSE Spec".
57  *
58  * The datasheet for the ftdichip.com's FT2232D part is here:
59  * http://www.ftdichip.com/Documents/DataSheets/DS_FT2232D.pdf
60  *
61  * Also note the issue with code 0x4b (clock data to TMS) noted in
62  * http://developer.intra2net.com/mailarchive/html/libftdi/2009/msg00292.html
63  * which can affect longer JTAG state paths.
64  */
65
66 #ifdef HAVE_CONFIG_H
67 #include "config.h"
68 #endif
69
70 /* project specific includes */
71 #include <jtag/interface.h>
72 #include <helper/time_support.h>
73
74 #if IS_CYGWIN == 1
75 #include <windows.h>
76 #endif
77
78 #include <assert.h>
79
80 #if (BUILD_FT2232_FTD2XX == 1 && BUILD_FT2232_LIBFTDI == 1)
81 #error "BUILD_FT2232_FTD2XX && BUILD_FT2232_LIBFTDI are mutually exclusive"
82 #elif (BUILD_FT2232_FTD2XX != 1 && BUILD_FT2232_LIBFTDI != 1)
83 #error "BUILD_FT2232_FTD2XX || BUILD_FT2232_LIBFTDI must be chosen"
84 #endif
85
86 /* FT2232 access library includes */
87 #if BUILD_FT2232_FTD2XX == 1
88 #include <ftd2xx.h>
89 #elif BUILD_FT2232_LIBFTDI == 1
90 #include <ftdi.h>
91 #endif
92
93 /* max TCK for the high speed devices 30000 kHz */
94 #define FTDI_2232H_4232H_MAX_TCK        30000
95 /* max TCK for the full speed devices 6000 kHz */
96 #define FTDI_2232C_MAX_TCK 6000
97 /* this speed value tells that RTCK is requested */
98 #define RTCK_SPEED -1
99
100 /*
101  * On my Athlon XP 1900+ EHCI host with FT2232H JTAG dongle I get read timeout
102  * errors with a retry count of 100. Increasing it solves the problem for me.
103  *      - Dimitar
104  *
105  * FIXME There's likely an issue with the usb_read_timeout from libftdi.
106  * Fix that (libusb? kernel? libftdi? here?) and restore the retry count
107  * to something sane.
108  */
109 #define LIBFTDI_READ_RETRY_COUNT                2000
110
111 #ifndef BUILD_FT2232_HIGHSPEED
112  #if BUILD_FT2232_FTD2XX == 1
113         enum { FT_DEVICE_2232H = 6, FT_DEVICE_4232H };
114  #elif BUILD_FT2232_LIBFTDI == 1
115         enum { TYPE_2232H = 4, TYPE_4232H = 5 };
116  #endif
117 #endif
118
119 /**
120  * Send out \a num_cycles on the TCK line while the TAP(s) are in a
121  * stable state.  Calling code must ensure that current state is stable,
122  * that verification is not done in here.
123  *
124  * @param num_cycles The number of clocks cycles to send.
125  * @param cmd The command to send.
126  *
127  * @returns ERROR_OK on success, or ERROR_JTAG_QUEUE_FAILED on failure.
128  */
129 static int ft2232_stableclocks(int num_cycles, struct jtag_command* cmd);
130
131 static char *       ft2232_device_desc_A = NULL;
132 static char*        ft2232_device_desc = NULL;
133 static char*        ft2232_serial  = NULL;
134 static char*        ft2232_layout  = NULL;
135 static uint8_t          ft2232_latency = 2;
136 static unsigned         ft2232_max_tck = FTDI_2232C_MAX_TCK;
137
138 #define MAX_USB_IDS 8
139 /* vid = pid = 0 marks the end of the list */
140 static uint16_t ft2232_vid[MAX_USB_IDS + 1] = { 0x0403, 0 };
141 static uint16_t ft2232_pid[MAX_USB_IDS + 1] = { 0x6010, 0 };
142
143 struct ft2232_layout {
144         char* name;
145         int (*init)(void);
146         void (*reset)(int trst, int srst);
147         void (*blink)(void);
148         int channel;
149 };
150
151 /* init procedures for supported layouts */
152 static int usbjtag_init(void);
153 static int jtagkey_init(void);
154 static int olimex_jtag_init(void);
155 static int flyswatter_init(void);
156 static int turtle_init(void);
157 static int comstick_init(void);
158 static int stm32stick_init(void);
159 static int axm0432_jtag_init(void);
160 static int sheevaplug_init(void);
161 static int icebear_jtag_init(void);
162 static int cortino_jtag_init(void);
163 static int signalyzer_h_init(void);
164 static int ktlink_init(void);
165
166 /* reset procedures for supported layouts */
167 static void usbjtag_reset(int trst, int srst);
168 static void jtagkey_reset(int trst, int srst);
169 static void olimex_jtag_reset(int trst, int srst);
170 static void flyswatter_reset(int trst, int srst);
171 static void turtle_reset(int trst, int srst);
172 static void comstick_reset(int trst, int srst);
173 static void stm32stick_reset(int trst, int srst);
174 static void axm0432_jtag_reset(int trst, int srst);
175 static void sheevaplug_reset(int trst, int srst);
176 static void icebear_jtag_reset(int trst, int srst);
177 static void signalyzer_h_reset(int trst, int srst);
178 static void ktlink_reset(int trst, int srst);
179
180 /* blink procedures for layouts that support a blinking led */
181 static void olimex_jtag_blink(void);
182 static void flyswatter_jtag_blink(void);
183 static void turtle_jtag_blink(void);
184 static void signalyzer_h_blink(void);
185 static void ktlink_blink(void);
186
187 static const struct ft2232_layout  ft2232_layouts[] =
188 {
189         { .name = "usbjtag",
190                 .init = usbjtag_init,
191                 .reset = usbjtag_reset,
192         },
193         { .name = "jtagkey",
194                 .init = jtagkey_init,
195                 .reset = jtagkey_reset,
196         },
197         { .name = "jtagkey_prototype_v1",
198                 .init = jtagkey_init,
199                 .reset = jtagkey_reset,
200         },
201         { .name = "oocdlink",
202                 .init = jtagkey_init,
203                 .reset = jtagkey_reset,
204         },
205         { .name = "signalyzer",
206                 .init = usbjtag_init,
207                 .reset = usbjtag_reset,
208         },
209         { .name = "evb_lm3s811",
210                 .init = usbjtag_init,
211                 .reset = usbjtag_reset,
212         },
213         { .name = "luminary_icdi",
214                 .init = usbjtag_init,
215                 .reset = usbjtag_reset,
216         },
217         { .name = "olimex-jtag",
218                 .init = olimex_jtag_init,
219                 .reset = olimex_jtag_reset,
220                 .blink = olimex_jtag_blink
221         },
222         { .name = "flyswatter",
223                 .init = flyswatter_init,
224                 .reset = flyswatter_reset,
225                 .blink = flyswatter_jtag_blink
226         },
227         { .name = "turtelizer2",
228                 .init = turtle_init,
229                 .reset = turtle_reset,
230                 .blink = turtle_jtag_blink
231         },
232         { .name = "comstick",
233                 .init = comstick_init,
234                 .reset = comstick_reset,
235         },
236         { .name = "stm32stick",
237                 .init = stm32stick_init,
238                 .reset = stm32stick_reset,
239         },
240         { .name = "axm0432_jtag",
241                 .init = axm0432_jtag_init,
242                 .reset = axm0432_jtag_reset,
243         },
244         { .name = "sheevaplug",
245                 .init = sheevaplug_init,
246                 .reset = sheevaplug_reset,
247         },
248         { .name = "icebear",
249                 .init = icebear_jtag_init,
250                 .reset = icebear_jtag_reset,
251         },
252         { .name = "cortino",
253                 .init = cortino_jtag_init,
254                 .reset = comstick_reset,
255         },
256         { .name = "signalyzer-h",
257                 .init = signalyzer_h_init,
258                 .reset = signalyzer_h_reset,
259                 .blink = signalyzer_h_blink
260         },
261         { .name = "ktlink",
262                 .init = ktlink_init,
263                 .reset = ktlink_reset,
264                 .blink = ktlink_blink
265         },
266         { .name = NULL, /* END OF TABLE */ },
267 };
268
269 static uint8_t                  nTRST, nTRSTnOE, nSRST, nSRSTnOE;
270
271 static const struct ft2232_layout *layout;
272 static uint8_t                  low_output     = 0x0;
273 static uint8_t                  low_direction  = 0x0;
274 static uint8_t                  high_output    = 0x0;
275 static uint8_t                  high_direction = 0x0;
276
277 #if BUILD_FT2232_FTD2XX == 1
278 static FT_HANDLE        ftdih = NULL;
279 static FT_DEVICE        ftdi_device = 0;
280 #elif BUILD_FT2232_LIBFTDI == 1
281 static struct ftdi_context ftdic;
282 static enum ftdi_chip_type ftdi_device;
283 #endif
284
285 static struct jtag_command* first_unsent;        /* next command that has to be sent */
286 static int             require_send;
287
288 /*      http://urjtag.wiki.sourceforge.net/Cable + FT2232 says:
289
290         "There is a significant difference between libftdi and libftd2xx. The latter
291         one allows to schedule up to 64*64 bytes of result data while libftdi fails
292         with more than 4*64. As a consequence, the FT2232 driver is forced to
293         perform around 16x more USB transactions for long command streams with TDO
294         capture when running with libftdi."
295
296         No idea how we get
297         #define FT2232_BUFFER_SIZE 131072
298         a comment would have been nice.
299 */
300
301 #define FT2232_BUFFER_SIZE 131072
302
303 static uint8_t*             ft2232_buffer = NULL;
304 static int             ft2232_buffer_size  = 0;
305 static int             ft2232_read_pointer = 0;
306 static int             ft2232_expect_read  = 0;
307
308 /**
309  * Function buffer_write
310  * writes a byte into the byte buffer, "ft2232_buffer", which must be sent later.
311  * @param val is the byte to send.
312  */
313 static inline void buffer_write(uint8_t val)
314 {
315         assert(ft2232_buffer);
316         assert((unsigned) ft2232_buffer_size < (unsigned) FT2232_BUFFER_SIZE);
317         ft2232_buffer[ft2232_buffer_size++] = val;
318 }
319
320 /**
321  * Function buffer_read
322  * returns a byte from the byte buffer.
323  */
324 static inline uint8_t buffer_read(void)
325 {
326         assert(ft2232_buffer);
327         assert(ft2232_read_pointer < ft2232_buffer_size);
328         return ft2232_buffer[ft2232_read_pointer++];
329 }
330
331 /**
332  * Clocks out \a bit_count bits on the TMS line, starting with the least
333  * significant bit of tms_bits and progressing to more significant bits.
334  * Rigorous state transition logging is done here via tap_set_state().
335  *
336  * @param mpsse_cmd One of the MPSSE TMS oriented commands such as
337  *      0x4b or 0x6b.  See the MPSSE spec referenced above for their
338  *      functionality. The MPSSE command "Clock Data to TMS/CS Pin (no Read)"
339  *      is often used for this, 0x4b.
340  *
341  * @param tms_bits Holds the sequence of bits to send.
342  * @param tms_count Tells how many bits in the sequence.
343  * @param tdi_bit A single bit to pass on to TDI before the first TCK
344  *      cycle and held static for the duration of TMS clocking.
345  *
346  * See the MPSSE spec referenced above.
347  */
348 static void clock_tms(uint8_t mpsse_cmd, int tms_bits, int tms_count, bool tdi_bit)
349 {
350         uint8_t tms_byte;
351         int     i;
352         int     tms_ndx;                                /* bit index into tms_byte */
353
354         assert(tms_count > 0);
355
356         DEBUG_JTAG_IO("mpsse cmd=%02x, tms_bits = 0x%08x, bit_count=%d",
357                         mpsse_cmd, tms_bits, tms_count);
358
359         for (tms_byte = tms_ndx = i = 0;   i < tms_count;   ++i, tms_bits>>=1)
360         {
361                 bool bit = tms_bits & 1;
362
363                 if (bit)
364                         tms_byte |= (1 << tms_ndx);
365
366                 /* always do state transitions in public view */
367                 tap_set_state(tap_state_transition(tap_get_state(), bit));
368
369                 /*      we wrote a bit to tms_byte just above, increment bit index.  if bit was zero
370                         also increment.
371                 */
372                 ++tms_ndx;
373
374                 if (tms_ndx == 7  || i == tms_count-1)
375                 {
376                         buffer_write(mpsse_cmd);
377                         buffer_write(tms_ndx - 1);
378
379                         /*      Bit 7 of the byte is passed on to TDI/DO before the first TCK/SK of
380                                 TMS/CS and is held static for the duration of TMS/CS clocking.
381                         */
382                         buffer_write(tms_byte | (tdi_bit << 7));
383                 }
384         }
385 }
386
387 /**
388  * Function get_tms_buffer_requirements
389  * returns what clock_tms() will consume if called with
390  * same \a bit_count.
391  */
392 static inline int get_tms_buffer_requirements(int bit_count)
393 {
394         return ((bit_count + 6)/7) * 3;
395 }
396
397 /**
398  * Function move_to_state
399  * moves the TAP controller from the current state to a
400  * \a goal_state through a path given by tap_get_tms_path().  State transition
401  * logging is performed by delegation to clock_tms().
402  *
403  * @param goal_state is the destination state for the move.
404  */
405 static void move_to_state(tap_state_t goal_state)
406 {
407         tap_state_t     start_state = tap_get_state();
408
409         /*      goal_state is 1/2 of a tuple/pair of states which allow convenient
410                 lookup of the required TMS pattern to move to this state from the
411                 start state.
412         */
413
414         /* do the 2 lookups */
415         int tms_bits  = tap_get_tms_path(start_state, goal_state);
416         int tms_count = tap_get_tms_path_len(start_state, goal_state);
417
418         DEBUG_JTAG_IO("start=%s goal=%s", tap_state_name(start_state), tap_state_name(goal_state));
419
420         clock_tms(0x4b,  tms_bits, tms_count, 0);
421 }
422
423 static int ft2232_write(uint8_t* buf, int size, uint32_t* bytes_written)
424 {
425 #if BUILD_FT2232_FTD2XX == 1
426         FT_STATUS status;
427         DWORD dw_bytes_written;
428         if ((status = FT_Write(ftdih, buf, size, &dw_bytes_written)) != FT_OK)
429         {
430                 *bytes_written = dw_bytes_written;
431                 LOG_ERROR("FT_Write returned: %lu", status);
432                 return ERROR_JTAG_DEVICE_ERROR;
433         }
434         else
435         {
436                 *bytes_written = dw_bytes_written;
437                 return ERROR_OK;
438         }
439 #elif BUILD_FT2232_LIBFTDI == 1
440         int retval;
441         if ((retval = ftdi_write_data(&ftdic, buf, size)) < 0)
442         {
443                 *bytes_written = 0;
444                 LOG_ERROR("ftdi_write_data: %s", ftdi_get_error_string(&ftdic));
445                 return ERROR_JTAG_DEVICE_ERROR;
446         }
447         else
448         {
449                 *bytes_written = retval;
450                 return ERROR_OK;
451         }
452 #endif
453 }
454
455 static int ft2232_read(uint8_t* buf, uint32_t size, uint32_t* bytes_read)
456 {
457 #if BUILD_FT2232_FTD2XX == 1
458         DWORD dw_bytes_read;
459         FT_STATUS status;
460         int timeout = 5;
461         *bytes_read = 0;
462
463         while ((*bytes_read < size) && timeout--)
464         {
465                 if ((status = FT_Read(ftdih, buf + *bytes_read, size -
466                                           *bytes_read, &dw_bytes_read)) != FT_OK)
467                 {
468                         *bytes_read = 0;
469                         LOG_ERROR("FT_Read returned: %lu", status);
470                         return ERROR_JTAG_DEVICE_ERROR;
471                 }
472                 *bytes_read += dw_bytes_read;
473         }
474
475 #elif BUILD_FT2232_LIBFTDI == 1
476         int retval;
477         int timeout = LIBFTDI_READ_RETRY_COUNT;
478         *bytes_read = 0;
479
480         while ((*bytes_read < size) && timeout--)
481         {
482                 if ((retval = ftdi_read_data(&ftdic, buf + *bytes_read, size - *bytes_read)) < 0)
483                 {
484                         *bytes_read = 0;
485                         LOG_ERROR("ftdi_read_data: %s", ftdi_get_error_string(&ftdic));
486                         return ERROR_JTAG_DEVICE_ERROR;
487                 }
488                 *bytes_read += retval;
489         }
490
491 #endif
492
493         if (*bytes_read < size)
494         {
495                 LOG_ERROR("couldn't read enough bytes from "
496                                 "FT2232 device (%i < %i)",
497                                 (unsigned)*bytes_read,
498                                 (unsigned)size);
499                 return ERROR_JTAG_DEVICE_ERROR;
500         }
501
502         return ERROR_OK;
503 }
504
505 static bool ft2232_device_is_highspeed(void)
506 {
507 #if BUILD_FT2232_FTD2XX == 1
508         return (ftdi_device == FT_DEVICE_2232H) || (ftdi_device == FT_DEVICE_4232H);
509 #elif BUILD_FT2232_LIBFTDI == 1
510         return (ftdi_device == TYPE_2232H || ftdi_device == TYPE_4232H);
511 #endif
512 }
513
514 /*
515  * Commands that only apply to the FT2232H and FT4232H devices.
516  * See chapter 6 in http://www.ftdichip.com/Documents/AppNotes/
517  * AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf
518  */
519
520 static int ft2232h_ft4232h_adaptive_clocking(bool enable)
521 {
522         uint8_t buf = enable ? 0x96 : 0x97;
523         LOG_DEBUG("%2.2x", buf);
524
525         uint32_t bytes_written;
526         int retval = ft2232_write(&buf, 1, &bytes_written);
527         if ((ERROR_OK != retval) || (bytes_written != 1))
528         {
529                 LOG_ERROR("couldn't write command to %s adaptive clocking"
530                         , enable ? "enable" : "disable");
531                 return retval;
532         }
533
534         return ERROR_OK;
535 }
536
537 /**
538  * Enable/disable the clk divide by 5 of the 60MHz master clock.
539  * This result in a JTAG clock speed range of 91.553Hz-6MHz
540  * respective 457.763Hz-30MHz.
541  */
542 static int ft2232h_ft4232h_clk_divide_by_5(bool enable)
543 {
544         uint32_t bytes_written;
545         uint8_t buf = enable ?  0x8b : 0x8a;
546         int retval = ft2232_write(&buf, 1, &bytes_written);
547         if ((ERROR_OK != retval) || (bytes_written != 1))
548         {
549                 LOG_ERROR("couldn't write command to %s clk divide by 5"
550                         , enable ? "enable" : "disable");
551                 return ERROR_JTAG_INIT_FAILED;
552         }
553         ft2232_max_tck = enable ? FTDI_2232C_MAX_TCK : FTDI_2232H_4232H_MAX_TCK;
554         LOG_INFO("max TCK change to: %u kHz", ft2232_max_tck);
555
556         return ERROR_OK;
557 }
558
559 static int ft2232_speed(int speed)
560 {
561         uint8_t buf[3];
562         int retval;
563         uint32_t bytes_written;
564
565         retval = ERROR_OK;
566         bool enable_adaptive_clocking = (RTCK_SPEED == speed);
567         if (ft2232_device_is_highspeed())
568                 retval = ft2232h_ft4232h_adaptive_clocking(enable_adaptive_clocking);
569         else if (enable_adaptive_clocking)
570         {
571                 LOG_ERROR("ft2232 device %lu does not support RTCK"
572                         , (long unsigned int)ftdi_device);
573                 return ERROR_FAIL;
574         }
575
576         if ((enable_adaptive_clocking) || (ERROR_OK != retval))
577                 return retval;
578
579         buf[0] = 0x86;                                  /* command "set divisor" */
580         buf[1] = speed & 0xff;                  /* valueL (0 = 6MHz, 1 = 3MHz, 2 = 2.0MHz, ...*/
581         buf[2] = (speed >> 8) & 0xff;   /* valueH */
582
583         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
584         if (((retval = ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
585         {
586                 LOG_ERROR("couldn't set FT2232 TCK speed");
587                 return retval;
588         }
589
590         return ERROR_OK;
591 }
592
593 static int ft2232_speed_div(int speed, int* khz)
594 {
595         /* Take a look in the FT2232 manual,
596          * AN2232C-01 Command Processor for
597          * MPSSE and MCU Host Bus. Chapter 3.8 */
598
599         *khz = (RTCK_SPEED == speed) ? 0 : ft2232_max_tck / (1 + speed);
600
601         return ERROR_OK;
602 }
603
604 static int ft2232_khz(int khz, int* jtag_speed)
605 {
606         if (khz == 0)
607         {
608                 if (ft2232_device_is_highspeed())
609                 {
610                         *jtag_speed = RTCK_SPEED;
611                         return ERROR_OK;
612                 }
613                 else
614                 {
615                         LOG_DEBUG("RCLK not supported");
616                         return ERROR_FAIL;
617                 }
618         }
619
620         /* Take a look in the FT2232 manual,
621          * AN2232C-01 Command Processor for
622          * MPSSE and MCU Host Bus. Chapter 3.8
623          *
624          * We will calc here with a multiplier
625          * of 10 for better rounding later. */
626
627         /* Calc speed, (ft2232_max_tck / khz) - 1 */
628         /* Use 65000 for better rounding */
629         *jtag_speed = ((ft2232_max_tck*10) / khz) - 10;
630
631         /* Add 0.9 for rounding */
632         *jtag_speed += 9;
633
634         /* Calc real speed */
635         *jtag_speed = *jtag_speed / 10;
636
637         /* Check if speed is greater than 0 */
638         if (*jtag_speed < 0)
639         {
640                 *jtag_speed = 0;
641         }
642
643         /* Check max value */
644         if (*jtag_speed > 0xFFFF)
645         {
646                 *jtag_speed = 0xFFFF;
647         }
648
649         return ERROR_OK;
650 }
651
652 static void ft2232_end_state(tap_state_t state)
653 {
654         if (tap_is_state_stable(state))
655                 tap_set_end_state(state);
656         else
657         {
658                 LOG_ERROR("BUG: %s is not a stable end state", tap_state_name(state));
659                 exit(-1);
660         }
661 }
662
663 static void ft2232_read_scan(enum scan_type type, uint8_t* buffer, int scan_size)
664 {
665         int num_bytes = (scan_size + 7) / 8;
666         int bits_left = scan_size;
667         int cur_byte  = 0;
668
669         while (num_bytes-- > 1)
670         {
671                 buffer[cur_byte++] = buffer_read();
672                 bits_left -= 8;
673         }
674
675         buffer[cur_byte] = 0x0;
676
677         /* There is one more partial byte left from the clock data in/out instructions */
678         if (bits_left > 1)
679         {
680                 buffer[cur_byte] = buffer_read() >> 1;
681         }
682         /* This shift depends on the length of the clock data to tms instruction, insterted at end of the scan, now fixed to a two step transition in ft2232_add_scan */
683         buffer[cur_byte] = (buffer[cur_byte] | (((buffer_read()) << 1) & 0x80)) >> (8 - bits_left);
684 }
685
686 static void ft2232_debug_dump_buffer(void)
687 {
688         int i;
689         char line[256];
690         char* line_p = line;
691
692         for (i = 0; i < ft2232_buffer_size; i++)
693         {
694                 line_p += snprintf(line_p, 256 - (line_p - line), "%2.2x ", ft2232_buffer[i]);
695                 if (i % 16 == 15)
696                 {
697                         LOG_DEBUG("%s", line);
698                         line_p = line;
699                 }
700         }
701
702         if (line_p != line)
703                 LOG_DEBUG("%s", line);
704 }
705
706 static int ft2232_send_and_recv(struct jtag_command* first, struct jtag_command* last)
707 {
708         struct jtag_command* cmd;
709         uint8_t* buffer;
710         int scan_size;
711         enum scan_type  type;
712         int retval;
713         uint32_t bytes_written = 0;
714         uint32_t bytes_read = 0;
715
716 #ifdef _DEBUG_USB_IO_
717         struct timeval  start, inter, inter2, end;
718         struct timeval  d_inter, d_inter2, d_end;
719 #endif
720
721 #ifdef _DEBUG_USB_COMMS_
722         LOG_DEBUG("write buffer (size %i):", ft2232_buffer_size);
723         ft2232_debug_dump_buffer();
724 #endif
725
726 #ifdef _DEBUG_USB_IO_
727         gettimeofday(&start, NULL);
728 #endif
729
730         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
731         {
732                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
733                 return retval;
734         }
735
736 #ifdef _DEBUG_USB_IO_
737         gettimeofday(&inter, NULL);
738 #endif
739
740         if (ft2232_expect_read)
741         {
742                 /* FIXME this "timeout" is never changed ... */
743                 int timeout = LIBFTDI_READ_RETRY_COUNT;
744                 ft2232_buffer_size = 0;
745
746 #ifdef _DEBUG_USB_IO_
747                 gettimeofday(&inter2, NULL);
748 #endif
749
750                 if ((retval = ft2232_read(ft2232_buffer, ft2232_expect_read, &bytes_read)) != ERROR_OK)
751                 {
752                         LOG_ERROR("couldn't read from FT2232");
753                         return retval;
754                 }
755
756 #ifdef _DEBUG_USB_IO_
757                 gettimeofday(&end, NULL);
758
759                 timeval_subtract(&d_inter, &inter, &start);
760                 timeval_subtract(&d_inter2, &inter2, &start);
761                 timeval_subtract(&d_end, &end, &start);
762
763                 LOG_INFO("inter: %u.%06u, inter2: %u.%06u end: %u.%06u",
764                         (unsigned)d_inter.tv_sec, (unsigned)d_inter.tv_usec,
765                         (unsigned)d_inter2.tv_sec, (unsigned)d_inter2.tv_usec,
766                         (unsigned)d_end.tv_sec, (unsigned)d_end.tv_usec);
767 #endif
768
769                 ft2232_buffer_size = bytes_read;
770
771                 if (ft2232_expect_read != ft2232_buffer_size)
772                 {
773                         LOG_ERROR("ft2232_expect_read (%i) != "
774                                         "ft2232_buffer_size (%i) "
775                                         "(%i retries)",
776                                         ft2232_expect_read,
777                                         ft2232_buffer_size,
778                                         LIBFTDI_READ_RETRY_COUNT - timeout);
779                         ft2232_debug_dump_buffer();
780
781                         exit(-1);
782                 }
783
784 #ifdef _DEBUG_USB_COMMS_
785                 LOG_DEBUG("read buffer (%i retries): %i bytes",
786                                 LIBFTDI_READ_RETRY_COUNT - timeout,
787                                 ft2232_buffer_size);
788                 ft2232_debug_dump_buffer();
789 #endif
790         }
791
792         ft2232_expect_read  = 0;
793         ft2232_read_pointer = 0;
794
795         /* return ERROR_OK, unless a jtag_read_buffer returns a failed check
796          * that wasn't handled by a caller-provided error handler
797          */
798         retval = ERROR_OK;
799
800         cmd = first;
801         while (cmd != last)
802         {
803                 switch (cmd->type)
804                 {
805                 case JTAG_SCAN:
806                         type = jtag_scan_type(cmd->cmd.scan);
807                         if (type != SCAN_OUT)
808                         {
809                                 scan_size = jtag_scan_size(cmd->cmd.scan);
810                                 buffer    = calloc(DIV_ROUND_UP(scan_size, 8), 1);
811                                 ft2232_read_scan(type, buffer, scan_size);
812                                 if (jtag_read_buffer(buffer, cmd->cmd.scan) != ERROR_OK)
813                                         retval = ERROR_JTAG_QUEUE_FAILED;
814                                 free(buffer);
815                         }
816                         break;
817
818                 default:
819                         break;
820                 }
821
822                 cmd = cmd->next;
823         }
824
825         ft2232_buffer_size = 0;
826
827         return retval;
828 }
829
830 /**
831  * Function ft2232_add_pathmove
832  * moves the TAP controller from the current state to a new state through the
833  * given path, where path is an array of tap_state_t's.
834  *
835  * @param path is an array of tap_stat_t which gives the states to traverse through
836  *   ending with the last state at path[num_states-1]
837  * @param num_states is the count of state steps to move through
838  */
839 static void ft2232_add_pathmove(tap_state_t* path, int num_states)
840 {
841         int state_count = 0;
842
843         assert((unsigned) num_states <= 32u);           /* tms_bits only holds 32 bits */
844
845         DEBUG_JTAG_IO("-");
846
847         /* this loop verifies that the path is legal and logs each state in the path */
848         while (num_states)
849         {
850                 unsigned char   tms_byte = 0;       /* zero this on each MPSSE batch */
851                 int             bit_count = 0;
852                 int             num_states_batch = num_states > 7 ? 7 : num_states;
853
854                 /* command "Clock Data to TMS/CS Pin (no Read)" */
855                 buffer_write(0x4b);
856
857                 /* number of states remaining */
858                 buffer_write(num_states_batch - 1);
859
860                 while (num_states_batch--) {
861                         /* either TMS=0 or TMS=1 must work ... */
862                         if (tap_state_transition(tap_get_state(), false)
863                                                 == path[state_count])
864                                 buf_set_u32(&tms_byte, bit_count++, 1, 0x0);
865                         else if (tap_state_transition(tap_get_state(), true)
866                                                 == path[state_count])
867                                 buf_set_u32(&tms_byte, bit_count++, 1, 0x1);
868
869                         /* ... or else the caller goofed BADLY */
870                         else {
871                                 LOG_ERROR("BUG: %s -> %s isn't a valid "
872                                                 "TAP state transition",
873                                         tap_state_name(tap_get_state()),
874                                         tap_state_name(path[state_count]));
875                                 exit(-1);
876                         }
877
878                         tap_set_state(path[state_count]);
879                         state_count++;
880                         num_states--;
881                 }
882
883                 buffer_write(tms_byte);
884         }
885         tap_set_end_state(tap_get_state());
886 }
887
888 static void ft2232_add_scan(bool ir_scan, enum scan_type type, uint8_t* buffer, int scan_size)
889 {
890         int num_bytes = (scan_size + 7) / 8;
891         int bits_left = scan_size;
892         int cur_byte  = 0;
893         int last_bit;
894
895         if (!ir_scan)
896         {
897                 if (tap_get_state() != TAP_DRSHIFT)
898                 {
899                         move_to_state(TAP_DRSHIFT);
900                 }
901         }
902         else
903         {
904                 if (tap_get_state() != TAP_IRSHIFT)
905                 {
906                         move_to_state(TAP_IRSHIFT);
907                 }
908         }
909
910         /* add command for complete bytes */
911         while (num_bytes > 1)
912         {
913                 int thisrun_bytes;
914                 if (type == SCAN_IO)
915                 {
916                         /* Clock Data Bytes In and Out LSB First */
917                         buffer_write(0x39);
918                         /* LOG_DEBUG("added TDI bytes (io %i)", num_bytes); */
919                 }
920                 else if (type == SCAN_OUT)
921                 {
922                         /* Clock Data Bytes Out on -ve Clock Edge LSB First (no Read) */
923                         buffer_write(0x19);
924                         /* LOG_DEBUG("added TDI bytes (o)"); */
925                 }
926                 else if (type == SCAN_IN)
927                 {
928                         /* Clock Data Bytes In on +ve Clock Edge LSB First (no Write) */
929                         buffer_write(0x28);
930                         /* LOG_DEBUG("added TDI bytes (i %i)", num_bytes); */
931                 }
932
933                 thisrun_bytes = (num_bytes > 65537) ? 65536 : (num_bytes - 1);
934                 num_bytes    -= thisrun_bytes;
935
936                 buffer_write((uint8_t) (thisrun_bytes - 1));
937                 buffer_write((uint8_t) ((thisrun_bytes - 1) >> 8));
938
939                 if (type != SCAN_IN)
940                 {
941                         /* add complete bytes */
942                         while (thisrun_bytes-- > 0)
943                         {
944                                 buffer_write(buffer[cur_byte++]);
945                                 bits_left -= 8;
946                         }
947                 }
948                 else /* (type == SCAN_IN) */
949                 {
950                         bits_left -= 8 * (thisrun_bytes);
951                 }
952         }
953
954         /* the most signifcant bit is scanned during TAP movement */
955         if (type != SCAN_IN)
956                 last_bit = (buffer[cur_byte] >> (bits_left - 1)) & 0x1;
957         else
958                 last_bit = 0;
959
960         /* process remaining bits but the last one */
961         if (bits_left > 1)
962         {
963                 if (type == SCAN_IO)
964                 {
965                         /* Clock Data Bits In and Out LSB First */
966                         buffer_write(0x3b);
967                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
968                 }
969                 else if (type == SCAN_OUT)
970                 {
971                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
972                         buffer_write(0x1b);
973                         /* LOG_DEBUG("added TDI bits (o)"); */
974                 }
975                 else if (type == SCAN_IN)
976                 {
977                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
978                         buffer_write(0x2a);
979                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
980                 }
981
982                 buffer_write(bits_left - 2);
983                 if (type != SCAN_IN)
984                         buffer_write(buffer[cur_byte]);
985         }
986
987         if ((ir_scan && (tap_get_end_state() == TAP_IRSHIFT))
988           || (!ir_scan && (tap_get_end_state() == TAP_DRSHIFT)))
989         {
990                 if (type == SCAN_IO)
991                 {
992                         /* Clock Data Bits In and Out LSB First */
993                         buffer_write(0x3b);
994                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
995                 }
996                 else if (type == SCAN_OUT)
997                 {
998                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
999                         buffer_write(0x1b);
1000                         /* LOG_DEBUG("added TDI bits (o)"); */
1001                 }
1002                 else if (type == SCAN_IN)
1003                 {
1004                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
1005                         buffer_write(0x2a);
1006                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
1007                 }
1008                 buffer_write(0x0);
1009                 buffer_write(last_bit);
1010         }
1011         else
1012         {
1013                 int tms_bits;
1014                 int tms_count;
1015                 uint8_t mpsse_cmd;
1016
1017                 /* move from Shift-IR/DR to end state */
1018                 if (type != SCAN_OUT)
1019                 {
1020                         /* We always go to the PAUSE state in two step at the end of an IN or IO scan */
1021                         /* This must be coordinated with the bit shifts in ft2232_read_scan    */
1022                         tms_bits  = 0x01;
1023                         tms_count = 2;
1024                         /* Clock Data to TMS/CS Pin with Read */
1025                         mpsse_cmd = 0x6b;
1026                 }
1027                 else
1028                 {
1029                         tms_bits  = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1030                         tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1031                         /* Clock Data to TMS/CS Pin (no Read) */
1032                         mpsse_cmd = 0x4b;
1033                 }
1034
1035                 DEBUG_JTAG_IO("finish %s", (type == SCAN_OUT) ? "without read" : "via PAUSE");
1036                 clock_tms(mpsse_cmd, tms_bits, tms_count, last_bit);
1037         }
1038
1039         if (tap_get_state() != tap_get_end_state())
1040         {
1041                 move_to_state(tap_get_end_state());
1042         }
1043 }
1044
1045 static int ft2232_large_scan(struct scan_command* cmd, enum scan_type type, uint8_t* buffer, int scan_size)
1046 {
1047         int num_bytes = (scan_size + 7) / 8;
1048         int bits_left = scan_size;
1049         int cur_byte  = 0;
1050         int last_bit;
1051         uint8_t* receive_buffer  = malloc(DIV_ROUND_UP(scan_size, 8));
1052         uint8_t* receive_pointer = receive_buffer;
1053         uint32_t bytes_written;
1054         uint32_t bytes_read;
1055         int retval;
1056         int thisrun_read = 0;
1057
1058         if (cmd->ir_scan)
1059         {
1060                 LOG_ERROR("BUG: large IR scans are not supported");
1061                 exit(-1);
1062         }
1063
1064         if (tap_get_state() != TAP_DRSHIFT)
1065         {
1066                 move_to_state(TAP_DRSHIFT);
1067         }
1068
1069         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1070         {
1071                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
1072                 exit(-1);
1073         }
1074         LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1075                   ft2232_buffer_size, (int)bytes_written);
1076         ft2232_buffer_size = 0;
1077
1078         /* add command for complete bytes */
1079         while (num_bytes > 1)
1080         {
1081                 int thisrun_bytes;
1082
1083                 if (type == SCAN_IO)
1084                 {
1085                         /* Clock Data Bytes In and Out LSB First */
1086                         buffer_write(0x39);
1087                         /* LOG_DEBUG("added TDI bytes (io %i)", num_bytes); */
1088                 }
1089                 else if (type == SCAN_OUT)
1090                 {
1091                         /* Clock Data Bytes Out on -ve Clock Edge LSB First (no Read) */
1092                         buffer_write(0x19);
1093                         /* LOG_DEBUG("added TDI bytes (o)"); */
1094                 }
1095                 else if (type == SCAN_IN)
1096                 {
1097                         /* Clock Data Bytes In on +ve Clock Edge LSB First (no Write) */
1098                         buffer_write(0x28);
1099                         /* LOG_DEBUG("added TDI bytes (i %i)", num_bytes); */
1100                 }
1101
1102                 thisrun_bytes = (num_bytes > 65537) ? 65536 : (num_bytes - 1);
1103                 thisrun_read  = thisrun_bytes;
1104                 num_bytes    -= thisrun_bytes;
1105                 buffer_write((uint8_t) (thisrun_bytes - 1));
1106                 buffer_write((uint8_t) ((thisrun_bytes - 1) >> 8));
1107
1108                 if (type != SCAN_IN)
1109                 {
1110                         /* add complete bytes */
1111                         while (thisrun_bytes-- > 0)
1112                         {
1113                                 buffer_write(buffer[cur_byte]);
1114                                 cur_byte++;
1115                                 bits_left -= 8;
1116                         }
1117                 }
1118                 else /* (type == SCAN_IN) */
1119                 {
1120                         bits_left -= 8 * (thisrun_bytes);
1121                 }
1122
1123                 if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1124                 {
1125                         LOG_ERROR("couldn't write MPSSE commands to FT2232");
1126                         exit(-1);
1127                 }
1128                 LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1129                           ft2232_buffer_size,
1130                           (int)bytes_written);
1131                 ft2232_buffer_size = 0;
1132
1133                 if (type != SCAN_OUT)
1134                 {
1135                         if ((retval = ft2232_read(receive_pointer, thisrun_read, &bytes_read)) != ERROR_OK)
1136                         {
1137                                 LOG_ERROR("couldn't read from FT2232");
1138                                 exit(-1);
1139                         }
1140                         LOG_DEBUG("thisrun_read: %i, bytes_read: %i",
1141                                   thisrun_read,
1142                                   (int)bytes_read);
1143                         receive_pointer += bytes_read;
1144                 }
1145         }
1146
1147         thisrun_read = 0;
1148
1149         /* the most signifcant bit is scanned during TAP movement */
1150         if (type != SCAN_IN)
1151                 last_bit = (buffer[cur_byte] >> (bits_left - 1)) & 0x1;
1152         else
1153                 last_bit = 0;
1154
1155         /* process remaining bits but the last one */
1156         if (bits_left > 1)
1157         {
1158                 if (type == SCAN_IO)
1159                 {
1160                         /* Clock Data Bits In and Out LSB First */
1161                         buffer_write(0x3b);
1162                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
1163                 }
1164                 else if (type == SCAN_OUT)
1165                 {
1166                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
1167                         buffer_write(0x1b);
1168                         /* LOG_DEBUG("added TDI bits (o)"); */
1169                 }
1170                 else if (type == SCAN_IN)
1171                 {
1172                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
1173                         buffer_write(0x2a);
1174                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
1175                 }
1176                 buffer_write(bits_left - 2);
1177                 if (type != SCAN_IN)
1178                         buffer_write(buffer[cur_byte]);
1179
1180                 if (type != SCAN_OUT)
1181                         thisrun_read += 2;
1182         }
1183
1184         if (tap_get_end_state() == TAP_DRSHIFT)
1185         {
1186                 if (type == SCAN_IO)
1187                 {
1188                         /* Clock Data Bits In and Out LSB First */
1189                         buffer_write(0x3b);
1190                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
1191                 }
1192                 else if (type == SCAN_OUT)
1193                 {
1194                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
1195                         buffer_write(0x1b);
1196                         /* LOG_DEBUG("added TDI bits (o)"); */
1197                 }
1198                 else if (type == SCAN_IN)
1199                 {
1200                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
1201                         buffer_write(0x2a);
1202                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
1203                 }
1204                 buffer_write(0x0);
1205                 buffer_write(last_bit);
1206         }
1207         else
1208         {
1209                 int tms_bits  = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1210                 int tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1211                 uint8_t mpsse_cmd;
1212
1213                 /* move from Shift-IR/DR to end state */
1214                 if (type != SCAN_OUT)
1215                 {
1216                         /* Clock Data to TMS/CS Pin with Read */
1217                         mpsse_cmd = 0x6b;
1218                         /* LOG_DEBUG("added TMS scan (read)"); */
1219                 }
1220                 else
1221                 {
1222                         /* Clock Data to TMS/CS Pin (no Read) */
1223                         mpsse_cmd = 0x4b;
1224                         /* LOG_DEBUG("added TMS scan (no read)"); */
1225                 }
1226
1227                 DEBUG_JTAG_IO("finish, %s", (type == SCAN_OUT) ? "no read" : "read");
1228                 clock_tms(mpsse_cmd, tms_bits, tms_count, last_bit);
1229         }
1230
1231         if (type != SCAN_OUT)
1232                 thisrun_read += 1;
1233
1234         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1235         {
1236                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
1237                 exit(-1);
1238         }
1239         LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1240                   ft2232_buffer_size,
1241                   (int)bytes_written);
1242         ft2232_buffer_size = 0;
1243
1244         if (type != SCAN_OUT)
1245         {
1246                 if ((retval = ft2232_read(receive_pointer, thisrun_read, &bytes_read)) != ERROR_OK)
1247                 {
1248                         LOG_ERROR("couldn't read from FT2232");
1249                         exit(-1);
1250                 }
1251                 LOG_DEBUG("thisrun_read: %i, bytes_read: %i",
1252                           thisrun_read,
1253                           (int)bytes_read);
1254                 receive_pointer += bytes_read;
1255         }
1256
1257         return ERROR_OK;
1258 }
1259
1260 static int ft2232_predict_scan_out(int scan_size, enum scan_type type)
1261 {
1262         int predicted_size = 3;
1263         int num_bytes = (scan_size - 1) / 8;
1264
1265         if (tap_get_state() != TAP_DRSHIFT)
1266                 predicted_size += get_tms_buffer_requirements(tap_get_tms_path_len(tap_get_state(), TAP_DRSHIFT));
1267
1268         if (type == SCAN_IN)    /* only from device to host */
1269         {
1270                 /* complete bytes */
1271                 predicted_size += DIV_ROUND_UP(num_bytes, 65536) * 3;
1272
1273                 /* remaining bits - 1 (up to 7) */
1274                 predicted_size += ((scan_size - 1) % 8) ? 2 : 0;
1275         }
1276         else    /* host to device, or bidirectional */
1277         {
1278                 /* complete bytes */
1279                 predicted_size += num_bytes + DIV_ROUND_UP(num_bytes, 65536) * 3;
1280
1281                 /* remaining bits -1 (up to 7) */
1282                 predicted_size += ((scan_size - 1) % 8) ? 3 : 0;
1283         }
1284
1285         return predicted_size;
1286 }
1287
1288 static int ft2232_predict_scan_in(int scan_size, enum scan_type type)
1289 {
1290         int predicted_size = 0;
1291
1292         if (type != SCAN_OUT)
1293         {
1294                 /* complete bytes */
1295                 predicted_size += (DIV_ROUND_UP(scan_size, 8) > 1) ? (DIV_ROUND_UP(scan_size, 8) - 1) : 0;
1296
1297                 /* remaining bits - 1 */
1298                 predicted_size += ((scan_size - 1) % 8) ? 1 : 0;
1299
1300                 /* last bit (from TMS scan) */
1301                 predicted_size += 1;
1302         }
1303
1304         /* LOG_DEBUG("scan_size: %i, predicted_size: %i", scan_size, predicted_size); */
1305
1306         return predicted_size;
1307 }
1308
1309 static void usbjtag_reset(int trst, int srst)
1310 {
1311         enum reset_types jtag_reset_config = jtag_get_reset_config();
1312         if (trst == 1)
1313         {
1314                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1315                         low_direction |= nTRSTnOE;      /* switch to output pin (output is low) */
1316                 else
1317                         low_output &= ~nTRST;           /* switch output low */
1318         }
1319         else if (trst == 0)
1320         {
1321                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1322                         low_direction &= ~nTRSTnOE;     /* switch to input pin (high-Z + internal and external pullup) */
1323                 else
1324                         low_output |= nTRST;            /* switch output high */
1325         }
1326
1327         if (srst == 1)
1328         {
1329                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1330                         low_output &= ~nSRST;           /* switch output low */
1331                 else
1332                         low_direction |= nSRSTnOE;      /* switch to output pin (output is low) */
1333         }
1334         else if (srst == 0)
1335         {
1336                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1337                         low_output |= nSRST;            /* switch output high */
1338                 else
1339                         low_direction &= ~nSRSTnOE;     /* switch to input pin (high-Z) */
1340         }
1341
1342         /* command "set data bits low byte" */
1343         buffer_write(0x80);
1344         buffer_write(low_output);
1345         buffer_write(low_direction);
1346 }
1347
1348 static void jtagkey_reset(int trst, int srst)
1349 {
1350         enum reset_types jtag_reset_config = jtag_get_reset_config();
1351         if (trst == 1)
1352         {
1353                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1354                         high_output &= ~nTRSTnOE;
1355                 else
1356                         high_output &= ~nTRST;
1357         }
1358         else if (trst == 0)
1359         {
1360                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1361                         high_output |= nTRSTnOE;
1362                 else
1363                         high_output |= nTRST;
1364         }
1365
1366         if (srst == 1)
1367         {
1368                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1369                         high_output &= ~nSRST;
1370                 else
1371                         high_output &= ~nSRSTnOE;
1372         }
1373         else if (srst == 0)
1374         {
1375                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1376                         high_output |= nSRST;
1377                 else
1378                         high_output |= nSRSTnOE;
1379         }
1380
1381         /* command "set data bits high byte" */
1382         buffer_write(0x82);
1383         buffer_write(high_output);
1384         buffer_write(high_direction);
1385         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1386                         high_direction);
1387 }
1388
1389 static void olimex_jtag_reset(int trst, int srst)
1390 {
1391         enum reset_types jtag_reset_config = jtag_get_reset_config();
1392         if (trst == 1)
1393         {
1394                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1395                         high_output &= ~nTRSTnOE;
1396                 else
1397                         high_output &= ~nTRST;
1398         }
1399         else if (trst == 0)
1400         {
1401                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1402                         high_output |= nTRSTnOE;
1403                 else
1404                         high_output |= nTRST;
1405         }
1406
1407         if (srst == 1)
1408         {
1409                 high_output |= nSRST;
1410         }
1411         else if (srst == 0)
1412         {
1413                 high_output &= ~nSRST;
1414         }
1415
1416         /* command "set data bits high byte" */
1417         buffer_write(0x82);
1418         buffer_write(high_output);
1419         buffer_write(high_direction);
1420         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1421                         high_direction);
1422 }
1423
1424 static void axm0432_jtag_reset(int trst, int srst)
1425 {
1426         if (trst == 1)
1427         {
1428                 tap_set_state(TAP_RESET);
1429                 high_output &= ~nTRST;
1430         }
1431         else if (trst == 0)
1432         {
1433                 high_output |= nTRST;
1434         }
1435
1436         if (srst == 1)
1437         {
1438                 high_output &= ~nSRST;
1439         }
1440         else if (srst == 0)
1441         {
1442                 high_output |= nSRST;
1443         }
1444
1445         /* command "set data bits low byte" */
1446         buffer_write(0x82);
1447         buffer_write(high_output);
1448         buffer_write(high_direction);
1449         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1450                         high_direction);
1451 }
1452
1453 static void flyswatter_reset(int trst, int srst)
1454 {
1455         if (trst == 1)
1456         {
1457                 low_output &= ~nTRST;
1458         }
1459         else if (trst == 0)
1460         {
1461                 low_output |= nTRST;
1462         }
1463
1464         if (srst == 1)
1465         {
1466                 low_output |= nSRST;
1467         }
1468         else if (srst == 0)
1469         {
1470                 low_output &= ~nSRST;
1471         }
1472
1473         /* command "set data bits low byte" */
1474         buffer_write(0x80);
1475         buffer_write(low_output);
1476         buffer_write(low_direction);
1477         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
1478 }
1479
1480 static void turtle_reset(int trst, int srst)
1481 {
1482         trst = trst;
1483
1484         if (srst == 1)
1485         {
1486                 low_output |= nSRST;
1487         }
1488         else if (srst == 0)
1489         {
1490                 low_output &= ~nSRST;
1491         }
1492
1493         /* command "set data bits low byte" */
1494         buffer_write(0x80);
1495         buffer_write(low_output);
1496         buffer_write(low_direction);
1497         LOG_DEBUG("srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", srst, low_output, low_direction);
1498 }
1499
1500 static void comstick_reset(int trst, int srst)
1501 {
1502         if (trst == 1)
1503         {
1504                 high_output &= ~nTRST;
1505         }
1506         else if (trst == 0)
1507         {
1508                 high_output |= nTRST;
1509         }
1510
1511         if (srst == 1)
1512         {
1513                 high_output &= ~nSRST;
1514         }
1515         else if (srst == 0)
1516         {
1517                 high_output |= nSRST;
1518         }
1519
1520         /* command "set data bits high byte" */
1521         buffer_write(0x82);
1522         buffer_write(high_output);
1523         buffer_write(high_direction);
1524         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1525                         high_direction);
1526 }
1527
1528 static void stm32stick_reset(int trst, int srst)
1529 {
1530         if (trst == 1)
1531         {
1532                 high_output &= ~nTRST;
1533         }
1534         else if (trst == 0)
1535         {
1536                 high_output |= nTRST;
1537         }
1538
1539         if (srst == 1)
1540         {
1541                 low_output &= ~nSRST;
1542         }
1543         else if (srst == 0)
1544         {
1545                 low_output |= nSRST;
1546         }
1547
1548         /* command "set data bits low byte" */
1549         buffer_write(0x80);
1550         buffer_write(low_output);
1551         buffer_write(low_direction);
1552
1553         /* command "set data bits high byte" */
1554         buffer_write(0x82);
1555         buffer_write(high_output);
1556         buffer_write(high_direction);
1557         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1558                         high_direction);
1559 }
1560
1561 static void sheevaplug_reset(int trst, int srst)
1562 {
1563         if (trst == 1)
1564                 high_output &= ~nTRST;
1565         else if (trst == 0)
1566                 high_output |= nTRST;
1567
1568         if (srst == 1)
1569                 high_output &= ~nSRSTnOE;
1570         else if (srst == 0)
1571                 high_output |= nSRSTnOE;
1572
1573         /* command "set data bits high byte" */
1574         buffer_write(0x82);
1575         buffer_write(high_output);
1576         buffer_write(high_direction);
1577         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output, high_direction);
1578 }
1579
1580 static int ft2232_execute_runtest(struct jtag_command *cmd)
1581 {
1582         int retval;
1583         int i;
1584         int predicted_size = 0;
1585         retval = ERROR_OK;
1586
1587         DEBUG_JTAG_IO("runtest %i cycles, end in %s",
1588                         cmd->cmd.runtest->num_cycles,
1589                         tap_state_name(cmd->cmd.runtest->end_state));
1590
1591         /* only send the maximum buffer size that FT2232C can handle */
1592         predicted_size = 0;
1593         if (tap_get_state() != TAP_IDLE)
1594                 predicted_size += 3;
1595         predicted_size += 3 * DIV_ROUND_UP(cmd->cmd.runtest->num_cycles, 7);
1596         if (cmd->cmd.runtest->end_state != TAP_IDLE)
1597                 predicted_size += 3;
1598         if (tap_get_end_state() != TAP_IDLE)
1599                 predicted_size += 3;
1600         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1601         {
1602                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1603                         retval = ERROR_JTAG_QUEUE_FAILED;
1604                 require_send = 0;
1605                 first_unsent = cmd;
1606         }
1607         if (tap_get_state() != TAP_IDLE)
1608         {
1609                 move_to_state(TAP_IDLE);
1610                 require_send = 1;
1611         }
1612         i = cmd->cmd.runtest->num_cycles;
1613         while (i > 0)
1614         {
1615                 /* there are no state transitions in this code, so omit state tracking */
1616
1617                 /* command "Clock Data to TMS/CS Pin (no Read)" */
1618                 buffer_write(0x4b);
1619
1620                 /* scan 7 bits */
1621                 buffer_write((i > 7) ? 6 : (i - 1));
1622
1623                 /* TMS data bits */
1624                 buffer_write(0x0);
1625
1626                 i -= (i > 7) ? 7 : i;
1627                 /* LOG_DEBUG("added TMS scan (no read)"); */
1628         }
1629
1630         ft2232_end_state(cmd->cmd.runtest->end_state);
1631
1632         if (tap_get_state() != tap_get_end_state())
1633         {
1634                 move_to_state(tap_get_end_state());
1635         }
1636
1637         require_send = 1;
1638         DEBUG_JTAG_IO("runtest: %i, end in %s",
1639                         cmd->cmd.runtest->num_cycles,
1640                         tap_state_name(tap_get_end_state()));
1641         return retval;
1642 }
1643
1644 static int ft2232_execute_statemove(struct jtag_command *cmd)
1645 {
1646         int     predicted_size = 0;
1647         int     retval = ERROR_OK;
1648
1649         DEBUG_JTAG_IO("statemove end in %s",
1650                         tap_state_name(cmd->cmd.statemove->end_state));
1651
1652         /* only send the maximum buffer size that FT2232C can handle */
1653         predicted_size = 3;
1654         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1655         {
1656                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1657                         retval = ERROR_JTAG_QUEUE_FAILED;
1658                 require_send = 0;
1659                 first_unsent = cmd;
1660         }
1661         ft2232_end_state(cmd->cmd.statemove->end_state);
1662
1663         /* For TAP_RESET, ignore the current recorded state.  It's often
1664          * wrong at server startup, and this transation is critical whenever
1665          * it's requested.
1666          */
1667         if (tap_get_end_state() == TAP_RESET) {
1668                 clock_tms(0x4b,  0xff, 5, 0);
1669                 require_send = 1;
1670
1671         /* shortest-path move to desired end state */
1672         } else if (tap_get_state() != tap_get_end_state())
1673         {
1674                 move_to_state(tap_get_end_state());
1675                 require_send = 1;
1676         }
1677
1678         return retval;
1679 }
1680
1681 /**
1682  * Clock a bunch of TMS (or SWDIO) transitions, to change the JTAG
1683  * (or SWD) state machine.
1684  */
1685 static int ft2232_execute_tms(struct jtag_command *cmd)
1686 {
1687         int             retval = ERROR_OK;
1688         unsigned        num_bits = cmd->cmd.tms->num_bits;
1689         const uint8_t   *bits = cmd->cmd.tms->bits;
1690         unsigned        count;
1691
1692         DEBUG_JTAG_IO("TMS: %d bits", num_bits);
1693
1694         /* only send the maximum buffer size that FT2232C can handle */
1695         count = 3 * DIV_ROUND_UP(num_bits, 4);
1696         if (ft2232_buffer_size + 3*count + 1 > FT2232_BUFFER_SIZE) {
1697                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1698                         retval = ERROR_JTAG_QUEUE_FAILED;
1699
1700                 require_send = 0;
1701                 first_unsent = cmd;
1702         }
1703
1704         /* Shift out in batches of at most 6 bits; there's a report of an
1705          * FT2232 bug in this area, where shifting exactly 7 bits can make
1706          * problems with TMS signaling for the last clock cycle:
1707          *
1708          *    http://developer.intra2net.com/mailarchive/html/
1709          *              libftdi/2009/msg00292.html
1710          *
1711          * Command 0x4b is: "Clock Data to TMS/CS Pin (no Read)"
1712          *
1713          * Note that pathmoves in JTAG are not often seven bits, so that
1714          * isn't a particularly likely situation outside of "special"
1715          * signaling such as switching between JTAG and SWD modes.
1716          */
1717         while (num_bits) {
1718                 if (num_bits <= 6) {
1719                         buffer_write(0x4b);
1720                         buffer_write(num_bits - 1);
1721                         buffer_write(*bits & 0x3f);
1722                         break;
1723                 }
1724
1725                 /* Yes, this is lazy ... we COULD shift out more data
1726                  * bits per operation, but doing it in nybbles is easy
1727                  */
1728                 buffer_write(0x4b);
1729                 buffer_write(3);
1730                 buffer_write(*bits & 0xf);
1731                 num_bits -= 4;
1732
1733                 count  = (num_bits > 4) ? 4 : num_bits;
1734
1735                 buffer_write(0x4b);
1736                 buffer_write(count - 1);
1737                 buffer_write((*bits >> 4) & 0xf);
1738                 num_bits -= count;
1739
1740                 bits++;
1741         }
1742
1743         require_send = 1;
1744         return retval;
1745 }
1746
1747 static int ft2232_execute_pathmove(struct jtag_command *cmd)
1748 {
1749         int     predicted_size = 0;
1750         int     retval = ERROR_OK;
1751
1752         tap_state_t*     path = cmd->cmd.pathmove->path;
1753         int     num_states    = cmd->cmd.pathmove->num_states;
1754
1755         DEBUG_JTAG_IO("pathmove: %i states, current: %s  end: %s", num_states,
1756                         tap_state_name(tap_get_state()),
1757                         tap_state_name(path[num_states-1]));
1758
1759         /* only send the maximum buffer size that FT2232C can handle */
1760         predicted_size = 3 * DIV_ROUND_UP(num_states, 7);
1761         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1762         {
1763                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1764                         retval = ERROR_JTAG_QUEUE_FAILED;
1765
1766                 require_send = 0;
1767                 first_unsent = cmd;
1768         }
1769
1770         ft2232_add_pathmove(path, num_states);
1771         require_send = 1;
1772
1773         return retval;
1774 }
1775
1776 static int ft2232_execute_scan(struct jtag_command *cmd)
1777 {
1778         uint8_t* buffer;
1779         int scan_size;                          /* size of IR or DR scan */
1780         int predicted_size = 0;
1781         int retval = ERROR_OK;
1782
1783         enum scan_type  type = jtag_scan_type(cmd->cmd.scan);
1784
1785         DEBUG_JTAG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN", type);
1786
1787         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
1788
1789         predicted_size = ft2232_predict_scan_out(scan_size, type);
1790         if ((predicted_size + 1) > FT2232_BUFFER_SIZE)
1791         {
1792                 LOG_DEBUG("oversized ft2232 scan (predicted_size > FT2232_BUFFER_SIZE)");
1793                 /* unsent commands before this */
1794                 if (first_unsent != cmd)
1795                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1796                                 retval = ERROR_JTAG_QUEUE_FAILED;
1797
1798                 /* current command */
1799                 ft2232_end_state(cmd->cmd.scan->end_state);
1800                 ft2232_large_scan(cmd->cmd.scan, type, buffer, scan_size);
1801                 require_send = 0;
1802                 first_unsent = cmd->next;
1803                 if (buffer)
1804                         free(buffer);
1805                 return retval;
1806         }
1807         else if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1808         {
1809                 LOG_DEBUG("ft2232 buffer size reached, sending queued commands (first_unsent: %p, cmd: %p)",
1810                                 first_unsent,
1811                                 cmd);
1812                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1813                         retval = ERROR_JTAG_QUEUE_FAILED;
1814                 require_send = 0;
1815                 first_unsent = cmd;
1816         }
1817         ft2232_expect_read += ft2232_predict_scan_in(scan_size, type);
1818         /* LOG_DEBUG("new read size: %i", ft2232_expect_read); */
1819         ft2232_end_state(cmd->cmd.scan->end_state);
1820         ft2232_add_scan(cmd->cmd.scan->ir_scan, type, buffer, scan_size);
1821         require_send = 1;
1822         if (buffer)
1823                 free(buffer);
1824         DEBUG_JTAG_IO("%s scan, %i bits, end in %s",
1825                         (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1826                         tap_state_name(tap_get_end_state()));
1827         return retval;
1828
1829 }
1830
1831 static int ft2232_execute_reset(struct jtag_command *cmd)
1832 {
1833         int retval;
1834         int predicted_size = 0;
1835         retval = ERROR_OK;
1836
1837         DEBUG_JTAG_IO("reset trst: %i srst %i",
1838                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1839
1840         /* only send the maximum buffer size that FT2232C can handle */
1841         predicted_size = 3;
1842         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1843         {
1844                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1845                         retval = ERROR_JTAG_QUEUE_FAILED;
1846                 require_send = 0;
1847                 first_unsent = cmd;
1848         }
1849
1850         if ((cmd->cmd.reset->trst == 1) || (cmd->cmd.reset->srst && (jtag_get_reset_config() & RESET_SRST_PULLS_TRST)))
1851         {
1852                 tap_set_state(TAP_RESET);
1853         }
1854
1855         layout->reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1856         require_send = 1;
1857
1858         DEBUG_JTAG_IO("trst: %i, srst: %i",
1859                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1860         return retval;
1861 }
1862
1863 static int ft2232_execute_sleep(struct jtag_command *cmd)
1864 {
1865         int retval;
1866         retval = ERROR_OK;
1867
1868         DEBUG_JTAG_IO("sleep %" PRIi32, cmd->cmd.sleep->us);
1869
1870         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1871                                 retval = ERROR_JTAG_QUEUE_FAILED;
1872         first_unsent = cmd->next;
1873         jtag_sleep(cmd->cmd.sleep->us);
1874         DEBUG_JTAG_IO("sleep %" PRIi32 " usec while in %s",
1875                         cmd->cmd.sleep->us,
1876                         tap_state_name(tap_get_state()));
1877         return retval;
1878 }
1879
1880 static int ft2232_execute_stableclocks(struct jtag_command *cmd)
1881 {
1882         int retval;
1883         retval = ERROR_OK;
1884
1885         /* this is only allowed while in a stable state.  A check for a stable
1886          * state was done in jtag_add_clocks()
1887          */
1888         if (ft2232_stableclocks(cmd->cmd.stableclocks->num_cycles, cmd) != ERROR_OK)
1889                 retval = ERROR_JTAG_QUEUE_FAILED;
1890         DEBUG_JTAG_IO("clocks %i while in %s",
1891                         cmd->cmd.stableclocks->num_cycles,
1892                         tap_state_name(tap_get_state()));
1893         return retval;
1894 }
1895
1896 static int ft2232_execute_command(struct jtag_command *cmd)
1897 {
1898         int retval;
1899
1900         switch (cmd->type)
1901         {
1902         case JTAG_RESET:        retval = ft2232_execute_reset(cmd); break;
1903         case JTAG_RUNTEST:      retval = ft2232_execute_runtest(cmd); break;
1904         case JTAG_STATEMOVE: retval = ft2232_execute_statemove(cmd); break;
1905         case JTAG_PATHMOVE:     retval = ft2232_execute_pathmove(cmd); break;
1906         case JTAG_SCAN:         retval = ft2232_execute_scan(cmd); break;
1907         case JTAG_SLEEP:        retval = ft2232_execute_sleep(cmd); break;
1908         case JTAG_STABLECLOCKS: retval = ft2232_execute_stableclocks(cmd); break;
1909         case JTAG_TMS:
1910                 retval = ft2232_execute_tms(cmd);
1911                 break;
1912         default:
1913                 LOG_ERROR("BUG: unknown JTAG command type encountered");
1914                 retval = ERROR_JTAG_QUEUE_FAILED;
1915                 break;
1916         }
1917         return retval;
1918 }
1919
1920 static int ft2232_execute_queue(void)
1921 {
1922         struct jtag_command* cmd = jtag_command_queue;  /* currently processed command */
1923         int retval;
1924
1925         first_unsent = cmd;             /* next command that has to be sent */
1926         require_send = 0;
1927
1928         /* return ERROR_OK, unless ft2232_send_and_recv reports a failed check
1929          * that wasn't handled by a caller-provided error handler
1930          */
1931         retval = ERROR_OK;
1932
1933         ft2232_buffer_size = 0;
1934         ft2232_expect_read = 0;
1935
1936         /* blink, if the current layout has that feature */
1937         if (layout->blink)
1938                 layout->blink();
1939
1940         while (cmd)
1941         {
1942                 if (ft2232_execute_command(cmd) != ERROR_OK)
1943                         retval = ERROR_JTAG_QUEUE_FAILED;
1944                 /* Start reading input before FT2232 TX buffer fills up */
1945                 cmd = cmd->next;
1946                 if (ft2232_expect_read > 256)
1947                 {
1948                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1949                                 retval = ERROR_JTAG_QUEUE_FAILED;
1950                         first_unsent = cmd;
1951                 }
1952         }
1953
1954         if (require_send > 0)
1955                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1956                         retval = ERROR_JTAG_QUEUE_FAILED;
1957
1958         return retval;
1959 }
1960
1961 #if BUILD_FT2232_FTD2XX == 1
1962 static int ft2232_init_ftd2xx(uint16_t vid, uint16_t pid, int more, int* try_more)
1963 {
1964         FT_STATUS       status;
1965         DWORD           deviceID;
1966         char            SerialNumber[16];
1967         char            Description[64];
1968         DWORD   openex_flags  = 0;
1969         char*   openex_string = NULL;
1970         uint8_t latency_timer;
1971
1972         LOG_DEBUG("'ft2232' interface using FTD2XX with '%s' layout (%4.4x:%4.4x)", ft2232_layout, vid, pid);
1973
1974 #if IS_WIN32 == 0
1975         /* Add non-standard Vid/Pid to the linux driver */
1976         if ((status = FT_SetVIDPID(vid, pid)) != FT_OK)
1977         {
1978                 LOG_WARNING("couldn't add %4.4x:%4.4x", vid, pid);
1979         }
1980 #endif
1981
1982         if (ft2232_device_desc && ft2232_serial)
1983         {
1984                 LOG_WARNING("can't open by device description and serial number, giving precedence to serial");
1985                 ft2232_device_desc = NULL;
1986         }
1987
1988         if (ft2232_device_desc)
1989         {
1990                 openex_string = ft2232_device_desc;
1991                 openex_flags  = FT_OPEN_BY_DESCRIPTION;
1992         }
1993         else if (ft2232_serial)
1994         {
1995                 openex_string = ft2232_serial;
1996                 openex_flags  = FT_OPEN_BY_SERIAL_NUMBER;
1997         }
1998         else
1999         {
2000                 LOG_ERROR("neither device description nor serial number specified");
2001                 LOG_ERROR("please add \"ft2232_device_desc <string>\" or \"ft2232_serial <string>\" to your .cfg file");
2002
2003                 return ERROR_JTAG_INIT_FAILED;
2004         }
2005
2006         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
2007         if (status != FT_OK) {
2008                 /* under Win32, the FTD2XX driver appends an "A" to the end
2009                  * of the description, if we tried by the desc, then
2010                  * try by the alternate "A" description. */
2011                 if (openex_string == ft2232_device_desc) {
2012                         /* Try the alternate method. */
2013                         openex_string = ft2232_device_desc_A;
2014                         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
2015                         if (status == FT_OK) {
2016                                 /* yea, the "alternate" method worked! */
2017                         } else {
2018                                 /* drat, give the user a meaningfull message.
2019                                  * telling the use we tried *BOTH* methods. */
2020                                 LOG_WARNING("Unable to open FTDI Device tried: '%s' and '%s'\n",
2021                                                         ft2232_device_desc,
2022                                                         ft2232_device_desc_A);
2023                         }
2024                 }
2025         }
2026
2027         if (status != FT_OK)
2028         {
2029                 DWORD num_devices;
2030
2031                 if (more)
2032                 {
2033                         LOG_WARNING("unable to open ftdi device (trying more): %lu", status);
2034                         *try_more = 1;
2035                         return ERROR_JTAG_INIT_FAILED;
2036                 }
2037                 LOG_ERROR("unable to open ftdi device: %lu", status);
2038                 status = FT_ListDevices(&num_devices, NULL, FT_LIST_NUMBER_ONLY);
2039                 if (status == FT_OK)
2040                 {
2041                         char** desc_array = malloc(sizeof(char*) * (num_devices + 1));
2042                         uint32_t i;
2043
2044                         for (i = 0; i < num_devices; i++)
2045                                 desc_array[i] = malloc(64);
2046
2047                         desc_array[num_devices] = NULL;
2048
2049                         status = FT_ListDevices(desc_array, &num_devices, FT_LIST_ALL | openex_flags);
2050
2051                         if (status == FT_OK)
2052                         {
2053                                 LOG_ERROR("ListDevices: %lu\n", num_devices);
2054                                 for (i = 0; i < num_devices; i++)
2055                                         LOG_ERROR("%" PRIu32 ": \"%s\"", i, desc_array[i]);
2056                         }
2057
2058                         for (i = 0; i < num_devices; i++)
2059                                 free(desc_array[i]);
2060
2061                         free(desc_array);
2062                 }
2063                 else
2064                 {
2065                         LOG_ERROR("ListDevices: NONE\n");
2066                 }
2067                 return ERROR_JTAG_INIT_FAILED;
2068         }
2069
2070         if ((status = FT_SetLatencyTimer(ftdih, ft2232_latency)) != FT_OK)
2071         {
2072                 LOG_ERROR("unable to set latency timer: %lu", status);
2073                 return ERROR_JTAG_INIT_FAILED;
2074         }
2075
2076         if ((status = FT_GetLatencyTimer(ftdih, &latency_timer)) != FT_OK)
2077         {
2078                 LOG_ERROR("unable to get latency timer: %lu", status);
2079                 return ERROR_JTAG_INIT_FAILED;
2080         }
2081         else
2082         {
2083                 LOG_DEBUG("current latency timer: %i", latency_timer);
2084         }
2085
2086         if ((status = FT_SetTimeouts(ftdih, 5000, 5000)) != FT_OK)
2087         {
2088                 LOG_ERROR("unable to set timeouts: %lu", status);
2089                 return ERROR_JTAG_INIT_FAILED;
2090         }
2091
2092         if ((status = FT_SetBitMode(ftdih, 0x0b, 2)) != FT_OK)
2093         {
2094                 LOG_ERROR("unable to enable bit i/o mode: %lu", status);
2095                 return ERROR_JTAG_INIT_FAILED;
2096         }
2097
2098         if ((status = FT_GetDeviceInfo(ftdih, &ftdi_device, &deviceID, SerialNumber, Description, NULL)) != FT_OK)
2099         {
2100                 LOG_ERROR("unable to get FT_GetDeviceInfo: %lu", status);
2101                 return ERROR_JTAG_INIT_FAILED;
2102         }
2103         else
2104         {
2105                 static const char* type_str[] =
2106                         {"BM", "AM", "100AX", "UNKNOWN", "2232C", "232R", "2232H", "4232H"};
2107                 unsigned no_of_known_types = ARRAY_SIZE(type_str) - 1;
2108                 unsigned type_index = ((unsigned)ftdi_device <= no_of_known_types)
2109                         ? ftdi_device : FT_DEVICE_UNKNOWN;
2110                 LOG_INFO("device: %lu \"%s\"", ftdi_device, type_str[type_index]);
2111                 LOG_INFO("deviceID: %lu", deviceID);
2112                 LOG_INFO("SerialNumber: %s", SerialNumber);
2113                 LOG_INFO("Description: %s", Description);
2114         }
2115
2116         return ERROR_OK;
2117 }
2118
2119 static int ft2232_purge_ftd2xx(void)
2120 {
2121         FT_STATUS status;
2122
2123         if ((status = FT_Purge(ftdih, FT_PURGE_RX | FT_PURGE_TX)) != FT_OK)
2124         {
2125                 LOG_ERROR("error purging ftd2xx device: %lu", status);
2126                 return ERROR_JTAG_INIT_FAILED;
2127         }
2128
2129         return ERROR_OK;
2130 }
2131
2132 #endif /* BUILD_FT2232_FTD2XX == 1 */
2133
2134 #if BUILD_FT2232_LIBFTDI == 1
2135 static int ft2232_init_libftdi(uint16_t vid, uint16_t pid, int more, int* try_more, int channel)
2136 {
2137         uint8_t latency_timer;
2138
2139         LOG_DEBUG("'ft2232' interface using libftdi with '%s' layout (%4.4x:%4.4x)",
2140                         ft2232_layout, vid, pid);
2141
2142         if (ftdi_init(&ftdic) < 0)
2143                 return ERROR_JTAG_INIT_FAILED;
2144
2145         /* default to INTERFACE_A */
2146         if(channel == INTERFACE_ANY) { channel = INTERFACE_A; }
2147
2148         if (ftdi_set_interface(&ftdic, channel) < 0)
2149         {
2150                 LOG_ERROR("unable to select FT2232 channel A: %s", ftdic.error_str);
2151                 return ERROR_JTAG_INIT_FAILED;
2152         }
2153
2154         /* context, vendor id, product id */
2155         if (ftdi_usb_open_desc(&ftdic, vid, pid, ft2232_device_desc,
2156                                 ft2232_serial) < 0)
2157         {
2158                 if (more)
2159                         LOG_WARNING("unable to open ftdi device (trying more): %s",
2160                                         ftdic.error_str);
2161                 else
2162                         LOG_ERROR("unable to open ftdi device: %s", ftdic.error_str);
2163                 *try_more = 1;
2164                 return ERROR_JTAG_INIT_FAILED;
2165         }
2166
2167         /* There is already a reset in ftdi_usb_open_desc, this should be redundant */
2168         if (ftdi_usb_reset(&ftdic) < 0)
2169         {
2170                 LOG_ERROR("unable to reset ftdi device");
2171                 return ERROR_JTAG_INIT_FAILED;
2172         }
2173
2174         if (ftdi_set_latency_timer(&ftdic, ft2232_latency) < 0)
2175         {
2176                 LOG_ERROR("unable to set latency timer");
2177                 return ERROR_JTAG_INIT_FAILED;
2178         }
2179
2180         if (ftdi_get_latency_timer(&ftdic, &latency_timer) < 0)
2181         {
2182                 LOG_ERROR("unable to get latency timer");
2183                 return ERROR_JTAG_INIT_FAILED;
2184         }
2185         else
2186         {
2187                 LOG_DEBUG("current latency timer: %i", latency_timer);
2188         }
2189
2190         ftdi_set_bitmode(&ftdic, 0x0b, 2); /* ctx, JTAG I/O mask */
2191
2192         ftdi_device = ftdic.type;
2193         static const char* type_str[] =
2194                 {"AM", "BM", "2232C", "R", "2232H", "4232H", "Unknown"};
2195         unsigned no_of_known_types = ARRAY_SIZE(type_str) - 1;
2196         unsigned type_index = ((unsigned)ftdi_device < no_of_known_types)
2197                 ? ftdi_device : no_of_known_types;
2198         LOG_DEBUG("FTDI chip type: %i \"%s\"", (int)ftdi_device, type_str[type_index]);
2199         return ERROR_OK;
2200 }
2201
2202 static int ft2232_purge_libftdi(void)
2203 {
2204         if (ftdi_usb_purge_buffers(&ftdic) < 0)
2205         {
2206                 LOG_ERROR("ftdi_purge_buffers: %s", ftdic.error_str);
2207                 return ERROR_JTAG_INIT_FAILED;
2208         }
2209
2210         return ERROR_OK;
2211 }
2212
2213 #endif /* BUILD_FT2232_LIBFTDI == 1 */
2214
2215 static int ft2232_init(void)
2216 {
2217         uint8_t  buf[1];
2218         int retval;
2219         uint32_t bytes_written;
2220         const struct ft2232_layout* cur_layout = ft2232_layouts;
2221         int i;
2222
2223         if (tap_get_tms_path_len(TAP_IRPAUSE,TAP_IRPAUSE) == 7)
2224         {
2225                 LOG_DEBUG("ft2232 interface using 7 step jtag state transitions");
2226         }
2227         else
2228         {
2229                 LOG_DEBUG("ft2232 interface using shortest path jtag state transitions");
2230
2231         }
2232         if ((ft2232_layout == NULL) || (ft2232_layout[0] == 0))
2233         {
2234                 ft2232_layout = "usbjtag";
2235                 LOG_WARNING("No ft2232 layout specified, using default 'usbjtag'");
2236         }
2237
2238         while (cur_layout->name)
2239         {
2240                 if (strcmp(cur_layout->name, ft2232_layout) == 0)
2241                 {
2242                         layout = cur_layout;
2243                         break;
2244                 }
2245                 cur_layout++;
2246         }
2247
2248         if (!layout)
2249         {
2250                 LOG_ERROR("No matching layout found for %s", ft2232_layout);
2251                 return ERROR_JTAG_INIT_FAILED;
2252         }
2253
2254         for (i = 0; 1; i++)
2255         {
2256                 /*
2257                  * "more indicates that there are more IDs to try, so we should
2258                  * not print an error for an ID mismatch (but for anything
2259                  * else, we should).
2260                  *
2261                  * try_more indicates that the error code returned indicates an
2262                  * ID mismatch (and nothing else) and that we should proceeed
2263                  * with the next ID pair.
2264                  */
2265                 int more     = ft2232_vid[i + 1] || ft2232_pid[i + 1];
2266                 int try_more = 0;
2267
2268 #if BUILD_FT2232_FTD2XX == 1
2269                 retval = ft2232_init_ftd2xx(ft2232_vid[i], ft2232_pid[i],
2270                                 more, &try_more);
2271 #elif BUILD_FT2232_LIBFTDI == 1
2272                 retval = ft2232_init_libftdi(ft2232_vid[i], ft2232_pid[i],
2273                                              more, &try_more, cur_layout->channel);
2274 #endif
2275                 if (retval >= 0)
2276                         break;
2277                 if (!more || !try_more)
2278                         return retval;
2279         }
2280
2281         ft2232_buffer_size = 0;
2282         ft2232_buffer = malloc(FT2232_BUFFER_SIZE);
2283
2284         if (layout->init() != ERROR_OK)
2285                 return ERROR_JTAG_INIT_FAILED;
2286
2287         if (ft2232_device_is_highspeed())
2288         {
2289 #ifndef BUILD_FT2232_HIGHSPEED
2290  #if BUILD_FT2232_FTD2XX == 1
2291                 LOG_WARNING("High Speed device found - You need a newer FTD2XX driver (version 2.04.16 or later)");
2292  #elif BUILD_FT2232_LIBFTDI == 1
2293                 LOG_WARNING("High Speed device found - You need a newer libftdi version (0.16 or later)");
2294  #endif
2295 #endif
2296                 /* make sure the legacy mode is disabled */
2297                 if (ft2232h_ft4232h_clk_divide_by_5(false) != ERROR_OK)
2298                         return ERROR_JTAG_INIT_FAILED;
2299         }
2300
2301         ft2232_speed(jtag_get_speed());
2302
2303         buf[0] = 0x85; /* Disconnect TDI/DO to TDO/DI for Loopback */
2304         if (((retval = ft2232_write(buf, 1, &bytes_written)) != ERROR_OK) || (bytes_written != 1))
2305         {
2306                 LOG_ERROR("couldn't write to FT2232 to disable loopback");
2307                 return ERROR_JTAG_INIT_FAILED;
2308         }
2309
2310 #if BUILD_FT2232_FTD2XX == 1
2311         return ft2232_purge_ftd2xx();
2312 #elif BUILD_FT2232_LIBFTDI == 1
2313         return ft2232_purge_libftdi();
2314 #endif
2315
2316         return ERROR_OK;
2317 }
2318
2319 static int usbjtag_init(void)
2320 {
2321         uint8_t  buf[3];
2322         uint32_t bytes_written;
2323
2324         low_output    = 0x08;
2325         low_direction = 0x0b;
2326
2327         if (strcmp(ft2232_layout, "usbjtag") == 0)
2328         {
2329                 nTRST    = 0x10;
2330                 nTRSTnOE = 0x10;
2331                 nSRST    = 0x40;
2332                 nSRSTnOE = 0x40;
2333         }
2334         else if (strcmp(ft2232_layout, "signalyzer") == 0)
2335         {
2336                 nTRST    = 0x10;
2337                 nTRSTnOE = 0x10;
2338                 nSRST    = 0x20;
2339                 nSRSTnOE = 0x20;
2340         }
2341         else if (strcmp(ft2232_layout, "evb_lm3s811") == 0)
2342         {
2343                 /* There are multiple revisions of LM3S811 eval boards:
2344                  * - Rev B (and older?) boards have no SWO trace support.
2345                  * - Rev C boards add ADBUS_6 DBG_ENn and BDBUS_4 SWO_EN;
2346                  *   they should use the "luminary_icdi" layout instead.
2347                  */
2348                 nTRST = 0x0;
2349                 nTRSTnOE = 0x00;
2350                 nSRST = 0x20;
2351                 nSRSTnOE = 0x20;
2352                 low_output    = 0x88;
2353                 low_direction = 0x8b;
2354         }
2355         else if (strcmp(ft2232_layout, "luminary_icdi") == 0)
2356         {
2357                 /* Most Luminary eval boards support SWO trace output,
2358                  * and should use this "luminary_icdi" layout.
2359                  */
2360                 nTRST = 0x0;
2361                 nTRSTnOE = 0x00;
2362                 nSRST = 0x20;
2363                 nSRSTnOE = 0x20;
2364                 low_output    = 0x88;
2365                 low_direction = 0xcb;
2366         }
2367         else
2368         {
2369                 LOG_ERROR("BUG: usbjtag_init called for unknown layout '%s'", ft2232_layout);
2370                 return ERROR_JTAG_INIT_FAILED;
2371         }
2372
2373         enum reset_types jtag_reset_config = jtag_get_reset_config();
2374         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2375         {
2376                 low_direction &= ~nTRSTnOE; /* nTRST input */
2377                 low_output    &= ~nTRST;    /* nTRST = 0 */
2378         }
2379         else
2380         {
2381                 low_direction |= nTRSTnOE;  /* nTRST output */
2382                 low_output    |= nTRST;     /* nTRST = 1 */
2383         }
2384
2385         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2386         {
2387                 low_direction |= nSRSTnOE;  /* nSRST output */
2388                 low_output    |= nSRST;     /* nSRST = 1 */
2389         }
2390         else
2391         {
2392                 low_direction &= ~nSRSTnOE; /* nSRST input */
2393                 low_output    &= ~nSRST;    /* nSRST = 0 */
2394         }
2395
2396         /* initialize low byte for jtag */
2397         buf[0] = 0x80;          /* command "set data bits low byte" */
2398         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, xRST high) */
2399         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in */
2400         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2401
2402         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2403         {
2404                 LOG_ERROR("couldn't initialize FT2232 with 'USBJTAG' layout");
2405                 return ERROR_JTAG_INIT_FAILED;
2406         }
2407
2408         return ERROR_OK;
2409 }
2410
2411 static int axm0432_jtag_init(void)
2412 {
2413         uint8_t  buf[3];
2414         uint32_t bytes_written;
2415
2416         low_output    = 0x08;
2417         low_direction = 0x2b;
2418
2419         /* initialize low byte for jtag */
2420         buf[0] = 0x80;          /* command "set data bits low byte" */
2421         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2422         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2423         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2424
2425         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2426         {
2427                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2428                 return ERROR_JTAG_INIT_FAILED;
2429         }
2430
2431         if (strcmp(layout->name, "axm0432_jtag") == 0)
2432         {
2433                 nTRST    = 0x08;
2434                 nTRSTnOE = 0x0;     /* No output enable for TRST*/
2435                 nSRST    = 0x04;
2436                 nSRSTnOE = 0x0;     /* No output enable for SRST*/
2437         }
2438         else
2439         {
2440                 LOG_ERROR("BUG: axm0432_jtag_init called for non axm0432 layout");
2441                 exit(-1);
2442         }
2443
2444         high_output    = 0x0;
2445         high_direction = 0x0c;
2446
2447         enum reset_types jtag_reset_config = jtag_get_reset_config();
2448         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2449         {
2450                 LOG_ERROR("can't set nTRSTOE to push-pull on the Dicarlo jtag");
2451         }
2452         else
2453         {
2454                 high_output |= nTRST;
2455         }
2456
2457         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2458         {
2459                 LOG_ERROR("can't set nSRST to push-pull on the Dicarlo jtag");
2460         }
2461         else
2462         {
2463                 high_output |= nSRST;
2464         }
2465
2466         /* initialize high port */
2467         buf[0] = 0x82;              /* command "set data bits high byte" */
2468         buf[1] = high_output;       /* value */
2469         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2470         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2471
2472         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2473         {
2474                 LOG_ERROR("couldn't initialize FT2232 with 'Dicarlo' layout");
2475                 return ERROR_JTAG_INIT_FAILED;
2476         }
2477
2478         return ERROR_OK;
2479 }
2480
2481 static int jtagkey_init(void)
2482 {
2483         uint8_t  buf[3];
2484         uint32_t bytes_written;
2485
2486         low_output    = 0x08;
2487         low_direction = 0x1b;
2488
2489         /* initialize low byte for jtag */
2490         buf[0] = 0x80;          /* command "set data bits low byte" */
2491         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2492         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2493         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2494
2495         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2496         {
2497                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2498                 return ERROR_JTAG_INIT_FAILED;
2499         }
2500
2501         if (strcmp(layout->name, "jtagkey") == 0)
2502         {
2503                 nTRST    = 0x01;
2504                 nTRSTnOE = 0x4;
2505                 nSRST    = 0x02;
2506                 nSRSTnOE = 0x08;
2507         }
2508         else if ((strcmp(layout->name, "jtagkey_prototype_v1") == 0)
2509                          || (strcmp(layout->name, "oocdlink") == 0))
2510         {
2511                 nTRST    = 0x02;
2512                 nTRSTnOE = 0x1;
2513                 nSRST    = 0x08;
2514                 nSRSTnOE = 0x04;
2515         }
2516         else
2517         {
2518                 LOG_ERROR("BUG: jtagkey_init called for non jtagkey layout");
2519                 exit(-1);
2520         }
2521
2522         high_output    = 0x0;
2523         high_direction = 0x0f;
2524
2525         enum reset_types jtag_reset_config = jtag_get_reset_config();
2526         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2527         {
2528                 high_output |= nTRSTnOE;
2529                 high_output &= ~nTRST;
2530         }
2531         else
2532         {
2533                 high_output &= ~nTRSTnOE;
2534                 high_output |= nTRST;
2535         }
2536
2537         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2538         {
2539                 high_output &= ~nSRSTnOE;
2540                 high_output |= nSRST;
2541         }
2542         else
2543         {
2544                 high_output |= nSRSTnOE;
2545                 high_output &= ~nSRST;
2546         }
2547
2548         /* initialize high port */
2549         buf[0] = 0x82;              /* command "set data bits high byte" */
2550         buf[1] = high_output;       /* value */
2551         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2552         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2553
2554         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2555         {
2556                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2557                 return ERROR_JTAG_INIT_FAILED;
2558         }
2559
2560         return ERROR_OK;
2561 }
2562
2563 static int olimex_jtag_init(void)
2564 {
2565         uint8_t  buf[3];
2566         uint32_t bytes_written;
2567
2568         low_output    = 0x08;
2569         low_direction = 0x1b;
2570
2571         /* initialize low byte for jtag */
2572         buf[0] = 0x80;          /* command "set data bits low byte" */
2573         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2574         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2575         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2576
2577         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2578         {
2579                 LOG_ERROR("couldn't initialize FT2232 with 'Olimex' layout");
2580                 return ERROR_JTAG_INIT_FAILED;
2581         }
2582
2583         nTRST    = 0x01;
2584         nTRSTnOE = 0x4;
2585         nSRST    = 0x02;
2586         nSRSTnOE = 0x00; /* no output enable for nSRST */
2587
2588         high_output    = 0x0;
2589         high_direction = 0x0f;
2590
2591         enum reset_types jtag_reset_config = jtag_get_reset_config();
2592         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2593         {
2594                 high_output |= nTRSTnOE;
2595                 high_output &= ~nTRST;
2596         }
2597         else
2598         {
2599                 high_output &= ~nTRSTnOE;
2600                 high_output |= nTRST;
2601         }
2602
2603         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2604         {
2605                 LOG_ERROR("can't set nSRST to push-pull on the Olimex ARM-USB-OCD");
2606         }
2607         else
2608         {
2609                 high_output &= ~nSRST;
2610         }
2611
2612         /* turn red LED on */
2613         high_output |= 0x08;
2614
2615         /* initialize high port */
2616         buf[0] = 0x82;              /* command "set data bits high byte" */
2617         buf[1] = high_output;       /* value */
2618         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2619         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2620
2621         if ((ft2232_write(buf, 3, &bytes_written) != ERROR_OK) || (bytes_written != 3))
2622         {
2623                 LOG_ERROR("couldn't initialize FT2232 with 'Olimex' layout");
2624                 return ERROR_JTAG_INIT_FAILED;
2625         }
2626
2627         return ERROR_OK;
2628 }
2629
2630 static int flyswatter_init(void)
2631 {
2632         uint8_t  buf[3];
2633         uint32_t bytes_written;
2634
2635         low_output    = 0x18;
2636         low_direction = 0xfb;
2637
2638         /* initialize low byte for jtag */
2639         buf[0] = 0x80;          /* command "set data bits low byte" */
2640         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2641         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE[12]=out, n[ST]srst = out */
2642         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2643
2644         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2645         {
2646                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2647                 return ERROR_JTAG_INIT_FAILED;
2648         }
2649
2650         nTRST    = 0x10;
2651         nTRSTnOE = 0x0;     /* not output enable for nTRST */
2652         nSRST    = 0x20;
2653         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2654
2655         high_output    = 0x00;
2656         high_direction = 0x0c;
2657
2658         /* turn red LED3 on, LED2 off */
2659         high_output |= 0x08;
2660
2661         /* initialize high port */
2662         buf[0] = 0x82;              /* command "set data bits high byte" */
2663         buf[1] = high_output;       /* value */
2664         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2665         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2666
2667         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2668         {
2669                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2670                 return ERROR_JTAG_INIT_FAILED;
2671         }
2672
2673         return ERROR_OK;
2674 }
2675
2676 static int turtle_init(void)
2677 {
2678         uint8_t  buf[3];
2679         uint32_t bytes_written;
2680
2681         low_output    = 0x08;
2682         low_direction = 0x5b;
2683
2684         /* initialize low byte for jtag */
2685         buf[0] = 0x80;          /* command "set data bits low byte" */
2686         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2687         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2688         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2689
2690         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2691         {
2692                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2693                 return ERROR_JTAG_INIT_FAILED;
2694         }
2695
2696         nSRST = 0x40;
2697
2698         high_output    = 0x00;
2699         high_direction = 0x0C;
2700
2701         /* initialize high port */
2702         buf[0] = 0x82; /* command "set data bits high byte" */
2703         buf[1] = high_output;
2704         buf[2] = high_direction;
2705         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2706
2707         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2708         {
2709                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2710                 return ERROR_JTAG_INIT_FAILED;
2711         }
2712
2713         return ERROR_OK;
2714 }
2715
2716 static int comstick_init(void)
2717 {
2718         uint8_t  buf[3];
2719         uint32_t bytes_written;
2720
2721         low_output    = 0x08;
2722         low_direction = 0x0b;
2723
2724         /* initialize low byte for jtag */
2725         buf[0] = 0x80;          /* command "set data bits low byte" */
2726         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2727         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2728         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2729
2730         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2731         {
2732                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2733                 return ERROR_JTAG_INIT_FAILED;
2734         }
2735
2736         nTRST    = 0x01;
2737         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2738         nSRST    = 0x02;
2739         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2740
2741         high_output    = 0x03;
2742         high_direction = 0x03;
2743
2744         /* initialize high port */
2745         buf[0] = 0x82; /* command "set data bits high byte" */
2746         buf[1] = high_output;
2747         buf[2] = high_direction;
2748         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2749
2750         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2751         {
2752                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2753                 return ERROR_JTAG_INIT_FAILED;
2754         }
2755
2756         return ERROR_OK;
2757 }
2758
2759 static int stm32stick_init(void)
2760 {
2761         uint8_t  buf[3];
2762         uint32_t bytes_written;
2763
2764         low_output    = 0x88;
2765         low_direction = 0x8b;
2766
2767         /* initialize low byte for jtag */
2768         buf[0] = 0x80;          /* command "set data bits low byte" */
2769         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2770         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2771         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2772
2773         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2774         {
2775                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2776                 return ERROR_JTAG_INIT_FAILED;
2777         }
2778
2779         nTRST    = 0x01;
2780         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2781         nSRST    = 0x80;
2782         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2783
2784         high_output    = 0x01;
2785         high_direction = 0x03;
2786
2787         /* initialize high port */
2788         buf[0] = 0x82; /* command "set data bits high byte" */
2789         buf[1] = high_output;
2790         buf[2] = high_direction;
2791         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2792
2793         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2794         {
2795                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2796                 return ERROR_JTAG_INIT_FAILED;
2797         }
2798
2799         return ERROR_OK;
2800 }
2801
2802 static int sheevaplug_init(void)
2803 {
2804         uint8_t buf[3];
2805         uint32_t bytes_written;
2806
2807         low_output = 0x08;
2808         low_direction = 0x1b;
2809
2810         /* initialize low byte for jtag */
2811         buf[0] = 0x80; /* command "set data bits low byte" */
2812         buf[1] = low_output; /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2813         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in */
2814         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2815
2816         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2817         {
2818                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2819                 return ERROR_JTAG_INIT_FAILED;
2820         }
2821
2822         nTRSTnOE = 0x1;
2823         nTRST = 0x02;
2824         nSRSTnOE = 0x4;
2825         nSRST = 0x08;
2826
2827         high_output = 0x0;
2828         high_direction = 0x0f;
2829
2830         /* nTRST is always push-pull */
2831         high_output &= ~nTRSTnOE;
2832         high_output |= nTRST;
2833
2834         /* nSRST is always open-drain */
2835         high_output |= nSRSTnOE;
2836         high_output &= ~nSRST;
2837
2838         /* initialize high port */
2839         buf[0] = 0x82; /* command "set data bits high byte" */
2840         buf[1] = high_output; /* value */
2841         buf[2] = high_direction;   /* all outputs - xRST */
2842         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2843
2844         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2845         {
2846                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2847                 return ERROR_JTAG_INIT_FAILED;
2848         }
2849
2850         return ERROR_OK;
2851 }
2852
2853 static int cortino_jtag_init(void)
2854 {
2855         uint8_t  buf[3];
2856         uint32_t bytes_written;
2857
2858         low_output    = 0x08;
2859         low_direction = 0x1b;
2860
2861         /* initialize low byte for jtag */
2862         buf[0] = 0x80;          /* command "set data bits low byte" */
2863         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2864         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2865         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2866
2867         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2868         {
2869                 LOG_ERROR("couldn't initialize FT2232 with 'cortino' layout");
2870                 return ERROR_JTAG_INIT_FAILED;
2871         }
2872
2873         nTRST    = 0x01;
2874         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2875         nSRST    = 0x02;
2876         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2877
2878         high_output    = 0x03;
2879         high_direction = 0x03;
2880
2881         /* initialize high port */
2882         buf[0] = 0x82; /* command "set data bits high byte" */
2883         buf[1] = high_output;
2884         buf[2] = high_direction;
2885         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2886
2887         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2888         {
2889                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2890                 return ERROR_JTAG_INIT_FAILED;
2891         }
2892
2893         return ERROR_OK;
2894 }
2895
2896 static void olimex_jtag_blink(void)
2897 {
2898         /* Olimex ARM-USB-OCD has a LED connected to ACBUS3
2899          * ACBUS3 is bit 3 of the GPIOH port
2900          */
2901         if (high_output & 0x08)
2902         {
2903                 /* set port pin high */
2904                 high_output &= 0x07;
2905         }
2906         else
2907         {
2908                 /* set port pin low */
2909                 high_output |= 0x08;
2910         }
2911
2912         buffer_write(0x82);
2913         buffer_write(high_output);
2914         buffer_write(high_direction);
2915 }
2916
2917 static void flyswatter_jtag_blink(void)
2918 {
2919         /*
2920          * Flyswatter has two LEDs connected to ACBUS2 and ACBUS3
2921          */
2922         high_output ^= 0x0c;
2923
2924         buffer_write(0x82);
2925         buffer_write(high_output);
2926         buffer_write(high_direction);
2927 }
2928
2929 static void turtle_jtag_blink(void)
2930 {
2931         /*
2932          * Turtelizer2 has two LEDs connected to ACBUS2 and ACBUS3
2933          */
2934         if (high_output & 0x08)
2935         {
2936                 high_output = 0x04;
2937         }
2938         else
2939         {
2940                 high_output = 0x08;
2941         }
2942
2943         buffer_write(0x82);
2944         buffer_write(high_output);
2945         buffer_write(high_direction);
2946 }
2947
2948 static int ft2232_quit(void)
2949 {
2950 #if BUILD_FT2232_FTD2XX == 1
2951         FT_STATUS status;
2952
2953         status = FT_Close(ftdih);
2954 #elif BUILD_FT2232_LIBFTDI == 1
2955         ftdi_usb_close(&ftdic);
2956
2957         ftdi_deinit(&ftdic);
2958 #endif
2959
2960         free(ft2232_buffer);
2961         ft2232_buffer = NULL;
2962
2963         return ERROR_OK;
2964 }
2965
2966 COMMAND_HANDLER(ft2232_handle_device_desc_command)
2967 {
2968         char *cp;
2969         char buf[200];
2970         if (CMD_ARGC == 1)
2971         {
2972                 ft2232_device_desc = strdup(CMD_ARGV[0]);
2973                 cp = strchr(ft2232_device_desc, 0);
2974                 /* under Win32, the FTD2XX driver appends an "A" to the end
2975                  * of the description, this examines the given desc
2976                  * and creates the 'missing' _A or non_A variable. */
2977                 if ((cp[-1] == 'A') && (cp[-2]==' ')) {
2978                         /* it was, so make this the "A" version. */
2979                         ft2232_device_desc_A = ft2232_device_desc;
2980                         /* and *CREATE* the non-A version. */
2981                         strcpy(buf, ft2232_device_desc);
2982                         cp = strchr(buf, 0);
2983                         cp[-2] = 0;
2984                         ft2232_device_desc =  strdup(buf);
2985                 } else {
2986                         /* <space > A not defined
2987                          * so create it */
2988                         sprintf(buf, "%s A", ft2232_device_desc);
2989                         ft2232_device_desc_A = strdup(buf);
2990                 }
2991         }
2992         else
2993         {
2994                 LOG_ERROR("expected exactly one argument to ft2232_device_desc <description>");
2995         }
2996
2997         return ERROR_OK;
2998 }
2999
3000 COMMAND_HANDLER(ft2232_handle_serial_command)
3001 {
3002         if (CMD_ARGC == 1)
3003         {
3004                 ft2232_serial = strdup(CMD_ARGV[0]);
3005         }
3006         else
3007         {
3008                 LOG_ERROR("expected exactly one argument to ft2232_serial <serial-number>");
3009         }
3010
3011         return ERROR_OK;
3012 }
3013
3014 COMMAND_HANDLER(ft2232_handle_layout_command)
3015 {
3016         if (CMD_ARGC == 0)
3017                 return ERROR_OK;
3018
3019         ft2232_layout = malloc(strlen(CMD_ARGV[0]) + 1);
3020         strcpy(ft2232_layout, CMD_ARGV[0]);
3021
3022         return ERROR_OK;
3023 }
3024
3025 COMMAND_HANDLER(ft2232_handle_vid_pid_command)
3026 {
3027         if (CMD_ARGC > MAX_USB_IDS * 2)
3028         {
3029                 LOG_WARNING("ignoring extra IDs in ft2232_vid_pid "
3030                                         "(maximum is %d pairs)", MAX_USB_IDS);
3031                 CMD_ARGC = MAX_USB_IDS * 2;
3032         }
3033         if (CMD_ARGC < 2 || (CMD_ARGC & 1))
3034         {
3035                 LOG_WARNING("incomplete ft2232_vid_pid configuration directive");
3036                 if (CMD_ARGC < 2)
3037                         return ERROR_COMMAND_SYNTAX_ERROR;
3038                 /* remove the incomplete trailing id */
3039                 CMD_ARGC -= 1;
3040         }
3041
3042         unsigned i;
3043         for (i = 0; i < CMD_ARGC; i += 2)
3044         {
3045                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], ft2232_vid[i >> 1]);
3046                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], ft2232_pid[i >> 1]);
3047         }
3048
3049         /*
3050          * Explicitly terminate, in case there are multiples instances of
3051          * ft2232_vid_pid.
3052          */
3053         ft2232_vid[i >> 1] = ft2232_pid[i >> 1] = 0;
3054
3055         return ERROR_OK;
3056 }
3057
3058 COMMAND_HANDLER(ft2232_handle_latency_command)
3059 {
3060         if (CMD_ARGC == 1)
3061         {
3062                 ft2232_latency = atoi(CMD_ARGV[0]);
3063         }
3064         else
3065         {
3066                 LOG_ERROR("expected exactly one argument to ft2232_latency <ms>");
3067         }
3068
3069         return ERROR_OK;
3070 }
3071
3072 static int ft2232_stableclocks(int num_cycles, struct jtag_command* cmd)
3073 {
3074         int retval = 0;
3075
3076         /* 7 bits of either ones or zeros. */
3077         uint8_t  tms = (tap_get_state() == TAP_RESET ? 0x7F : 0x00);
3078
3079         while (num_cycles > 0)
3080         {
3081                 /* the command 0x4b, "Clock Data to TMS/CS Pin (no Read)" handles
3082                  * at most 7 bits per invocation.  Here we invoke it potentially
3083                  * several times.
3084                  */
3085                 int bitcount_per_command = (num_cycles > 7) ? 7 : num_cycles;
3086
3087                 if (ft2232_buffer_size + 3 >= FT2232_BUFFER_SIZE)
3088                 {
3089                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
3090                                 retval = ERROR_JTAG_QUEUE_FAILED;
3091
3092                         first_unsent = cmd;
3093                 }
3094
3095                 /* there are no state transitions in this code, so omit state tracking */
3096
3097                 /* command "Clock Data to TMS/CS Pin (no Read)" */
3098                 buffer_write(0x4b);
3099
3100                 /* scan 7 bit */
3101                 buffer_write(bitcount_per_command - 1);
3102
3103                 /* TMS data bits are either all zeros or ones to stay in the current stable state */
3104                 buffer_write(tms);
3105
3106                 require_send = 1;
3107
3108                 num_cycles -= bitcount_per_command;
3109         }
3110
3111         return retval;
3112 }
3113
3114 /* ---------------------------------------------------------------------
3115  * Support for IceBear JTAG adapter from Section5:
3116  *      http://section5.ch/icebear
3117  *
3118  * Author: Sten, debian@sansys-electronic.com
3119  */
3120
3121 /* Icebear pin layout
3122  *
3123  * ADBUS5 (nEMU) nSRST  | 2   1|        GND (10k->VCC)
3124  * GND GND              | 4   3|        n.c.
3125  * ADBUS3 TMS           | 6   5|        ADBUS6 VCC
3126  * ADBUS0 TCK           | 8   7|        ADBUS7 (GND)
3127  * ADBUS4 nTRST         |10   9|        ACBUS0 (GND)
3128  * ADBUS1 TDI           |12  11|        ACBUS1 (GND)
3129  * ADBUS2 TDO           |14  13|        GND GND
3130  *
3131  * ADBUS0 O L TCK               ACBUS0 GND
3132  * ADBUS1 O L TDI               ACBUS1 GND
3133  * ADBUS2 I   TDO               ACBUS2 n.c.
3134  * ADBUS3 O H TMS               ACBUS3 n.c.
3135  * ADBUS4 O H nTRST
3136  * ADBUS5 O H nSRST
3137  * ADBUS6 -   VCC
3138  * ADBUS7 -   GND
3139  */
3140 static int icebear_jtag_init(void) {
3141         uint8_t  buf[3];
3142         uint32_t bytes_written;
3143
3144         low_direction   = 0x0b; /* output: TCK TDI TMS; input: TDO */
3145         low_output      = 0x08; /* high: TMS; low: TCK TDI */
3146         nTRST           = 0x10;
3147         nSRST           = 0x20;
3148
3149         enum reset_types jtag_reset_config = jtag_get_reset_config();
3150         if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0) {
3151                 low_direction   &= ~nTRST;      /* nTRST high impedance */
3152         }
3153         else {
3154                 low_direction   |= nTRST;
3155                 low_output      |= nTRST;
3156         }
3157
3158         low_direction   |= nSRST;
3159         low_output      |= nSRST;
3160
3161         /* initialize low byte for jtag */
3162         buf[0] = 0x80;          /* command "set data bits low byte" */
3163         buf[1] = low_output;
3164         buf[2] = low_direction;
3165         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
3166
3167         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3)) {
3168                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (low)");
3169                 return ERROR_JTAG_INIT_FAILED;
3170         }
3171
3172         high_output    = 0x0;
3173         high_direction = 0x00;
3174
3175
3176         /* initialize high port */
3177         buf[0] = 0x82;              /* command "set data bits high byte" */
3178         buf[1] = high_output;       /* value */
3179         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
3180         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
3181
3182         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3)) {
3183                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (high)");
3184                 return ERROR_JTAG_INIT_FAILED;
3185         }
3186
3187         return ERROR_OK;
3188 }
3189
3190 static void icebear_jtag_reset(int trst, int srst) {
3191
3192         if (trst == 1) {
3193                 low_direction   |= nTRST;
3194                 low_output      &= ~nTRST;
3195         }
3196         else if (trst == 0) {
3197                 enum reset_types jtag_reset_config = jtag_get_reset_config();
3198                 if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0)
3199                         low_direction   &= ~nTRST;
3200                 else
3201                         low_output      |= nTRST;
3202         }
3203
3204         if (srst == 1) {
3205                 low_output &= ~nSRST;
3206         }
3207         else if (srst == 0) {
3208                 low_output |= nSRST;
3209         }
3210
3211         /* command "set data bits low byte" */
3212         buffer_write(0x80);
3213         buffer_write(low_output);
3214         buffer_write(low_direction);
3215
3216         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
3217 }
3218
3219 /* ---------------------------------------------------------------------
3220  * Support for Signalyzer H2 and Signalyzer H4
3221  * JTAG adapter from Xverve Technologies Inc.
3222  * http://www.signalyzer.com or http://www.xverve.com
3223  *
3224  * Author: Oleg Seiljus, oleg@signalyzer.com
3225  */
3226 static unsigned char signalyzer_h_side;
3227 static unsigned int signalyzer_h_adapter_type;
3228
3229 static int signalyzer_h_ctrl_write(int address, unsigned short value);
3230
3231 #if BUILD_FT2232_FTD2XX == 1
3232 static int signalyzer_h_ctrl_read(int address, unsigned short *value);
3233 #endif
3234
3235 #define SIGNALYZER_COMMAND_ADDR                                 128
3236 #define SIGNALYZER_DATA_BUFFER_ADDR                             129
3237
3238 #define SIGNALYZER_COMMAND_VERSION                              0x41
3239 #define SIGNALYZER_COMMAND_RESET                                0x42
3240 #define SIGNALYZER_COMMAND_POWERCONTROL_GET             0x50
3241 #define SIGNALYZER_COMMAND_POWERCONTROL_SET             0x51
3242 #define SIGNALYZER_COMMAND_PWM_SET                              0x52
3243 #define SIGNALYZER_COMMAND_LED_SET                              0x53
3244 #define SIGNALYZER_COMMAND_ADC                                  0x54
3245 #define SIGNALYZER_COMMAND_GPIO_STATE                   0x55
3246 #define SIGNALYZER_COMMAND_GPIO_MODE                    0x56
3247 #define SIGNALYZER_COMMAND_GPIO_PORT                    0x57
3248 #define SIGNALYZER_COMMAND_I2C                                  0x58
3249
3250 #define SIGNALYZER_CHAN_A                                               1
3251 #define SIGNALYZER_CHAN_B                                               2
3252 /* LEDS use channel C */
3253 #define SIGNALYZER_CHAN_C                                               4
3254
3255 #define SIGNALYZER_LED_GREEN                                    1
3256 #define SIGNALYZER_LED_RED                                              2
3257
3258 #define SIGNALYZER_MODULE_TYPE_EM_LT16_A                0x0301
3259 #define SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG              0x0302
3260 #define SIGNALYZER_MODULE_TYPE_EM_JTAG                  0x0303
3261 #define SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P    0x0304
3262 #define SIGNALYZER_MODULE_TYPE_EM_JTAG_P                0x0305
3263
3264
3265 static int signalyzer_h_ctrl_write(int address, unsigned short value)
3266 {
3267 #if BUILD_FT2232_FTD2XX == 1
3268         return FT_WriteEE(ftdih, address, value);
3269 #elif BUILD_FT2232_LIBFTDI == 1
3270         return 0;
3271 #endif
3272 }
3273
3274 #if BUILD_FT2232_FTD2XX == 1
3275 static int signalyzer_h_ctrl_read(int address, unsigned short *value)
3276 {
3277         return FT_ReadEE(ftdih, address, value);
3278 }
3279 #endif
3280
3281 static int signalyzer_h_led_set(unsigned char channel, unsigned char led,
3282         int on_time_ms, int off_time_ms, unsigned char cycles)
3283 {
3284         unsigned char on_time;
3285         unsigned char off_time;
3286
3287         if (on_time_ms < 0xFFFF)
3288                 on_time = (unsigned char)(on_time_ms / 62);
3289         else
3290                 on_time = 0xFF;
3291
3292         off_time = (unsigned char)(off_time_ms / 62);
3293
3294 #if BUILD_FT2232_FTD2XX == 1
3295         FT_STATUS status;
3296
3297         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3298                         ((uint32_t)(channel << 8) | led))) != FT_OK)
3299         {
3300                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %lu", status);
3301                 return ERROR_JTAG_DEVICE_ERROR;
3302         }
3303
3304         if ((status = signalyzer_h_ctrl_write(
3305                         (SIGNALYZER_DATA_BUFFER_ADDR + 1),
3306                         ((uint32_t)(on_time << 8) | off_time))) != FT_OK)
3307         {
3308                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %lu", status);
3309                 return ERROR_JTAG_DEVICE_ERROR;
3310         }
3311
3312         if ((status = signalyzer_h_ctrl_write(
3313                         (SIGNALYZER_DATA_BUFFER_ADDR + 2),
3314                         ((uint32_t)cycles))) != FT_OK)
3315         {
3316                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %lu", status);
3317                 return ERROR_JTAG_DEVICE_ERROR;
3318         }
3319
3320         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3321                         SIGNALYZER_COMMAND_LED_SET)) != FT_OK)
3322         {
3323                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %lu", status);
3324                 return ERROR_JTAG_DEVICE_ERROR;
3325         }
3326
3327         return ERROR_OK;
3328 #elif BUILD_FT2232_LIBFTDI == 1
3329         int retval;
3330
3331         if ((retval = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3332                         ((uint32_t)(channel << 8) | led))) < 0)
3333         {
3334                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3335                                 ftdi_get_error_string(&ftdic));
3336                 return ERROR_JTAG_DEVICE_ERROR;
3337         }
3338
3339         if ((retval = signalyzer_h_ctrl_write(
3340                         (SIGNALYZER_DATA_BUFFER_ADDR + 1),
3341                         ((uint32_t)(on_time << 8) | off_time))) < 0)
3342         {
3343                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3344                                 ftdi_get_error_string(&ftdic));
3345                 return ERROR_JTAG_DEVICE_ERROR;
3346         }
3347
3348         if ((retval = signalyzer_h_ctrl_write(
3349                         (SIGNALYZER_DATA_BUFFER_ADDR + 2),
3350                         (uint32_t)cycles)) < 0)
3351         {
3352                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3353                                 ftdi_get_error_string(&ftdic));
3354                 return ERROR_JTAG_DEVICE_ERROR;
3355         }
3356
3357         if ((retval = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3358                         SIGNALYZER_COMMAND_LED_SET)) < 0)
3359         {
3360                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3361                                 ftdi_get_error_string(&ftdic));
3362                 return ERROR_JTAG_DEVICE_ERROR;
3363         }
3364
3365         return ERROR_OK;
3366 #endif
3367 }
3368
3369 static int signalyzer_h_init(void)
3370 {
3371 #if BUILD_FT2232_FTD2XX == 1
3372         FT_STATUS status;
3373         int i;
3374 #endif
3375
3376         char *end_of_desc;
3377
3378         uint16_t read_buf[12] = { 0 };
3379         uint8_t  buf[3];
3380         uint32_t bytes_written;
3381
3382         /* turn on center green led */
3383         signalyzer_h_led_set(SIGNALYZER_CHAN_C, SIGNALYZER_LED_GREEN,
3384                         0xFFFF, 0x00, 0x00);
3385
3386         /* determine what channel config wants to open
3387          * TODO: change me... current implementation is made to work
3388          * with openocd description parsing.
3389          */
3390         end_of_desc = strrchr(ft2232_device_desc, 0x00);
3391
3392         if (end_of_desc)
3393         {
3394                 signalyzer_h_side = *(end_of_desc - 1);
3395                 if (signalyzer_h_side == 'B')
3396                         signalyzer_h_side = SIGNALYZER_CHAN_B;
3397                 else
3398                         signalyzer_h_side = SIGNALYZER_CHAN_A;
3399         }
3400         else
3401         {
3402                 LOG_ERROR("No Channel was specified");
3403                 return ERROR_FAIL;
3404         }
3405
3406         signalyzer_h_led_set(signalyzer_h_side, SIGNALYZER_LED_GREEN,
3407                         1000, 1000, 0xFF);
3408
3409 #if BUILD_FT2232_FTD2XX == 1
3410         /* read signalyzer versionining information */
3411         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3412                         SIGNALYZER_COMMAND_VERSION)) != FT_OK)
3413         {
3414                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3415                 return ERROR_JTAG_DEVICE_ERROR;
3416         }
3417
3418         for (i = 0; i < 10; i++)
3419         {
3420                 if ((status = signalyzer_h_ctrl_read(
3421                         (SIGNALYZER_DATA_BUFFER_ADDR + i),
3422                         &read_buf[i])) != FT_OK)
3423                 {
3424                         LOG_ERROR("signalyzer_h_ctrl_read returned: %lu",
3425                                         status);
3426                         return ERROR_JTAG_DEVICE_ERROR;
3427                 }
3428         }
3429
3430         LOG_INFO("Signalyzer: ID info: { %.4x %.4x %.4x %.4x %.4x %.4x %.4x }",
3431                         read_buf[0], read_buf[1], read_buf[2], read_buf[3],
3432                         read_buf[4], read_buf[5], read_buf[6]);
3433
3434         /* set gpio register */
3435         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3436                         (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3437         {
3438                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3439                 return ERROR_JTAG_DEVICE_ERROR;
3440         }
3441
3442         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR + 1,
3443                         0x0404)) != FT_OK)
3444         {
3445                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3446                 return ERROR_JTAG_DEVICE_ERROR;
3447         }
3448
3449         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3450                         SIGNALYZER_COMMAND_GPIO_STATE)) != FT_OK)
3451         {
3452                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3453                 return ERROR_JTAG_DEVICE_ERROR;
3454         }
3455
3456         /* read adapter type information */
3457         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3458                         ((uint32_t)(signalyzer_h_side << 8) | 0x01))) != FT_OK)
3459         {
3460                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3461                 return ERROR_JTAG_DEVICE_ERROR;
3462         }
3463
3464         if ((status = signalyzer_h_ctrl_write(
3465                         (SIGNALYZER_DATA_BUFFER_ADDR + 1), 0xA000)) != FT_OK)
3466         {
3467                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3468                 return ERROR_JTAG_DEVICE_ERROR;
3469         }
3470
3471         if ((status = signalyzer_h_ctrl_write(
3472                         (SIGNALYZER_DATA_BUFFER_ADDR + 2), 0x0008)) != FT_OK)
3473         {
3474                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3475                 return ERROR_JTAG_DEVICE_ERROR;
3476         }
3477
3478         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3479                         SIGNALYZER_COMMAND_I2C)) != FT_OK)
3480         {
3481                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3482                 return ERROR_JTAG_DEVICE_ERROR;
3483         }
3484
3485         usleep(100000);
3486
3487         if ((status = signalyzer_h_ctrl_read(SIGNALYZER_COMMAND_ADDR,
3488                         &read_buf[0])) != FT_OK)
3489         {
3490                 LOG_ERROR("signalyzer_h_ctrl_read returned: %lu", status);
3491                 return ERROR_JTAG_DEVICE_ERROR;
3492         }
3493
3494         if (read_buf[0] != 0x0498)
3495                 signalyzer_h_adapter_type = 0x0000;
3496         else
3497         {
3498                 for (i = 0; i < 4; i++)
3499                 {
3500                         if ((status = signalyzer_h_ctrl_read(
3501                                         (SIGNALYZER_DATA_BUFFER_ADDR + i),
3502                                         &read_buf[i])) != FT_OK)
3503                         {
3504                                 LOG_ERROR("signalyzer_h_ctrl_read returned: %lu",
3505                                         status);
3506                                 return ERROR_JTAG_DEVICE_ERROR;
3507                         }
3508                 }
3509
3510                 signalyzer_h_adapter_type = read_buf[0];
3511         }
3512
3513 #elif BUILD_FT2232_LIBFTDI == 1
3514         /* currently libftdi does not allow reading individual eeprom
3515          * locations, therefore adapter type cannot be detected.
3516          * override with most common type
3517          */
3518         signalyzer_h_adapter_type = SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG;
3519 #endif
3520
3521         enum reset_types jtag_reset_config = jtag_get_reset_config();
3522
3523         /* ADAPTOR: EM_LT16_A */
3524         if (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_LT16_A)
3525         {
3526                 LOG_INFO("Signalyzer: EM-LT (16-channel level translator) "
3527                         "detected. (HW: %2x).", (read_buf[1] >> 8));
3528
3529                 nTRST    = 0x10;
3530                 nTRSTnOE = 0x10;
3531                 nSRST    = 0x20;
3532                 nSRSTnOE = 0x20;
3533
3534                 low_output     = 0x08;
3535                 low_direction  = 0x1b;
3536
3537                 high_output    = 0x0;
3538                 high_direction = 0x0;
3539
3540                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3541                 {
3542                         low_direction &= ~nTRSTnOE; /* nTRST input */
3543                         low_output    &= ~nTRST;    /* nTRST = 0 */
3544                 }
3545                 else
3546                 {
3547                         low_direction |= nTRSTnOE;  /* nTRST output */
3548                         low_output    |= nTRST;     /* nTRST = 1 */
3549                 }
3550
3551                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3552                 {
3553                         low_direction |= nSRSTnOE;  /* nSRST output */
3554                         low_output    |= nSRST;     /* nSRST = 1 */
3555                 }
3556                 else
3557                 {
3558                         low_direction &= ~nSRSTnOE; /* nSRST input */
3559                         low_output    &= ~nSRST;    /* nSRST = 0 */
3560                 }
3561
3562 #if BUILD_FT2232_FTD2XX == 1
3563                 /* enable power to the module */
3564                 if ((status = signalyzer_h_ctrl_write(
3565                                 SIGNALYZER_DATA_BUFFER_ADDR,
3566                                 ((uint32_t)(signalyzer_h_side << 8) | 0x01)))
3567                         != FT_OK)
3568                 {
3569                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3570                                 status);
3571                         return ERROR_JTAG_DEVICE_ERROR;
3572                 }
3573
3574                 if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3575                                 SIGNALYZER_COMMAND_POWERCONTROL_SET)) != FT_OK)
3576                 {
3577                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3578                                         status);
3579                         return ERROR_JTAG_DEVICE_ERROR;
3580                 }
3581
3582                 /* set gpio mode register */
3583                 if ((status = signalyzer_h_ctrl_write(
3584                                 SIGNALYZER_DATA_BUFFER_ADDR,
3585                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3586                 {
3587                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3588                                         status);
3589                         return ERROR_JTAG_DEVICE_ERROR;
3590                 }
3591
3592                 if ((status = signalyzer_h_ctrl_write(
3593                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x0000))
3594                         != FT_OK)
3595                 {
3596                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3597                                         status);
3598                         return ERROR_JTAG_DEVICE_ERROR;
3599                 }
3600
3601                 if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3602                                 SIGNALYZER_COMMAND_GPIO_MODE)) != FT_OK)
3603                 {
3604                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3605                                         status);
3606                         return ERROR_JTAG_DEVICE_ERROR;
3607                 }
3608
3609                 /* set gpio register */
3610                 if ((status = signalyzer_h_ctrl_write(
3611                                 SIGNALYZER_DATA_BUFFER_ADDR,
3612                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3613                 {
3614                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3615                                         status);
3616                         return ERROR_JTAG_DEVICE_ERROR;
3617                 }
3618
3619                 if ((status = signalyzer_h_ctrl_write(
3620                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x4040))
3621                         != FT_OK)
3622                 {
3623                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3624                                         status);
3625                         return ERROR_JTAG_DEVICE_ERROR;
3626                 }
3627
3628                 if ((status = signalyzer_h_ctrl_write(
3629                                 SIGNALYZER_COMMAND_ADDR,
3630                                 SIGNALYZER_COMMAND_GPIO_STATE)) != FT_OK)
3631                 {
3632                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3633                                         status);
3634                         return ERROR_JTAG_DEVICE_ERROR;
3635                 }
3636 #endif
3637         }
3638
3639         /* ADAPTOR: EM_ARM_JTAG, EM_ARM_JTAG_P, EM_JTAG, EM_JTAG_P */
3640         else if ((signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG) ||
3641                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P) ||
3642                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG)  ||
3643                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG_P))
3644         {
3645                 if (signalyzer_h_adapter_type
3646                                 == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG)
3647                         LOG_INFO("Signalyzer: EM-ARM-JTAG (ARM JTAG) "
3648                                 "detected. (HW: %2x).", (read_buf[1] >> 8));
3649                 else if (signalyzer_h_adapter_type
3650                                 == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P)
3651                         LOG_INFO("Signalyzer: EM-ARM-JTAG_P "
3652                                 "(ARM JTAG with PSU) detected. (HW: %2x).",
3653                                 (read_buf[1] >> 8));
3654                 else if (signalyzer_h_adapter_type
3655                                 == SIGNALYZER_MODULE_TYPE_EM_JTAG)
3656                         LOG_INFO("Signalyzer: EM-JTAG (Generic JTAG) "
3657                                 "detected. (HW: %2x).", (read_buf[1] >> 8));
3658                 else if (signalyzer_h_adapter_type
3659                                 == SIGNALYZER_MODULE_TYPE_EM_JTAG_P)
3660                         LOG_INFO("Signalyzer: EM-JTAG-P "
3661                                 "(Generic JTAG with PSU) detected. (HW: %2x).",
3662                                 (read_buf[1] >> 8));
3663
3664                 nTRST          = 0x02;
3665                 nTRSTnOE       = 0x04;
3666                 nSRST          = 0x08;
3667                 nSRSTnOE       = 0x10;
3668
3669                 low_output     = 0x08;
3670                 low_direction  = 0x1b;
3671
3672                 high_output    = 0x0;
3673                 high_direction = 0x1f;
3674
3675                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3676                 {
3677                         high_output |= nTRSTnOE;
3678                         high_output &= ~nTRST;
3679                 }
3680                 else
3681                 {
3682                         high_output &= ~nTRSTnOE;
3683                         high_output |= nTRST;
3684                 }
3685
3686                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3687                 {
3688                         high_output &= ~nSRSTnOE;
3689                         high_output |= nSRST;
3690                 }
3691                 else
3692                 {
3693                         high_output |= nSRSTnOE;
3694                         high_output &= ~nSRST;
3695                 }
3696
3697 #if BUILD_FT2232_FTD2XX == 1
3698                 /* enable power to the module */
3699                 if ((status = signalyzer_h_ctrl_write(
3700                                 SIGNALYZER_DATA_BUFFER_ADDR,
3701                                 ((uint32_t)(signalyzer_h_side << 8) | 0x01)))
3702                         != FT_OK)
3703                 {
3704                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3705                                         status);
3706                         return ERROR_JTAG_DEVICE_ERROR;
3707                 }
3708
3709                 if ((status = signalyzer_h_ctrl_write(
3710                                 SIGNALYZER_COMMAND_ADDR,
3711                                 SIGNALYZER_COMMAND_POWERCONTROL_SET)) != FT_OK)
3712                 {
3713                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3714                                         status);
3715                         return ERROR_JTAG_DEVICE_ERROR;
3716                 }
3717
3718                 /* set gpio mode register (IO_16 and IO_17 set as analog
3719                  * inputs, other is gpio)
3720                  */
3721                 if ((status = signalyzer_h_ctrl_write(
3722                                 SIGNALYZER_DATA_BUFFER_ADDR,
3723                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3724                 {
3725                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3726                                         status);
3727                         return ERROR_JTAG_DEVICE_ERROR;
3728                 }
3729
3730                 if ((status = signalyzer_h_ctrl_write(
3731                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x0060))
3732                         != FT_OK)
3733                 {
3734                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3735                                         status);
3736                         return ERROR_JTAG_DEVICE_ERROR;
3737                 }
3738
3739                 if ((status = signalyzer_h_ctrl_write(
3740                                 SIGNALYZER_COMMAND_ADDR,
3741                                 SIGNALYZER_COMMAND_GPIO_MODE)) != FT_OK)
3742                 {
3743                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3744                                         status);
3745                         return ERROR_JTAG_DEVICE_ERROR;
3746                 }
3747
3748                 /* set gpio register (all inputs, for -P modules,
3749                  * PSU will be turned off)
3750                  */
3751                 if ((status = signalyzer_h_ctrl_write(
3752                                 SIGNALYZER_DATA_BUFFER_ADDR,
3753                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3754                 {
3755                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3756                                         status);
3757                         return ERROR_JTAG_DEVICE_ERROR;
3758                 }
3759
3760                 if ((status = signalyzer_h_ctrl_write(
3761                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x0000))
3762                         != FT_OK)
3763                 {
3764                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3765                                         status);
3766                         return ERROR_JTAG_DEVICE_ERROR;
3767                 }
3768
3769                 if ((status = signalyzer_h_ctrl_write(
3770                                 SIGNALYZER_COMMAND_ADDR,
3771                                 SIGNALYZER_COMMAND_GPIO_STATE)) != FT_OK)
3772                 {
3773                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3774                                         status);
3775                         return ERROR_JTAG_DEVICE_ERROR;
3776                 }
3777 #endif
3778         }
3779
3780         else if (signalyzer_h_adapter_type == 0x0000)
3781         {
3782                 LOG_INFO("Signalyzer: No external modules were detected.");
3783
3784                 nTRST    = 0x10;
3785                 nTRSTnOE = 0x10;
3786                 nSRST    = 0x20;
3787                 nSRSTnOE = 0x20;
3788
3789                 low_output     = 0x08;
3790                 low_direction  = 0x1b;
3791
3792                 high_output    = 0x0;
3793                 high_direction = 0x0;
3794
3795                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3796                 {
3797                         low_direction &= ~nTRSTnOE; /* nTRST input */
3798                         low_output    &= ~nTRST;    /* nTRST = 0 */
3799                 }
3800                 else
3801                 {
3802                         low_direction |= nTRSTnOE;  /* nTRST output */
3803                         low_output    |= nTRST;     /* nTRST = 1 */
3804                 }
3805
3806                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3807                 {
3808                         low_direction |= nSRSTnOE;  /* nSRST output */
3809                         low_output    |= nSRST;     /* nSRST = 1 */
3810                 }
3811                 else
3812                 {
3813                         low_direction &= ~nSRSTnOE; /* nSRST input */
3814                         low_output    &= ~nSRST;    /* nSRST = 0 */
3815                 }
3816         }
3817         else
3818         {
3819                 LOG_ERROR("Unknown module type is detected: %.4x",
3820                                 signalyzer_h_adapter_type);
3821                 return ERROR_JTAG_DEVICE_ERROR;
3822         }
3823
3824         /* initialize low byte of controller for jtag operation */
3825         buf[0] = 0x80;
3826         buf[1] = low_output;
3827         buf[2] = low_direction;
3828
3829         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK)
3830                         || (bytes_written != 3))
3831         {
3832                 LOG_ERROR("couldn't initialize Signalyzer-H layout");
3833                 return ERROR_JTAG_INIT_FAILED;
3834         }
3835
3836 #if BUILD_FT2232_FTD2XX == 1
3837         if (ftdi_device == FT_DEVICE_2232H)
3838         {
3839                 /* initialize high byte of controller for jtag operation */
3840                 buf[0] = 0x82;
3841                 buf[1] = high_output;
3842                 buf[2] = high_direction;
3843
3844                 if ((ft2232_write(buf, 3, &bytes_written) != ERROR_OK)
3845                                 || (bytes_written != 3))
3846                 {
3847                         LOG_ERROR("couldn't initialize Signalyzer-H layout");
3848                         return ERROR_JTAG_INIT_FAILED;
3849                 }
3850         }
3851 #elif BUILD_FT2232_LIBFTDI == 1
3852         if (ftdi_device == TYPE_2232H)
3853         {
3854                 /* initialize high byte of controller for jtag operation */
3855                 buf[0] = 0x82;
3856                 buf[1] = high_output;
3857                 buf[2] = high_direction;
3858
3859                 if ((ft2232_write(buf, 3, &bytes_written) != ERROR_OK)
3860                                 || (bytes_written != 3))
3861                 {
3862                         LOG_ERROR("couldn't initialize Signalyzer-H layout");
3863                         return ERROR_JTAG_INIT_FAILED;
3864                 }
3865         }
3866 #endif
3867         return ERROR_OK;
3868 }
3869
3870 static void signalyzer_h_reset(int trst, int srst)
3871 {
3872         enum reset_types jtag_reset_config = jtag_get_reset_config();
3873
3874         /* ADAPTOR: EM_LT16_A */
3875         if (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_LT16_A)
3876         {
3877                 if (trst == 1)
3878                 {
3879                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3880                                 /* switch to output pin (output is low) */
3881                                 low_direction |= nTRSTnOE;
3882                         else
3883                                 /* switch output low */
3884                                 low_output &= ~nTRST;
3885                 }
3886                 else if (trst == 0)
3887                 {
3888                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3889                                 /* switch to input pin (high-Z + internal
3890                                  * and external pullup) */
3891                                 low_direction &= ~nTRSTnOE;
3892                         else
3893                                 /* switch output high */
3894                                 low_output |= nTRST;
3895                 }
3896
3897                 if (srst == 1)
3898                 {
3899                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3900                                 /* switch output low */
3901                                 low_output &= ~nSRST;
3902                         else
3903                                 /* switch to output pin (output is low) */
3904                                 low_direction |= nSRSTnOE;
3905                 }
3906                 else if (srst == 0)
3907                 {
3908                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3909                                 /* switch output high */
3910                                 low_output |= nSRST;
3911                         else
3912                                 /* switch to input pin (high-Z) */
3913                                 low_direction &= ~nSRSTnOE;
3914                 }
3915
3916                 /* command "set data bits low byte" */
3917                 buffer_write(0x80);
3918                 buffer_write(low_output);
3919                 buffer_write(low_direction);
3920                 LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, "
3921                                 "low_direction: 0x%2.2x",
3922                                 trst, srst, low_output, low_direction);
3923         }
3924         /* ADAPTOR: EM_ARM_JTAG,  EM_ARM_JTAG_P, EM_JTAG, EM_JTAG_P */
3925         else if ((signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG) ||
3926                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P) ||
3927                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG)  ||
3928                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG_P))
3929         {
3930                 if (trst == 1)
3931                 {
3932                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3933                                 high_output &= ~nTRSTnOE;
3934                         else
3935                                 high_output &= ~nTRST;
3936                 }
3937                 else if (trst == 0)
3938                 {
3939                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3940                                 high_output |= nTRSTnOE;
3941                         else
3942                                 high_output |= nTRST;
3943                 }
3944
3945                 if (srst == 1)
3946                 {
3947                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3948                                 high_output &= ~nSRST;
3949                         else
3950                                 high_output &= ~nSRSTnOE;
3951                 }
3952                 else if (srst == 0)
3953                 {
3954                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3955                                 high_output |= nSRST;
3956                         else
3957                                 high_output |= nSRSTnOE;
3958                 }
3959
3960                 /* command "set data bits high byte" */
3961                 buffer_write(0x82);
3962                 buffer_write(high_output);
3963                 buffer_write(high_direction);
3964                 LOG_INFO("trst: %i, srst: %i, high_output: 0x%2.2x, "
3965                                 "high_direction: 0x%2.2x",
3966                                 trst, srst, high_output, high_direction);
3967         }
3968         else if (signalyzer_h_adapter_type == 0x0000)
3969         {
3970                 if (trst == 1)
3971                 {
3972                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3973                                 /* switch to output pin (output is low) */
3974                                 low_direction |= nTRSTnOE;
3975                         else
3976                                 /* switch output low */
3977                                 low_output &= ~nTRST;
3978                 }
3979                 else if (trst == 0)
3980                 {
3981                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3982                                 /* switch to input pin (high-Z + internal
3983                                  * and external pullup) */
3984                                 low_direction &= ~nTRSTnOE;
3985                         else
3986                                 /* switch output high */
3987                                 low_output |= nTRST;
3988                 }
3989
3990                 if (srst == 1)
3991                 {
3992                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3993                                 /* switch output low */
3994                                 low_output &= ~nSRST;
3995                         else
3996                                 /* switch to output pin (output is low) */
3997                                 low_direction |= nSRSTnOE;
3998                 }
3999                 else if (srst == 0)
4000                 {
4001                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4002                                 /* switch output high */
4003                                 low_output |= nSRST;
4004                         else
4005                                 /* switch to input pin (high-Z) */
4006                                 low_direction &= ~nSRSTnOE;
4007                 }
4008
4009                 /* command "set data bits low byte" */
4010                 buffer_write(0x80);
4011                 buffer_write(low_output);
4012                 buffer_write(low_direction);
4013                 LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, "
4014                                 "low_direction: 0x%2.2x",
4015                                 trst, srst, low_output, low_direction);
4016         }
4017 }
4018
4019 static void signalyzer_h_blink(void)
4020 {
4021         signalyzer_h_led_set(signalyzer_h_side, SIGNALYZER_LED_RED, 100, 0, 1);
4022 }
4023
4024 /********************************************************************
4025  * Support for KT-LINK
4026  * JTAG adapter from KRISTECH
4027  * http://www.kristech.eu
4028  *******************************************************************/
4029 static int ktlink_init(void)
4030 {
4031         uint8_t  buf[3];
4032         uint32_t bytes_written;
4033         uint8_t  swd_en = 0x20; //0x20 SWD disable, 0x00 SWD enable (ADBUS5)
4034
4035         low_output    = 0x08 | swd_en; // value; TMS=1,TCK=0,TDI=0,SWD=swd_en
4036         low_direction = 0x3B;          // out=1; TCK/TDI/TMS=out,TDO=in,SWD=out,RTCK=in,SRSTIN=in
4037
4038         // initialize low port
4039         buf[0] = 0x80;          // command "set data bits low byte"
4040         buf[1] = low_output;
4041         buf[2] = low_direction;
4042         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
4043
4044         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
4045         {
4046                 LOG_ERROR("couldn't initialize FT2232 with 'ktlink' layout");
4047                 return ERROR_JTAG_INIT_FAILED;
4048         }
4049
4050         nTRST    = 0x01;
4051         nSRST    = 0x02;
4052         nTRSTnOE = 0x04;
4053         nSRSTnOE = 0x08;
4054
4055         high_output    = 0x80; // turn LED on
4056         high_direction = 0xFF; // all outputs
4057
4058         enum reset_types jtag_reset_config = jtag_get_reset_config();
4059
4060         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN) {
4061                 high_output |= nTRSTnOE;
4062                 high_output &= ~nTRST;
4063         } else {
4064                 high_output &= ~nTRSTnOE;
4065                 high_output |= nTRST;
4066         }
4067
4068         if (jtag_reset_config & RESET_SRST_PUSH_PULL) {
4069                 high_output &= ~nSRSTnOE;
4070                 high_output |= nSRST;
4071         } else {
4072                 high_output |= nSRSTnOE;
4073                 high_output &= ~nSRST;
4074         }
4075
4076         // initialize high port
4077         buf[0] = 0x82;              // command "set data bits high byte"
4078         buf[1] = high_output;       // value
4079         buf[2] = high_direction;
4080         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
4081
4082         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
4083         {
4084                 LOG_ERROR("couldn't initialize FT2232 with 'ktlink' layout");
4085                 return ERROR_JTAG_INIT_FAILED;
4086         }
4087
4088         return ERROR_OK;
4089 }
4090
4091 static void ktlink_reset(int trst, int srst)
4092 {
4093         enum reset_types jtag_reset_config = jtag_get_reset_config();
4094
4095         if (trst == 1) {
4096                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4097                         high_output &= ~nTRSTnOE;
4098                 else
4099                         high_output &= ~nTRST;
4100         } else if (trst == 0) {
4101                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4102                         high_output |= nTRSTnOE;
4103                 else
4104                         high_output |= nTRST;
4105         }
4106
4107         if (srst == 1) {
4108                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4109                         high_output &= ~nSRST;
4110                 else
4111                         high_output &= ~nSRSTnOE;
4112         } else if (srst == 0) {
4113                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4114                         high_output |= nSRST;
4115                 else
4116                         high_output |= nSRSTnOE;
4117         }
4118
4119         buffer_write(0x82); // command "set data bits high byte"
4120         buffer_write(high_output);
4121         buffer_write(high_direction);
4122         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,high_direction);
4123 }
4124
4125 static void ktlink_blink(void)
4126 {
4127         /* LED connected to ACBUS7 */
4128         if (high_output & 0x80)
4129                 high_output &= 0x7F;
4130         else
4131                 high_output |= 0x80;
4132
4133         buffer_write(0x82);  // command "set data bits high byte"
4134         buffer_write(high_output);
4135         buffer_write(high_direction);
4136 }
4137
4138 static const struct command_registration ft2232_command_handlers[] = {
4139         {
4140                 .name = "ft2232_device_desc",
4141                 .handler = &ft2232_handle_device_desc_command,
4142                 .mode = COMMAND_CONFIG,
4143                 .help = "set the USB device description of the FTDI FT2232 device",
4144                 .usage = "description_string",
4145         },
4146         {
4147                 .name = "ft2232_serial",
4148                 .handler = &ft2232_handle_serial_command,
4149                 .mode = COMMAND_CONFIG,
4150                 .help = "set the serial number of the FTDI FT2232 device",
4151                 .usage = "serial_string",
4152         },
4153         {
4154                 .name = "ft2232_layout",
4155                 .handler = &ft2232_handle_layout_command,
4156                 .mode = COMMAND_CONFIG,
4157                 .help = "set the layout of the FT2232 GPIO signals used "
4158                         "to control output-enables and reset signals",
4159                 .usage = "layout_name",
4160         },
4161         {
4162                 .name = "ft2232_vid_pid",
4163                 .handler = &ft2232_handle_vid_pid_command,
4164                 .mode = COMMAND_CONFIG,
4165                 .help = "the vendor ID and product ID of the FTDI FT2232 device",
4166                 .usage = "(vid pid)* ",
4167         },
4168         {
4169                 .name = "ft2232_latency",
4170                 .handler = &ft2232_handle_latency_command,
4171                 .mode = COMMAND_CONFIG,
4172                 .help = "set the FT2232 latency timer to a new value",
4173                 .usage = "value",
4174         },
4175         COMMAND_REGISTRATION_DONE
4176 };
4177
4178 struct jtag_interface ft2232_interface = {
4179         .name = "ft2232",
4180         .supported = DEBUG_CAP_TMS_SEQ,
4181         .commands = ft2232_command_handlers,
4182
4183         .init = ft2232_init,
4184         .quit = ft2232_quit,
4185         .speed = ft2232_speed,
4186         .speed_div = ft2232_speed_div,
4187         .khz = ft2232_khz,
4188         .execute_queue = ft2232_execute_queue,
4189 };