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