881d7c772b79ac01f729326e65ee2db75ca4c56a
[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         }
1349
1350         return ERROR_OK;
1351 }
1352
1353 static int ft2232_predict_scan_out(int scan_size, enum scan_type type)
1354 {
1355         int predicted_size = 3;
1356         int num_bytes = (scan_size - 1) / 8;
1357
1358         if (tap_get_state() != TAP_DRSHIFT)
1359                 predicted_size += get_tms_buffer_requirements(tap_get_tms_path_len(tap_get_state(), TAP_DRSHIFT));
1360
1361         if (type == SCAN_IN)    /* only from device to host */
1362         {
1363                 /* complete bytes */
1364                 predicted_size += DIV_ROUND_UP(num_bytes, 65536) * 3;
1365
1366                 /* remaining bits - 1 (up to 7) */
1367                 predicted_size += ((scan_size - 1) % 8) ? 2 : 0;
1368         }
1369         else    /* host to device, or bidirectional */
1370         {
1371                 /* complete bytes */
1372                 predicted_size += num_bytes + DIV_ROUND_UP(num_bytes, 65536) * 3;
1373
1374                 /* remaining bits -1 (up to 7) */
1375                 predicted_size += ((scan_size - 1) % 8) ? 3 : 0;
1376         }
1377
1378         return predicted_size;
1379 }
1380
1381 static int ft2232_predict_scan_in(int scan_size, enum scan_type type)
1382 {
1383         int predicted_size = 0;
1384
1385         if (type != SCAN_OUT)
1386         {
1387                 /* complete bytes */
1388                 predicted_size += (DIV_ROUND_UP(scan_size, 8) > 1) ? (DIV_ROUND_UP(scan_size, 8) - 1) : 0;
1389
1390                 /* remaining bits - 1 */
1391                 predicted_size += ((scan_size - 1) % 8) ? 1 : 0;
1392
1393                 /* last bit (from TMS scan) */
1394                 predicted_size += 1;
1395         }
1396
1397         /* LOG_DEBUG("scan_size: %i, predicted_size: %i", scan_size, predicted_size); */
1398
1399         return predicted_size;
1400 }
1401
1402 /* semi-generic FT2232/FT4232 reset code */
1403 static void ftx23_reset(int trst, int srst)
1404 {
1405         enum reset_types jtag_reset_config = jtag_get_reset_config();
1406         if (trst == 1)
1407         {
1408                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1409                         low_direction |= nTRSTnOE;      /* switch to output pin (output is low) */
1410                 else
1411                         low_output &= ~nTRST;           /* switch output low */
1412         }
1413         else if (trst == 0)
1414         {
1415                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1416                         low_direction &= ~nTRSTnOE;     /* switch to input pin (high-Z + internal and external pullup) */
1417                 else
1418                         low_output |= nTRST;            /* switch output high */
1419         }
1420
1421         if (srst == 1)
1422         {
1423                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1424                         low_output &= ~nSRST;           /* switch output low */
1425                 else
1426                         low_direction |= nSRSTnOE;      /* switch to output pin (output is low) */
1427         }
1428         else if (srst == 0)
1429         {
1430                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1431                         low_output |= nSRST;            /* switch output high */
1432                 else
1433                         low_direction &= ~nSRSTnOE;     /* switch to input pin (high-Z) */
1434         }
1435
1436         /* command "set data bits low byte" */
1437         buffer_write(0x80);
1438         buffer_write(low_output);
1439         buffer_write(low_direction);
1440 }
1441
1442 static void jtagkey_reset(int trst, int srst)
1443 {
1444         enum reset_types jtag_reset_config = jtag_get_reset_config();
1445         if (trst == 1)
1446         {
1447                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1448                         high_output &= ~nTRSTnOE;
1449                 else
1450                         high_output &= ~nTRST;
1451         }
1452         else if (trst == 0)
1453         {
1454                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1455                         high_output |= nTRSTnOE;
1456                 else
1457                         high_output |= nTRST;
1458         }
1459
1460         if (srst == 1)
1461         {
1462                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1463                         high_output &= ~nSRST;
1464                 else
1465                         high_output &= ~nSRSTnOE;
1466         }
1467         else if (srst == 0)
1468         {
1469                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1470                         high_output |= nSRST;
1471                 else
1472                         high_output |= nSRSTnOE;
1473         }
1474
1475         /* command "set data bits high byte" */
1476         buffer_write(0x82);
1477         buffer_write(high_output);
1478         buffer_write(high_direction);
1479         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1480                         high_direction);
1481 }
1482
1483 static void olimex_jtag_reset(int trst, int srst)
1484 {
1485         enum reset_types jtag_reset_config = jtag_get_reset_config();
1486         if (trst == 1)
1487         {
1488                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1489                         high_output &= ~nTRSTnOE;
1490                 else
1491                         high_output &= ~nTRST;
1492         }
1493         else if (trst == 0)
1494         {
1495                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1496                         high_output |= nTRSTnOE;
1497                 else
1498                         high_output |= nTRST;
1499         }
1500
1501         if (srst == 1)
1502         {
1503                 high_output |= nSRST;
1504         }
1505         else if (srst == 0)
1506         {
1507                 high_output &= ~nSRST;
1508         }
1509
1510         /* command "set data bits high byte" */
1511         buffer_write(0x82);
1512         buffer_write(high_output);
1513         buffer_write(high_direction);
1514         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1515                         high_direction);
1516 }
1517
1518 static void axm0432_jtag_reset(int trst, int srst)
1519 {
1520         if (trst == 1)
1521         {
1522                 tap_set_state(TAP_RESET);
1523                 high_output &= ~nTRST;
1524         }
1525         else if (trst == 0)
1526         {
1527                 high_output |= nTRST;
1528         }
1529
1530         if (srst == 1)
1531         {
1532                 high_output &= ~nSRST;
1533         }
1534         else if (srst == 0)
1535         {
1536                 high_output |= nSRST;
1537         }
1538
1539         /* command "set data bits low byte" */
1540         buffer_write(0x82);
1541         buffer_write(high_output);
1542         buffer_write(high_direction);
1543         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1544                         high_direction);
1545 }
1546
1547 static void flyswatter_reset(int trst, int srst)
1548 {
1549         if (trst == 1)
1550         {
1551                 low_output &= ~nTRST;
1552         }
1553         else if (trst == 0)
1554         {
1555                 low_output |= nTRST;
1556         }
1557
1558         if (srst == 1)
1559         {
1560                 low_output |= nSRST;
1561         }
1562         else if (srst == 0)
1563         {
1564                 low_output &= ~nSRST;
1565         }
1566
1567         /* command "set data bits low byte" */
1568         buffer_write(0x80);
1569         buffer_write(low_output);
1570         buffer_write(low_direction);
1571         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
1572 }
1573
1574 static void minimodule_reset(int trst, int srst)
1575 {
1576         if (srst == 1)
1577         {
1578                 low_output &= ~nSRST;
1579         }
1580         else if (srst == 0)
1581         {
1582                 low_output |= nSRST;
1583         }
1584
1585         /* command "set data bits low byte" */
1586         buffer_write(0x80);
1587         buffer_write(low_output);
1588         buffer_write(low_direction);
1589         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
1590 }
1591
1592 static void turtle_reset(int trst, int srst)
1593 {
1594         trst = trst;
1595
1596         if (srst == 1)
1597         {
1598                 low_output |= nSRST;
1599         }
1600         else if (srst == 0)
1601         {
1602                 low_output &= ~nSRST;
1603         }
1604
1605         /* command "set data bits low byte" */
1606         buffer_write(0x80);
1607         buffer_write(low_output);
1608         buffer_write(low_direction);
1609         LOG_DEBUG("srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", srst, low_output, low_direction);
1610 }
1611
1612 static void comstick_reset(int trst, int srst)
1613 {
1614         if (trst == 1)
1615         {
1616                 high_output &= ~nTRST;
1617         }
1618         else if (trst == 0)
1619         {
1620                 high_output |= nTRST;
1621         }
1622
1623         if (srst == 1)
1624         {
1625                 high_output &= ~nSRST;
1626         }
1627         else if (srst == 0)
1628         {
1629                 high_output |= nSRST;
1630         }
1631
1632         /* command "set data bits high byte" */
1633         buffer_write(0x82);
1634         buffer_write(high_output);
1635         buffer_write(high_direction);
1636         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1637                         high_direction);
1638 }
1639
1640 static void stm32stick_reset(int trst, int srst)
1641 {
1642         if (trst == 1)
1643         {
1644                 high_output &= ~nTRST;
1645         }
1646         else if (trst == 0)
1647         {
1648                 high_output |= nTRST;
1649         }
1650
1651         if (srst == 1)
1652         {
1653                 low_output &= ~nSRST;
1654         }
1655         else if (srst == 0)
1656         {
1657                 low_output |= nSRST;
1658         }
1659
1660         /* command "set data bits low byte" */
1661         buffer_write(0x80);
1662         buffer_write(low_output);
1663         buffer_write(low_direction);
1664
1665         /* command "set data bits high byte" */
1666         buffer_write(0x82);
1667         buffer_write(high_output);
1668         buffer_write(high_direction);
1669         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1670                         high_direction);
1671 }
1672
1673 static void sheevaplug_reset(int trst, int srst)
1674 {
1675         if (trst == 1)
1676                 high_output &= ~nTRST;
1677         else if (trst == 0)
1678                 high_output |= nTRST;
1679
1680         if (srst == 1)
1681                 high_output &= ~nSRSTnOE;
1682         else if (srst == 0)
1683                 high_output |= nSRSTnOE;
1684
1685         /* command "set data bits high byte" */
1686         buffer_write(0x82);
1687         buffer_write(high_output);
1688         buffer_write(high_direction);
1689         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output, high_direction);
1690 }
1691
1692 static void redbee_reset(int trst, int srst)
1693 {
1694         if (trst == 1)
1695         {
1696                 tap_set_state(TAP_RESET);
1697                 high_output &= ~nTRST;
1698         }
1699         else if (trst == 0)
1700         {
1701                 high_output |= nTRST;
1702         }
1703
1704         if (srst == 1)
1705         {
1706                 high_output &= ~nSRST;
1707         }
1708         else if (srst == 0)
1709         {
1710                 high_output |= nSRST;
1711         }
1712
1713         /* command "set data bits low byte" */
1714         buffer_write(0x82);
1715         buffer_write(high_output);
1716         buffer_write(high_direction);
1717         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, "
1718                         "high_direction: 0x%2.2x", trst, srst, high_output,
1719                         high_direction);
1720 }
1721
1722 static void xds100v2_reset(int trst, int srst)
1723 {
1724         if (trst == 1)
1725         {
1726                 tap_set_state(TAP_RESET);
1727                 high_output &= ~nTRST;
1728         }
1729         else if (trst == 0)
1730         {
1731                 high_output |= nTRST;
1732         }
1733
1734         if (srst == 1)
1735         {
1736                 high_output |= nSRST;
1737         }
1738         else if (srst == 0)
1739         {
1740                 high_output &= ~nSRST;
1741         }
1742
1743         /* command "set data bits low byte" */
1744         buffer_write(0x82);
1745         buffer_write(high_output);
1746         buffer_write(high_direction);
1747         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, "
1748                         "high_direction: 0x%2.2x", trst, srst, high_output,
1749                         high_direction);
1750 }
1751
1752 static int ft2232_execute_runtest(struct jtag_command *cmd)
1753 {
1754         int retval;
1755         int i;
1756         int predicted_size = 0;
1757         retval = ERROR_OK;
1758
1759         DEBUG_JTAG_IO("runtest %i cycles, end in %s",
1760                         cmd->cmd.runtest->num_cycles,
1761                         tap_state_name(cmd->cmd.runtest->end_state));
1762
1763         /* only send the maximum buffer size that FT2232C can handle */
1764         predicted_size = 0;
1765         if (tap_get_state() != TAP_IDLE)
1766                 predicted_size += 3;
1767         predicted_size += 3 * DIV_ROUND_UP(cmd->cmd.runtest->num_cycles, 7);
1768         if (cmd->cmd.runtest->end_state != TAP_IDLE)
1769                 predicted_size += 3;
1770         if (tap_get_end_state() != TAP_IDLE)
1771                 predicted_size += 3;
1772         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1773         {
1774                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1775                         retval = ERROR_JTAG_QUEUE_FAILED;
1776                 require_send = 0;
1777                 first_unsent = cmd;
1778         }
1779         if (tap_get_state() != TAP_IDLE)
1780         {
1781                 move_to_state(TAP_IDLE);
1782                 require_send = 1;
1783         }
1784         i = cmd->cmd.runtest->num_cycles;
1785         while (i > 0)
1786         {
1787                 /* there are no state transitions in this code, so omit state tracking */
1788
1789                 /* command "Clock Data to TMS/CS Pin (no Read)" */
1790                 buffer_write(0x4b);
1791
1792                 /* scan 7 bits */
1793                 buffer_write((i > 7) ? 6 : (i - 1));
1794
1795                 /* TMS data bits */
1796                 buffer_write(0x0);
1797
1798                 i -= (i > 7) ? 7 : i;
1799                 /* LOG_DEBUG("added TMS scan (no read)"); */
1800         }
1801
1802         ft2232_end_state(cmd->cmd.runtest->end_state);
1803
1804         if (tap_get_state() != tap_get_end_state())
1805         {
1806                 move_to_state(tap_get_end_state());
1807         }
1808
1809         require_send = 1;
1810         DEBUG_JTAG_IO("runtest: %i, end in %s",
1811                         cmd->cmd.runtest->num_cycles,
1812                         tap_state_name(tap_get_end_state()));
1813         return retval;
1814 }
1815
1816 static int ft2232_execute_statemove(struct jtag_command *cmd)
1817 {
1818         int     predicted_size = 0;
1819         int     retval = ERROR_OK;
1820
1821         DEBUG_JTAG_IO("statemove end in %s",
1822                         tap_state_name(cmd->cmd.statemove->end_state));
1823
1824         /* only send the maximum buffer size that FT2232C can handle */
1825         predicted_size = 3;
1826         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1827         {
1828                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1829                         retval = ERROR_JTAG_QUEUE_FAILED;
1830                 require_send = 0;
1831                 first_unsent = cmd;
1832         }
1833         ft2232_end_state(cmd->cmd.statemove->end_state);
1834
1835         /* For TAP_RESET, ignore the current recorded state.  It's often
1836          * wrong at server startup, and this transation is critical whenever
1837          * it's requested.
1838          */
1839         if (tap_get_end_state() == TAP_RESET) {
1840                 clock_tms(0x4b,  0xff, 5, 0);
1841                 require_send = 1;
1842
1843         /* shortest-path move to desired end state */
1844         } else if (tap_get_state() != tap_get_end_state())
1845         {
1846                 move_to_state(tap_get_end_state());
1847                 require_send = 1;
1848         }
1849
1850         return retval;
1851 }
1852
1853 /**
1854  * Clock a bunch of TMS (or SWDIO) transitions, to change the JTAG
1855  * (or SWD) state machine.
1856  */
1857 static int ft2232_execute_tms(struct jtag_command *cmd)
1858 {
1859         int             retval = ERROR_OK;
1860         unsigned        num_bits = cmd->cmd.tms->num_bits;
1861         const uint8_t   *bits = cmd->cmd.tms->bits;
1862         unsigned        count;
1863
1864         DEBUG_JTAG_IO("TMS: %d bits", num_bits);
1865
1866         /* only send the maximum buffer size that FT2232C can handle */
1867         count = 3 * DIV_ROUND_UP(num_bits, 4);
1868         if (ft2232_buffer_size + 3*count + 1 > FT2232_BUFFER_SIZE) {
1869                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1870                         retval = ERROR_JTAG_QUEUE_FAILED;
1871
1872                 require_send = 0;
1873                 first_unsent = cmd;
1874         }
1875
1876         /* Shift out in batches of at most 6 bits; there's a report of an
1877          * FT2232 bug in this area, where shifting exactly 7 bits can make
1878          * problems with TMS signaling for the last clock cycle:
1879          *
1880          *    http://developer.intra2net.com/mailarchive/html/
1881          *              libftdi/2009/msg00292.html
1882          *
1883          * Command 0x4b is: "Clock Data to TMS/CS Pin (no Read)"
1884          *
1885          * Note that pathmoves in JTAG are not often seven bits, so that
1886          * isn't a particularly likely situation outside of "special"
1887          * signaling such as switching between JTAG and SWD modes.
1888          */
1889         while (num_bits) {
1890                 if (num_bits <= 6) {
1891                         buffer_write(0x4b);
1892                         buffer_write(num_bits - 1);
1893                         buffer_write(*bits & 0x3f);
1894                         break;
1895                 }
1896
1897                 /* Yes, this is lazy ... we COULD shift out more data
1898                  * bits per operation, but doing it in nybbles is easy
1899                  */
1900                 buffer_write(0x4b);
1901                 buffer_write(3);
1902                 buffer_write(*bits & 0xf);
1903                 num_bits -= 4;
1904
1905                 count  = (num_bits > 4) ? 4 : num_bits;
1906
1907                 buffer_write(0x4b);
1908                 buffer_write(count - 1);
1909                 buffer_write((*bits >> 4) & 0xf);
1910                 num_bits -= count;
1911
1912                 bits++;
1913         }
1914
1915         require_send = 1;
1916         return retval;
1917 }
1918
1919 static int ft2232_execute_pathmove(struct jtag_command *cmd)
1920 {
1921         int     predicted_size = 0;
1922         int     retval = ERROR_OK;
1923
1924         tap_state_t*     path = cmd->cmd.pathmove->path;
1925         int     num_states    = cmd->cmd.pathmove->num_states;
1926
1927         DEBUG_JTAG_IO("pathmove: %i states, current: %s  end: %s", num_states,
1928                         tap_state_name(tap_get_state()),
1929                         tap_state_name(path[num_states-1]));
1930
1931         /* only send the maximum buffer size that FT2232C can handle */
1932         predicted_size = 3 * DIV_ROUND_UP(num_states, 7);
1933         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1934         {
1935                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1936                         retval = ERROR_JTAG_QUEUE_FAILED;
1937
1938                 require_send = 0;
1939                 first_unsent = cmd;
1940         }
1941
1942         ft2232_add_pathmove(path, num_states);
1943         require_send = 1;
1944
1945         return retval;
1946 }
1947
1948 static int ft2232_execute_scan(struct jtag_command *cmd)
1949 {
1950         uint8_t* buffer;
1951         int scan_size;                          /* size of IR or DR scan */
1952         int predicted_size = 0;
1953         int retval = ERROR_OK;
1954
1955         enum scan_type  type = jtag_scan_type(cmd->cmd.scan);
1956
1957         DEBUG_JTAG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN", type);
1958
1959         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
1960
1961         predicted_size = ft2232_predict_scan_out(scan_size, type);
1962         if ((predicted_size + 1) > FT2232_BUFFER_SIZE)
1963         {
1964                 LOG_DEBUG("oversized ft2232 scan (predicted_size > FT2232_BUFFER_SIZE)");
1965                 /* unsent commands before this */
1966                 if (first_unsent != cmd)
1967                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1968                                 retval = ERROR_JTAG_QUEUE_FAILED;
1969
1970                 /* current command */
1971                 ft2232_end_state(cmd->cmd.scan->end_state);
1972                 ft2232_large_scan(cmd->cmd.scan, type, buffer, scan_size);
1973                 require_send = 0;
1974                 first_unsent = cmd->next;
1975                 if (buffer)
1976                         free(buffer);
1977                 return retval;
1978         }
1979         else if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1980         {
1981                 LOG_DEBUG("ft2232 buffer size reached, sending queued commands (first_unsent: %p, cmd: %p)",
1982                                 first_unsent,
1983                                 cmd);
1984                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1985                         retval = ERROR_JTAG_QUEUE_FAILED;
1986                 require_send = 0;
1987                 first_unsent = cmd;
1988         }
1989         ft2232_expect_read += ft2232_predict_scan_in(scan_size, type);
1990         /* LOG_DEBUG("new read size: %i", ft2232_expect_read); */
1991         ft2232_end_state(cmd->cmd.scan->end_state);
1992         ft2232_add_scan(cmd->cmd.scan->ir_scan, type, buffer, scan_size);
1993         require_send = 1;
1994         if (buffer)
1995                 free(buffer);
1996         DEBUG_JTAG_IO("%s scan, %i bits, end in %s",
1997                         (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1998                         tap_state_name(tap_get_end_state()));
1999         return retval;
2000
2001 }
2002
2003 static int ft2232_execute_reset(struct jtag_command *cmd)
2004 {
2005         int retval;
2006         int predicted_size = 0;
2007         retval = ERROR_OK;
2008
2009         DEBUG_JTAG_IO("reset trst: %i srst %i",
2010                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
2011
2012         /* only send the maximum buffer size that FT2232C can handle */
2013         predicted_size = 3;
2014         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
2015         {
2016                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
2017                         retval = ERROR_JTAG_QUEUE_FAILED;
2018                 require_send = 0;
2019                 first_unsent = cmd;
2020         }
2021
2022         if ((cmd->cmd.reset->trst == 1) || (cmd->cmd.reset->srst && (jtag_get_reset_config() & RESET_SRST_PULLS_TRST)))
2023         {
2024                 tap_set_state(TAP_RESET);
2025         }
2026
2027         layout->reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
2028         require_send = 1;
2029
2030         DEBUG_JTAG_IO("trst: %i, srst: %i",
2031                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
2032         return retval;
2033 }
2034
2035 static int ft2232_execute_sleep(struct jtag_command *cmd)
2036 {
2037         int retval;
2038         retval = ERROR_OK;
2039
2040         DEBUG_JTAG_IO("sleep %" PRIi32, cmd->cmd.sleep->us);
2041
2042         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
2043                                 retval = ERROR_JTAG_QUEUE_FAILED;
2044         first_unsent = cmd->next;
2045         jtag_sleep(cmd->cmd.sleep->us);
2046         DEBUG_JTAG_IO("sleep %" PRIi32 " usec while in %s",
2047                         cmd->cmd.sleep->us,
2048                         tap_state_name(tap_get_state()));
2049         return retval;
2050 }
2051
2052 static int ft2232_execute_stableclocks(struct jtag_command *cmd)
2053 {
2054         int retval;
2055         retval = ERROR_OK;
2056
2057         /* this is only allowed while in a stable state.  A check for a stable
2058          * state was done in jtag_add_clocks()
2059          */
2060         if (ft2232_stableclocks(cmd->cmd.stableclocks->num_cycles, cmd) != ERROR_OK)
2061                 retval = ERROR_JTAG_QUEUE_FAILED;
2062         DEBUG_JTAG_IO("clocks %i while in %s",
2063                         cmd->cmd.stableclocks->num_cycles,
2064                         tap_state_name(tap_get_state()));
2065         return retval;
2066 }
2067
2068 static int ft2232_execute_command(struct jtag_command *cmd)
2069 {
2070         int retval;
2071
2072         switch (cmd->type)
2073         {
2074         case JTAG_RESET:        retval = ft2232_execute_reset(cmd); break;
2075         case JTAG_RUNTEST:      retval = ft2232_execute_runtest(cmd); break;
2076         case JTAG_TLR_RESET: retval = ft2232_execute_statemove(cmd); break;
2077         case JTAG_PATHMOVE:     retval = ft2232_execute_pathmove(cmd); break;
2078         case JTAG_SCAN:         retval = ft2232_execute_scan(cmd); break;
2079         case JTAG_SLEEP:        retval = ft2232_execute_sleep(cmd); break;
2080         case JTAG_STABLECLOCKS: retval = ft2232_execute_stableclocks(cmd); break;
2081         case JTAG_TMS:
2082                 retval = ft2232_execute_tms(cmd);
2083                 break;
2084         default:
2085                 LOG_ERROR("BUG: unknown JTAG command type encountered");
2086                 retval = ERROR_JTAG_QUEUE_FAILED;
2087                 break;
2088         }
2089         return retval;
2090 }
2091
2092 static int ft2232_execute_queue(void)
2093 {
2094         struct jtag_command* cmd = jtag_command_queue;  /* currently processed command */
2095         int retval;
2096
2097         first_unsent = cmd;             /* next command that has to be sent */
2098         require_send = 0;
2099
2100         /* return ERROR_OK, unless ft2232_send_and_recv reports a failed check
2101          * that wasn't handled by a caller-provided error handler
2102          */
2103         retval = ERROR_OK;
2104
2105         ft2232_buffer_size = 0;
2106         ft2232_expect_read = 0;
2107
2108         /* blink, if the current layout has that feature */
2109         if (layout->blink)
2110                 layout->blink();
2111
2112         while (cmd)
2113         {
2114                 /* fill the write buffer with the desired command */
2115                 if (ft2232_execute_command(cmd) != ERROR_OK)
2116                         retval = ERROR_JTAG_QUEUE_FAILED;
2117                 /* Start reading input before FT2232 TX buffer fills up.
2118                  * Sometimes this happens because we don't know the
2119                  * length of the last command before we execute it. So
2120                  * we simple inform the user.
2121                  */
2122                 cmd = cmd->next;
2123
2124                 if (ft2232_expect_read >= FT2232_BUFFER_READ_QUEUE_SIZE )
2125                 {
2126                         if (ft2232_expect_read > (FT2232_BUFFER_READ_QUEUE_SIZE+1) )
2127                                 LOG_DEBUG("read buffer size looks too high %d/%d",ft2232_expect_read,(FT2232_BUFFER_READ_QUEUE_SIZE+1));
2128                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
2129                                 retval = ERROR_JTAG_QUEUE_FAILED;
2130                         first_unsent = cmd;
2131                 }
2132         }
2133
2134         if (require_send > 0)
2135                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
2136                         retval = ERROR_JTAG_QUEUE_FAILED;
2137
2138         return retval;
2139 }
2140
2141 #if BUILD_FT2232_FTD2XX == 1
2142 static int ft2232_init_ftd2xx(uint16_t vid, uint16_t pid, int more, int* try_more)
2143 {
2144         FT_STATUS       status;
2145         DWORD           deviceID;
2146         char            SerialNumber[16];
2147         char            Description[64];
2148         DWORD   openex_flags  = 0;
2149         char*   openex_string = NULL;
2150         uint8_t latency_timer;
2151
2152         if (layout == NULL) {
2153                 LOG_WARNING("No ft2232 layout specified'");
2154                 return ERROR_JTAG_INIT_FAILED;
2155         }
2156
2157         LOG_DEBUG("'ft2232' interface using FTD2XX with '%s' layout (%4.4x:%4.4x)", layout->name, vid, pid);
2158
2159 #if IS_WIN32 == 0
2160         /* Add non-standard Vid/Pid to the linux driver */
2161         if ((status = FT_SetVIDPID(vid, pid)) != FT_OK)
2162         {
2163                 LOG_WARNING("couldn't add %4.4x:%4.4x", vid, pid);
2164         }
2165 #endif
2166
2167         if (ft2232_device_desc && ft2232_serial)
2168         {
2169                 LOG_WARNING("can't open by device description and serial number, giving precedence to serial");
2170                 ft2232_device_desc = NULL;
2171         }
2172
2173         if (ft2232_device_desc)
2174         {
2175                 openex_string = ft2232_device_desc;
2176                 openex_flags  = FT_OPEN_BY_DESCRIPTION;
2177         }
2178         else if (ft2232_serial)
2179         {
2180                 openex_string = ft2232_serial;
2181                 openex_flags  = FT_OPEN_BY_SERIAL_NUMBER;
2182         }
2183         else
2184         {
2185                 LOG_ERROR("neither device description nor serial number specified");
2186                 LOG_ERROR("please add \"ft2232_device_desc <string>\" or \"ft2232_serial <string>\" to your .cfg file");
2187
2188                 return ERROR_JTAG_INIT_FAILED;
2189         }
2190
2191         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
2192         if (status != FT_OK) {
2193                 /* under Win32, the FTD2XX driver appends an "A" to the end
2194                  * of the description, if we tried by the desc, then
2195                  * try by the alternate "A" description. */
2196                 if (openex_string == ft2232_device_desc) {
2197                         /* Try the alternate method. */
2198                         openex_string = ft2232_device_desc_A;
2199                         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
2200                         if (status == FT_OK) {
2201                                 /* yea, the "alternate" method worked! */
2202                         } else {
2203                                 /* drat, give the user a meaningfull message.
2204                                  * telling the use we tried *BOTH* methods. */
2205                                 LOG_WARNING("Unable to open FTDI Device tried: '%s' and '%s'",
2206                                                         ft2232_device_desc,
2207                                                         ft2232_device_desc_A);
2208                         }
2209                 }
2210         }
2211
2212         if (status != FT_OK)
2213         {
2214                 DWORD num_devices;
2215
2216                 if (more)
2217                 {
2218                         LOG_WARNING("unable to open ftdi device (trying more): %s",
2219                                         ftd2xx_status_string(status));
2220                         *try_more = 1;
2221                         return ERROR_JTAG_INIT_FAILED;
2222                 }
2223                 LOG_ERROR("unable to open ftdi device: %s",
2224                                 ftd2xx_status_string(status));
2225                 status = FT_ListDevices(&num_devices, NULL, FT_LIST_NUMBER_ONLY);
2226                 if (status == FT_OK)
2227                 {
2228                         char** desc_array = malloc(sizeof(char*) * (num_devices + 1));
2229                         uint32_t i;
2230
2231                         for (i = 0; i < num_devices; i++)
2232                                 desc_array[i] = malloc(64);
2233
2234                         desc_array[num_devices] = NULL;
2235
2236                         status = FT_ListDevices(desc_array, &num_devices, FT_LIST_ALL | openex_flags);
2237
2238                         if (status == FT_OK)
2239                         {
2240                                 LOG_ERROR("ListDevices: %" PRIu32, (uint32_t)num_devices);
2241                                 for (i = 0; i < num_devices; i++)
2242                                         LOG_ERROR("%" PRIu32 ": \"%s\"", i, desc_array[i]);
2243                         }
2244
2245                         for (i = 0; i < num_devices; i++)
2246                                 free(desc_array[i]);
2247
2248                         free(desc_array);
2249                 }
2250                 else
2251                 {
2252                         LOG_ERROR("ListDevices: NONE");
2253                 }
2254                 return ERROR_JTAG_INIT_FAILED;
2255         }
2256
2257         if ((status = FT_SetLatencyTimer(ftdih, ft2232_latency)) != FT_OK)
2258         {
2259                 LOG_ERROR("unable to set latency timer: %s",
2260                                 ftd2xx_status_string(status));
2261                 return ERROR_JTAG_INIT_FAILED;
2262         }
2263
2264         if ((status = FT_GetLatencyTimer(ftdih, &latency_timer)) != FT_OK)
2265         {
2266                 /* ftd2xx 1.04 (linux) has a bug when calling FT_GetLatencyTimer
2267                  * so ignore errors if using this driver version */
2268                 DWORD dw_version;
2269
2270                 status = FT_GetDriverVersion(ftdih, &dw_version);
2271                 LOG_ERROR("unable to get latency timer: %s",
2272                                 ftd2xx_status_string(status));
2273
2274                 if ((status == FT_OK) && (dw_version == 0x10004)) {
2275                         LOG_ERROR("ftd2xx 1.04 detected - this has known issues " \
2276                                         "with FT_GetLatencyTimer, upgrade to a newer version");
2277                 }
2278                 else {
2279                         return ERROR_JTAG_INIT_FAILED;
2280                 }
2281         }
2282         else
2283         {
2284                 LOG_DEBUG("current latency timer: %i", latency_timer);
2285         }
2286
2287         if ((status = FT_SetTimeouts(ftdih, 5000, 5000)) != FT_OK)
2288         {
2289                 LOG_ERROR("unable to set timeouts: %s",
2290                                 ftd2xx_status_string(status));
2291                 return ERROR_JTAG_INIT_FAILED;
2292         }
2293
2294         if ((status = FT_SetBitMode(ftdih, 0x0b, 2)) != FT_OK)
2295         {
2296                 LOG_ERROR("unable to enable bit i/o mode: %s",
2297                                 ftd2xx_status_string(status));
2298                 return ERROR_JTAG_INIT_FAILED;
2299         }
2300
2301         if ((status = FT_GetDeviceInfo(ftdih, &ftdi_device, &deviceID, SerialNumber, Description, NULL)) != FT_OK)
2302         {
2303                 LOG_ERROR("unable to get FT_GetDeviceInfo: %s",
2304                                 ftd2xx_status_string(status));
2305                 return ERROR_JTAG_INIT_FAILED;
2306         }
2307         else
2308         {
2309                 static const char* type_str[] =
2310                         {"BM", "AM", "100AX", "UNKNOWN", "2232C", "232R", "2232H", "4232H"};
2311                 unsigned no_of_known_types = ARRAY_SIZE(type_str) - 1;
2312                 unsigned type_index = ((unsigned)ftdi_device <= no_of_known_types)
2313                         ? ftdi_device : FT_DEVICE_UNKNOWN;
2314                 LOG_INFO("device: %" PRIu32 " \"%s\"", (uint32_t)ftdi_device, type_str[type_index]);
2315                 LOG_INFO("deviceID: %" PRIu32, (uint32_t)deviceID);
2316                 LOG_INFO("SerialNumber: %s", SerialNumber);
2317                 LOG_INFO("Description: %s", Description);
2318         }
2319
2320         return ERROR_OK;
2321 }
2322
2323 static int ft2232_purge_ftd2xx(void)
2324 {
2325         FT_STATUS status;
2326
2327         if ((status = FT_Purge(ftdih, FT_PURGE_RX | FT_PURGE_TX)) != FT_OK)
2328         {
2329                 LOG_ERROR("error purging ftd2xx device: %s",
2330                                 ftd2xx_status_string(status));
2331                 return ERROR_JTAG_INIT_FAILED;
2332         }
2333
2334         return ERROR_OK;
2335 }
2336
2337 #endif /* BUILD_FT2232_FTD2XX == 1 */
2338
2339 #if BUILD_FT2232_LIBFTDI == 1
2340 static int ft2232_init_libftdi(uint16_t vid, uint16_t pid, int more, int* try_more, int channel)
2341 {
2342         uint8_t latency_timer;
2343
2344         if (layout == NULL) {
2345                 LOG_WARNING("No ft2232 layout specified'");
2346                 return ERROR_JTAG_INIT_FAILED;
2347         }
2348
2349         LOG_DEBUG("'ft2232' interface using libftdi with '%s' layout (%4.4x:%4.4x)",
2350                         layout->name, vid, pid);
2351
2352         if (ftdi_init(&ftdic) < 0)
2353                 return ERROR_JTAG_INIT_FAILED;
2354
2355         /* default to INTERFACE_A */
2356         if(channel == INTERFACE_ANY) { channel = INTERFACE_A; }
2357
2358         if (ftdi_set_interface(&ftdic, channel) < 0)
2359         {
2360                 LOG_ERROR("unable to select FT2232 channel A: %s", ftdic.error_str);
2361                 return ERROR_JTAG_INIT_FAILED;
2362         }
2363
2364         /* context, vendor id, product id */
2365         if (ftdi_usb_open_desc(&ftdic, vid, pid, ft2232_device_desc,
2366                                 ft2232_serial) < 0)
2367         {
2368                 if (more)
2369                         LOG_WARNING("unable to open ftdi device (trying more): %s",
2370                                         ftdic.error_str);
2371                 else
2372                         LOG_ERROR("unable to open ftdi device: %s", ftdic.error_str);
2373                 *try_more = 1;
2374                 return ERROR_JTAG_INIT_FAILED;
2375         }
2376
2377         /* There is already a reset in ftdi_usb_open_desc, this should be redundant */
2378         if (ftdi_usb_reset(&ftdic) < 0)
2379         {
2380                 LOG_ERROR("unable to reset ftdi device");
2381                 return ERROR_JTAG_INIT_FAILED;
2382         }
2383
2384         if (ftdi_set_latency_timer(&ftdic, ft2232_latency) < 0)
2385         {
2386                 LOG_ERROR("unable to set latency timer");
2387                 return ERROR_JTAG_INIT_FAILED;
2388         }
2389
2390         if (ftdi_get_latency_timer(&ftdic, &latency_timer) < 0)
2391         {
2392                 LOG_ERROR("unable to get latency timer");
2393                 return ERROR_JTAG_INIT_FAILED;
2394         }
2395         else
2396         {
2397                 LOG_DEBUG("current latency timer: %i", latency_timer);
2398         }
2399
2400         ftdi_set_bitmode(&ftdic, 0x0b, 2); /* ctx, JTAG I/O mask */
2401
2402         ftdi_device = ftdic.type;
2403         static const char* type_str[] =
2404                 {"AM", "BM", "2232C", "R", "2232H", "4232H", "Unknown"};
2405         unsigned no_of_known_types = ARRAY_SIZE(type_str) - 1;
2406         unsigned type_index = ((unsigned)ftdi_device < no_of_known_types)
2407                 ? ftdi_device : no_of_known_types;
2408         LOG_DEBUG("FTDI chip type: %i \"%s\"", (int)ftdi_device, type_str[type_index]);
2409         return ERROR_OK;
2410 }
2411
2412 static int ft2232_purge_libftdi(void)
2413 {
2414         if (ftdi_usb_purge_buffers(&ftdic) < 0)
2415         {
2416                 LOG_ERROR("ftdi_purge_buffers: %s", ftdic.error_str);
2417                 return ERROR_JTAG_INIT_FAILED;
2418         }
2419
2420         return ERROR_OK;
2421 }
2422
2423 #endif /* BUILD_FT2232_LIBFTDI == 1 */
2424
2425 static int ft2232_set_data_bits_low_byte( uint8_t value, uint8_t direction )
2426 {
2427         uint8_t  buf[3];
2428         uint32_t bytes_written;
2429
2430         buf[0] = 0x80;          /* command "set data bits low byte" */
2431         buf[1] = value;         /* value */
2432         buf[2] = direction;     /* direction */
2433
2434         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2435
2436         if (ft2232_write(buf, sizeof(buf), &bytes_written) != ERROR_OK)
2437         {
2438                 LOG_ERROR("couldn't initialize data bits low byte");
2439                 return ERROR_JTAG_INIT_FAILED;
2440         }
2441
2442         return ERROR_OK;
2443 }
2444
2445 static int ft2232_set_data_bits_high_byte( uint8_t value, uint8_t direction )
2446 {
2447         uint8_t  buf[3];
2448         uint32_t bytes_written;
2449
2450         buf[0] = 0x82;          /* command "set data bits high byte" */
2451         buf[1] = value;         /* value */
2452         buf[2] = direction;     /* direction */
2453
2454         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2455
2456         if (ft2232_write(buf, sizeof(buf), &bytes_written) != ERROR_OK)
2457         {
2458                 LOG_ERROR("couldn't initialize data bits high byte");
2459                 return ERROR_JTAG_INIT_FAILED;
2460         }
2461
2462         return ERROR_OK;
2463 }
2464
2465 static int ft2232_init(void)
2466 {
2467         uint8_t  buf[1];
2468         int retval;
2469         uint32_t bytes_written;
2470
2471         if (tap_get_tms_path_len(TAP_IRPAUSE,TAP_IRPAUSE) == 7)
2472         {
2473                 LOG_DEBUG("ft2232 interface using 7 step jtag state transitions");
2474         }
2475         else
2476         {
2477                 LOG_DEBUG("ft2232 interface using shortest path jtag state transitions");
2478
2479         }
2480         if (layout == NULL) {
2481                 LOG_WARNING("No ft2232 layout specified'");
2482                 return ERROR_JTAG_INIT_FAILED;
2483         }
2484
2485         for (int i = 0; 1; i++)
2486         {
2487                 /*
2488                  * "more indicates that there are more IDs to try, so we should
2489                  * not print an error for an ID mismatch (but for anything
2490                  * else, we should).
2491                  *
2492                  * try_more indicates that the error code returned indicates an
2493                  * ID mismatch (and nothing else) and that we should proceeed
2494                  * with the next ID pair.
2495                  */
2496                 int more     = ft2232_vid[i + 1] || ft2232_pid[i + 1];
2497                 int try_more = 0;
2498
2499 #if BUILD_FT2232_FTD2XX == 1
2500                 retval = ft2232_init_ftd2xx(ft2232_vid[i], ft2232_pid[i],
2501                                 more, &try_more);
2502 #elif BUILD_FT2232_LIBFTDI == 1
2503                 retval = ft2232_init_libftdi(ft2232_vid[i], ft2232_pid[i],
2504                                              more, &try_more, layout->channel);
2505 #endif
2506                 if (retval >= 0)
2507                         break;
2508                 if (!more || !try_more)
2509                         return retval;
2510         }
2511
2512         ft2232_buffer_size = 0;
2513         ft2232_buffer = malloc(FT2232_BUFFER_SIZE);
2514
2515         if (layout->init() != ERROR_OK)
2516                 return ERROR_JTAG_INIT_FAILED;
2517
2518         if (ft2232_device_is_highspeed())
2519         {
2520 #ifndef BUILD_FT2232_HIGHSPEED
2521  #if BUILD_FT2232_FTD2XX == 1
2522                 LOG_WARNING("High Speed device found - You need a newer FTD2XX driver (version 2.04.16 or later)");
2523  #elif BUILD_FT2232_LIBFTDI == 1
2524                 LOG_WARNING("High Speed device found - You need a newer libftdi version (0.16 or later)");
2525  #endif
2526 #endif
2527                 /* make sure the legacy mode is disabled */
2528                 if (ft2232h_ft4232h_clk_divide_by_5(false) != ERROR_OK)
2529                         return ERROR_JTAG_INIT_FAILED;
2530         }
2531
2532         buf[0] = 0x85; /* Disconnect TDI/DO to TDO/DI for Loopback */
2533         if ((retval = ft2232_write(buf, 1, &bytes_written)) != ERROR_OK)
2534         {
2535                 LOG_ERROR("couldn't write to FT2232 to disable loopback");
2536                 return ERROR_JTAG_INIT_FAILED;
2537         }
2538
2539 #if BUILD_FT2232_FTD2XX == 1
2540         return ft2232_purge_ftd2xx();
2541 #elif BUILD_FT2232_LIBFTDI == 1
2542         return ft2232_purge_libftdi();
2543 #endif
2544
2545         return ERROR_OK;
2546 }
2547
2548 /** Updates defaults for DBUS signals:  the four JTAG signals
2549  * (TCK, TDI, TDO, TMS) and * the four GPIOL signals.
2550  */
2551 static inline void ftx232_dbus_init(void)
2552 {
2553         low_output    = 0x08;
2554         low_direction = 0x0b;
2555 }
2556
2557 /** Initializes DBUS signals:  the four JTAG signals (TCK, TDI, TDO, TMS),
2558  * the four GPIOL signals.  Initialization covers value and direction,
2559  * as customized for each layout.
2560  */
2561 static int ftx232_dbus_write(void)
2562 {
2563         enum reset_types jtag_reset_config = jtag_get_reset_config();
2564         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2565         {
2566                 low_direction &= ~nTRSTnOE; /* nTRST input */
2567                 low_output    &= ~nTRST;    /* nTRST = 0 */
2568         }
2569         else
2570         {
2571                 low_direction |= nTRSTnOE;  /* nTRST output */
2572                 low_output    |= nTRST;     /* nTRST = 1 */
2573         }
2574
2575         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2576         {
2577                 low_direction |= nSRSTnOE;  /* nSRST output */
2578                 low_output    |= nSRST;     /* nSRST = 1 */
2579         }
2580         else
2581         {
2582                 low_direction &= ~nSRSTnOE; /* nSRST input */
2583                 low_output    &= ~nSRST;    /* nSRST = 0 */
2584         }
2585
2586         /* initialize low byte for jtag */
2587         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
2588         {
2589                 LOG_ERROR("couldn't initialize FT2232 DBUS");
2590                 return ERROR_JTAG_INIT_FAILED;
2591         }
2592
2593         return ERROR_OK;
2594 }
2595
2596 static int usbjtag_init(void)
2597 {
2598         /*
2599          * NOTE:  This is now _specific_ to the "usbjtag" layout.
2600          * Don't try cram any more layouts into this.
2601          */
2602         ftx232_dbus_init();
2603
2604         nTRST    = 0x10;
2605         nTRSTnOE = 0x10;
2606         nSRST    = 0x40;
2607         nSRSTnOE = 0x40;
2608
2609         return ftx232_dbus_write();
2610 }
2611
2612 static int lm3s811_jtag_init(void)
2613 {
2614         ftx232_dbus_init();
2615
2616         /* There are multiple revisions of LM3S811 eval boards:
2617          * - Rev B (and older?) boards have no SWO trace support.
2618          * - Rev C boards add ADBUS_6 DBG_ENn and BDBUS_4 SWO_EN;
2619          *   they should use the "luminary_icdi" layout instead.
2620          */
2621         nTRST = 0x0;
2622         nTRSTnOE = 0x00;
2623         nSRST = 0x20;
2624         nSRSTnOE = 0x20;
2625         low_output    = 0x88;
2626         low_direction = 0x8b;
2627
2628         return ftx232_dbus_write();
2629 }
2630
2631 static int icdi_jtag_init(void)
2632 {
2633         ftx232_dbus_init();
2634
2635         /* Most Luminary eval boards support SWO trace output,
2636          * and should use this "luminary_icdi" layout.
2637          *
2638          * ADBUS 0..3 are used for JTAG as usual.  GPIOs are used
2639          * to switch between JTAG and SWD, or switch the ft2232 UART
2640          * on the second MPSSE channel/interface (BDBUS)
2641          * between (i) the stellaris UART (on Luminary boards)
2642          * or (ii) SWO trace data (generic).
2643          *
2644          * We come up in JTAG mode and may switch to SWD later (with
2645          * SWO/trace option if SWD is active).
2646          *
2647          * DBUS == GPIO-Lx
2648          * CBUS == GPIO-Hx
2649          */
2650
2651
2652 #define ICDI_JTAG_EN (1 << 7)           /* ADBUS 7 (a.k.a. DBGMOD) */
2653 #define ICDI_DBG_ENn (1 << 6)           /* ADBUS 6 */
2654 #define ICDI_SRST (1 << 5)              /* ADBUS 5 */
2655
2656
2657         /* GPIOs on second channel/interface (UART) ... */
2658 #define ICDI_SWO_EN (1 << 4)            /* BDBUS 4 */
2659 #define ICDI_TX_SWO (1 << 1)            /* BDBUS 1 */
2660 #define ICDI_VCP_RX (1 << 0)            /* BDBUS 0 (to stellaris UART) */
2661
2662         nTRST = 0x0;
2663         nTRSTnOE = 0x00;
2664         nSRST = ICDI_SRST;
2665         nSRSTnOE = ICDI_SRST;
2666
2667         low_direction |= ICDI_JTAG_EN | ICDI_DBG_ENn;
2668         low_output    |= ICDI_JTAG_EN;
2669         low_output    &= ~ICDI_DBG_ENn;
2670
2671         return ftx232_dbus_write();
2672 }
2673
2674 static int signalyzer_init(void)
2675 {
2676         ftx232_dbus_init();
2677
2678         nTRST    = 0x10;
2679         nTRSTnOE = 0x10;
2680         nSRST    = 0x20;
2681         nSRSTnOE = 0x20;
2682         return ftx232_dbus_write();
2683 }
2684
2685 static int axm0432_jtag_init(void)
2686 {
2687         low_output    = 0x08;
2688         low_direction = 0x2b;
2689
2690         /* initialize low byte for jtag */
2691         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
2692         {
2693                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2694                 return ERROR_JTAG_INIT_FAILED;
2695         }
2696
2697         if (strcmp(layout->name, "axm0432_jtag") == 0)
2698         {
2699                 nTRST    = 0x08;
2700                 nTRSTnOE = 0x0;     /* No output enable for TRST*/
2701                 nSRST    = 0x04;
2702                 nSRSTnOE = 0x0;     /* No output enable for SRST*/
2703         }
2704         else
2705         {
2706                 LOG_ERROR("BUG: axm0432_jtag_init called for non axm0432 layout");
2707                 exit(-1);
2708         }
2709
2710         high_output    = 0x0;
2711         high_direction = 0x0c;
2712
2713         enum reset_types jtag_reset_config = jtag_get_reset_config();
2714         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2715         {
2716                 LOG_ERROR("can't set nTRSTOE to push-pull on the Dicarlo jtag");
2717         }
2718         else
2719         {
2720                 high_output |= nTRST;
2721         }
2722
2723         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2724         {
2725                 LOG_ERROR("can't set nSRST to push-pull on the Dicarlo jtag");
2726         }
2727         else
2728         {
2729                 high_output |= nSRST;
2730         }
2731
2732         /* initialize high byte for jtag */
2733         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
2734         {
2735                 LOG_ERROR("couldn't initialize FT2232 with 'Dicarlo' layout");
2736                 return ERROR_JTAG_INIT_FAILED;
2737         }
2738
2739         return ERROR_OK;
2740 }
2741
2742 static int redbee_init(void)
2743 {
2744         low_output    = 0x08;
2745         low_direction = 0x2b;
2746
2747         /* initialize low byte for jtag */
2748         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
2749         {
2750                 LOG_ERROR("couldn't initialize FT2232 with 'redbee' layout");
2751                 return ERROR_JTAG_INIT_FAILED;
2752         }
2753
2754         nTRST    = 0x08;
2755         nTRSTnOE = 0x0;     /* No output enable for TRST*/
2756         nSRST    = 0x04;
2757         nSRSTnOE = 0x0;     /* No output enable for SRST*/
2758
2759         high_output    = 0x0;
2760         high_direction = 0x0c;
2761
2762         enum reset_types jtag_reset_config = jtag_get_reset_config();
2763         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2764         {
2765                 LOG_ERROR("can't set nTRSTOE to push-pull on redbee");
2766         }
2767         else
2768         {
2769                 high_output |= nTRST;
2770         }
2771
2772         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2773         {
2774                 LOG_ERROR("can't set nSRST to push-pull on redbee");
2775         }
2776         else
2777         {
2778                 high_output |= nSRST;
2779         }
2780
2781         /* initialize high byte for jtag */
2782         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
2783         {
2784                 LOG_ERROR("couldn't initialize FT2232 with 'redbee' layout");
2785                 return ERROR_JTAG_INIT_FAILED;
2786         }
2787
2788         return ERROR_OK;
2789 }
2790
2791 static int jtagkey_init(void)
2792 {
2793         low_output    = 0x08;
2794         low_direction = 0x1b;
2795
2796         /* initialize low byte for jtag */
2797         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
2798         {
2799                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2800                 return ERROR_JTAG_INIT_FAILED;
2801         }
2802
2803         if (strcmp(layout->name, "jtagkey") == 0)
2804         {
2805                 nTRST    = 0x01;
2806                 nTRSTnOE = 0x4;
2807                 nSRST    = 0x02;
2808                 nSRSTnOE = 0x08;
2809         }
2810         else if ((strcmp(layout->name, "jtagkey_prototype_v1") == 0)
2811                          || (strcmp(layout->name, "oocdlink") == 0))
2812         {
2813                 nTRST    = 0x02;
2814                 nTRSTnOE = 0x1;
2815                 nSRST    = 0x08;
2816                 nSRSTnOE = 0x04;
2817         }
2818         else
2819         {
2820                 LOG_ERROR("BUG: jtagkey_init called for non jtagkey layout");
2821                 exit(-1);
2822         }
2823
2824         high_output    = 0x0;
2825         high_direction = 0x0f;
2826
2827         enum reset_types jtag_reset_config = jtag_get_reset_config();
2828         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2829         {
2830                 high_output |= nTRSTnOE;
2831                 high_output &= ~nTRST;
2832         }
2833         else
2834         {
2835                 high_output &= ~nTRSTnOE;
2836                 high_output |= nTRST;
2837         }
2838
2839         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2840         {
2841                 high_output &= ~nSRSTnOE;
2842                 high_output |= nSRST;
2843         }
2844         else
2845         {
2846                 high_output |= nSRSTnOE;
2847                 high_output &= ~nSRST;
2848         }
2849
2850         /* initialize high byte for jtag */
2851         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
2852         {
2853                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2854                 return ERROR_JTAG_INIT_FAILED;
2855         }
2856
2857         return ERROR_OK;
2858 }
2859
2860 static int olimex_jtag_init(void)
2861 {
2862         low_output    = 0x08;
2863         low_direction = 0x1b;
2864
2865         /* initialize low byte for jtag */
2866         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
2867         {
2868                 LOG_ERROR("couldn't initialize FT2232 with 'Olimex' layout");
2869                 return ERROR_JTAG_INIT_FAILED;
2870         }
2871
2872         nTRST    = 0x01;
2873         nTRSTnOE = 0x4;
2874         nSRST    = 0x02;
2875         nSRSTnOE = 0x00; /* no output enable for nSRST */
2876
2877         high_output    = 0x0;
2878         high_direction = 0x0f;
2879
2880         enum reset_types jtag_reset_config = jtag_get_reset_config();
2881         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2882         {
2883                 high_output |= nTRSTnOE;
2884                 high_output &= ~nTRST;
2885         }
2886         else
2887         {
2888                 high_output &= ~nTRSTnOE;
2889                 high_output |= nTRST;
2890         }
2891
2892         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2893         {
2894                 LOG_ERROR("can't set nSRST to push-pull on the Olimex ARM-USB-OCD");
2895         }
2896         else
2897         {
2898                 high_output &= ~nSRST;
2899         }
2900
2901         /* turn red LED on */
2902         high_output |= 0x08;
2903
2904         /* initialize high byte for jtag */
2905         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
2906         {
2907                 LOG_ERROR("couldn't initialize FT2232 with 'Olimex' layout");
2908                 return ERROR_JTAG_INIT_FAILED;
2909         }
2910
2911         return ERROR_OK;
2912 }
2913
2914 static int flyswatter_init(void)
2915 {
2916         low_output    = 0x18;
2917         low_direction = 0xfb;
2918
2919         /* initialize low byte for jtag */
2920         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
2921         {
2922                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2923                 return ERROR_JTAG_INIT_FAILED;
2924         }
2925
2926         nTRST    = 0x10;
2927         nTRSTnOE = 0x0;     /* not output enable for nTRST */
2928         nSRST    = 0x20;
2929         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2930
2931         high_output    = 0x00;
2932         high_direction = 0x0c;
2933
2934         /* turn red LED3 on, LED2 off */
2935         high_output |= 0x08;
2936
2937         /* initialize high byte for jtag */
2938         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
2939         {
2940                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2941                 return ERROR_JTAG_INIT_FAILED;
2942         }
2943
2944         return ERROR_OK;
2945 }
2946
2947 static int minimodule_init(void)
2948 {
2949         low_output    = 0x18;//check if srst should be 1 or 0 initially. (0x08) (flyswatter was 0x18)
2950         low_direction = 0xfb;//0xfb;
2951
2952         /* initialize low byte for jtag */
2953         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
2954         {
2955                 LOG_ERROR("couldn't initialize FT2232 with 'minimodule' layout");
2956                 return ERROR_JTAG_INIT_FAILED;
2957         }
2958
2959
2960         nSRST    = 0x20;
2961
2962         high_output    = 0x00;
2963         high_direction = 0x05;
2964
2965         /* turn red LED3 on, LED2 off */
2966         //high_output |= 0x08;
2967
2968         /* initialize high byte for jtag */
2969         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
2970         {
2971                 LOG_ERROR("couldn't initialize FT2232 with 'minimodule' layout");
2972                 return ERROR_JTAG_INIT_FAILED;
2973         }
2974
2975         return ERROR_OK;
2976 }
2977
2978 static int turtle_init(void)
2979 {
2980         low_output    = 0x08;
2981         low_direction = 0x5b;
2982
2983         /* initialize low byte for jtag */
2984         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
2985         {
2986                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2987                 return ERROR_JTAG_INIT_FAILED;
2988         }
2989
2990         nSRST = 0x40;
2991
2992         high_output    = 0x00;
2993         high_direction = 0x0C;
2994
2995         /* initialize high byte for jtag */
2996         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
2997         {
2998                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2999                 return ERROR_JTAG_INIT_FAILED;
3000         }
3001
3002         return ERROR_OK;
3003 }
3004
3005 static int comstick_init(void)
3006 {
3007         low_output    = 0x08;
3008         low_direction = 0x0b;
3009
3010         /* initialize low byte for jtag */
3011         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
3012         {
3013                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
3014                 return ERROR_JTAG_INIT_FAILED;
3015         }
3016
3017         nTRST    = 0x01;
3018         nTRSTnOE = 0x00;    /* no output enable for nTRST */
3019         nSRST    = 0x02;
3020         nSRSTnOE = 0x00;    /* no output enable for nSRST */
3021
3022         high_output    = 0x03;
3023         high_direction = 0x03;
3024
3025         /* initialize high byte for jtag */
3026         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
3027         {
3028                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
3029                 return ERROR_JTAG_INIT_FAILED;
3030         }
3031
3032         return ERROR_OK;
3033 }
3034
3035 static int stm32stick_init(void)
3036 {
3037         low_output    = 0x88;
3038         low_direction = 0x8b;
3039
3040         /* initialize low byte for jtag */
3041         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
3042         {
3043                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
3044                 return ERROR_JTAG_INIT_FAILED;
3045         }
3046
3047         nTRST    = 0x01;
3048         nTRSTnOE = 0x00;    /* no output enable for nTRST */
3049         nSRST    = 0x80;
3050         nSRSTnOE = 0x00;    /* no output enable for nSRST */
3051
3052         high_output    = 0x01;
3053         high_direction = 0x03;
3054
3055         /* initialize high byte for jtag */
3056         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
3057         {
3058                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
3059                 return ERROR_JTAG_INIT_FAILED;
3060         }
3061
3062         return ERROR_OK;
3063 }
3064
3065 static int sheevaplug_init(void)
3066 {
3067         low_output = 0x08;
3068         low_direction = 0x1b;
3069
3070         /* initialize low byte for jtag */
3071         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
3072         {
3073                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
3074                 return ERROR_JTAG_INIT_FAILED;
3075         }
3076
3077         nTRSTnOE = 0x1;
3078         nTRST = 0x02;
3079         nSRSTnOE = 0x4;
3080         nSRST = 0x08;
3081
3082         high_output = 0x0;
3083         high_direction = 0x0f;
3084
3085         /* nTRST is always push-pull */
3086         high_output &= ~nTRSTnOE;
3087         high_output |= nTRST;
3088
3089         /* nSRST is always open-drain */
3090         high_output |= nSRSTnOE;
3091         high_output &= ~nSRST;
3092
3093         /* initialize high byte for jtag */
3094         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
3095         {
3096                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
3097                 return ERROR_JTAG_INIT_FAILED;
3098         }
3099
3100         return ERROR_OK;
3101 }
3102
3103 static int cortino_jtag_init(void)
3104 {
3105         low_output    = 0x08;
3106         low_direction = 0x1b;
3107
3108         /* initialize low byte for jtag */
3109         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
3110         {
3111                 LOG_ERROR("couldn't initialize FT2232 with 'cortino' layout");
3112                 return ERROR_JTAG_INIT_FAILED;
3113         }
3114
3115         nTRST    = 0x01;
3116         nTRSTnOE = 0x00;    /* no output enable for nTRST */
3117         nSRST    = 0x02;
3118         nSRSTnOE = 0x00;    /* no output enable for nSRST */
3119
3120         high_output    = 0x03;
3121         high_direction = 0x03;
3122
3123         /* initialize high byte for jtag */
3124         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
3125         {
3126                 LOG_ERROR("couldn't initialize FT2232 with 'cortino' layout");
3127                 return ERROR_JTAG_INIT_FAILED;
3128         }
3129
3130         return ERROR_OK;
3131 }
3132
3133 static int lisa_l_init(void)
3134 {
3135         ftx232_dbus_init();
3136
3137         nTRST    = 0x10;
3138         nTRSTnOE = 0x10;
3139         nSRST    = 0x40;
3140         nSRSTnOE = 0x40;
3141
3142         high_output = 0x00;
3143         high_direction = 0x18;
3144
3145         /* initialize high byte for jtag */
3146         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
3147         {
3148                 LOG_ERROR("couldn't initialize FT2232 with 'lisa_l' layout");
3149                 return ERROR_JTAG_INIT_FAILED;
3150         }
3151
3152         return ftx232_dbus_write();
3153 }
3154
3155 static int flossjtag_init(void)
3156 {
3157         ftx232_dbus_init();
3158
3159         nTRST    = 0x10;
3160         nTRSTnOE = 0x10;
3161         nSRST    = 0x40;
3162         nSRSTnOE = 0x40;
3163
3164         high_output = 0x00;
3165         high_direction = 0x18;
3166
3167         /* initialize high byte for jtag */
3168         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
3169         {
3170                 LOG_ERROR("couldn't initialize FT2232 with 'Floss-JTAG' layout");
3171                 return ERROR_JTAG_INIT_FAILED;
3172         }
3173
3174         return ftx232_dbus_write();
3175 }
3176
3177 /*
3178  * The reference schematic from TI for the XDS100v2 has a CPLD on which opens
3179  * the door for a number of different configurations
3180  *
3181  * Known Implementations:
3182  * http://processors.wiki.ti.com/images/9/93/TMS570LS20216_USB_STICK_Schematic.pdf
3183  *
3184  * http://processors.wiki.ti.com/index.php/XDS100 (rev2)
3185  *      * CLPD logic: Rising edge to enable outputs (XDS100_PWR_RST)
3186  *              * ACBUS3 to transition 0->1 (OE rising edge)
3187  *      * CPLD logic: Put the EMU0/1 pins in Hi-Z:
3188  *              * ADBUS5/GPIOL1 = EMU_EN = 1
3189  *              * ADBUS6/GPIOL2 = EMU0 = 0
3190  *              * ACBUS4/SPARE0 = EMU1 = 0
3191  *      * CPLD logic: Disable loopback
3192  *              * ACBUS6/SPARE2 = LOOPBACK = 0
3193  */
3194 #define XDS100_nEMU_EN  (1<<5)
3195 #define XDS100_nEMU0    (1<<6)
3196
3197 #define XDS100_PWR_RST  (1<<3)
3198 #define XDS100_nEMU1    (1<<4)
3199 #define XDS100_LOOPBACK (1<<6)
3200 static int xds100v2_init(void)
3201 {
3202         /* These are in the lower byte */
3203         nTRST    = 0x10;
3204         nTRSTnOE = 0x10;
3205
3206         /* These aren't actually used on 14 pin connectors */
3207         /* These are in the upper byte */
3208         nSRST    = 0x01;
3209         nSRSTnOE = 0x01;
3210
3211         low_output    = 0x08 | nTRST | XDS100_nEMU_EN;
3212         low_direction = 0x0b | nTRSTnOE | XDS100_nEMU_EN | XDS100_nEMU0;
3213
3214         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
3215         {
3216                 LOG_ERROR("couldn't initialize FT2232 with 'xds100v2' layout");
3217                 return ERROR_JTAG_INIT_FAILED;
3218         }
3219
3220         high_output = 0;
3221         high_direction = nSRSTnOE | XDS100_LOOPBACK | XDS100_PWR_RST | XDS100_nEMU1;
3222
3223         /* initialize high byte for jtag */
3224         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
3225         {
3226                 LOG_ERROR("couldn't put CPLD in to reset with 'xds100v2' layout");
3227                 return ERROR_JTAG_INIT_FAILED;
3228         }
3229
3230         high_output |= XDS100_PWR_RST;
3231
3232         /* initialize high byte for jtag */
3233         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
3234         {
3235                 LOG_ERROR("couldn't bring CPLD out of reset with 'xds100v2' layout");
3236                 return ERROR_JTAG_INIT_FAILED;
3237         }
3238
3239         return ERROR_OK;
3240 }
3241
3242 static void olimex_jtag_blink(void)
3243 {
3244         /* Olimex ARM-USB-OCD has a LED connected to ACBUS3
3245          * ACBUS3 is bit 3 of the GPIOH port
3246          */
3247         high_output ^= 0x08;
3248
3249         buffer_write(0x82);
3250         buffer_write(high_output);
3251         buffer_write(high_direction);
3252 }
3253
3254 static void flyswatter_jtag_blink(void)
3255 {
3256         /*
3257          * Flyswatter has two LEDs connected to ACBUS2 and ACBUS3
3258          */
3259         high_output ^= 0x0c;
3260
3261         buffer_write(0x82);
3262         buffer_write(high_output);
3263         buffer_write(high_direction);
3264 }
3265
3266 static void turtle_jtag_blink(void)
3267 {
3268         /*
3269          * Turtelizer2 has two LEDs connected to ACBUS2 and ACBUS3
3270          */
3271         if (high_output & 0x08)
3272         {
3273                 high_output = 0x04;
3274         }
3275         else
3276         {
3277                 high_output = 0x08;
3278         }
3279
3280         buffer_write(0x82);
3281         buffer_write(high_output);
3282         buffer_write(high_direction);
3283 }
3284
3285 static void lisa_l_blink(void)
3286 {
3287         /*
3288          * Lisa/L has two LEDs connected to BCBUS3 and BCBUS4
3289          */
3290         if (high_output & 0x10)
3291         {
3292                 high_output = 0x08;
3293         }
3294         else
3295         {
3296                 high_output = 0x10;
3297         }
3298
3299         buffer_write(0x82);
3300         buffer_write(high_output);
3301         buffer_write(high_direction);
3302 }
3303
3304 static void flossjtag_blink(void)
3305 {
3306         /*
3307          * Floss-JTAG has two LEDs connected to ACBUS3 and ACBUS4
3308          */
3309         if (high_output & 0x10)
3310         {
3311                 high_output = 0x08;
3312         }
3313         else
3314         {
3315                 high_output = 0x10;
3316         }
3317
3318         buffer_write(0x82);
3319         buffer_write(high_output);
3320         buffer_write(high_direction);
3321 }
3322
3323 static int ft2232_quit(void)
3324 {
3325 #if BUILD_FT2232_FTD2XX == 1
3326         FT_STATUS status;
3327
3328         status = FT_Close(ftdih);
3329 #elif BUILD_FT2232_LIBFTDI == 1
3330         ftdi_usb_close(&ftdic);
3331
3332         ftdi_deinit(&ftdic);
3333 #endif
3334
3335         free(ft2232_buffer);
3336         ft2232_buffer = NULL;
3337
3338         return ERROR_OK;
3339 }
3340
3341 COMMAND_HANDLER(ft2232_handle_device_desc_command)
3342 {
3343         char *cp;
3344         char buf[200];
3345         if (CMD_ARGC == 1)
3346         {
3347                 ft2232_device_desc = strdup(CMD_ARGV[0]);
3348                 cp = strchr(ft2232_device_desc, 0);
3349                 /* under Win32, the FTD2XX driver appends an "A" to the end
3350                  * of the description, this examines the given desc
3351                  * and creates the 'missing' _A or non_A variable. */
3352                 if ((cp[-1] == 'A') && (cp[-2]==' ')) {
3353                         /* it was, so make this the "A" version. */
3354                         ft2232_device_desc_A = ft2232_device_desc;
3355                         /* and *CREATE* the non-A version. */
3356                         strcpy(buf, ft2232_device_desc);
3357                         cp = strchr(buf, 0);
3358                         cp[-2] = 0;
3359                         ft2232_device_desc =  strdup(buf);
3360                 } else {
3361                         /* <space > A not defined
3362                          * so create it */
3363                         sprintf(buf, "%s A", ft2232_device_desc);
3364                         ft2232_device_desc_A = strdup(buf);
3365                 }
3366         }
3367         else
3368         {
3369                 LOG_ERROR("expected exactly one argument to ft2232_device_desc <description>");
3370         }
3371
3372         return ERROR_OK;
3373 }
3374
3375 COMMAND_HANDLER(ft2232_handle_serial_command)
3376 {
3377         if (CMD_ARGC == 1)
3378         {
3379                 ft2232_serial = strdup(CMD_ARGV[0]);
3380         }
3381         else
3382         {
3383                 LOG_ERROR("expected exactly one argument to ft2232_serial <serial-number>");
3384         }
3385
3386         return ERROR_OK;
3387 }
3388
3389 COMMAND_HANDLER(ft2232_handle_layout_command)
3390 {
3391         if (CMD_ARGC != 1) {
3392                 LOG_ERROR("Need exactly one argument to ft2232_layout");
3393                 return ERROR_FAIL;
3394         }
3395
3396         if (layout) {
3397                 LOG_ERROR("already specified ft2232_layout %s",
3398                                 layout->name);
3399                 return (strcmp(layout->name, CMD_ARGV[0]) != 0)
3400                                 ? ERROR_FAIL
3401                                 : ERROR_OK;
3402         }
3403
3404         for (const struct ft2232_layout *l = ft2232_layouts; l->name; l++) {
3405                 if (strcmp(l->name, CMD_ARGV[0]) == 0) {
3406                         layout = l;
3407                         return ERROR_OK;
3408                 }
3409         }
3410
3411         LOG_ERROR("No FT2232 layout '%s' found", CMD_ARGV[0]);
3412         return ERROR_FAIL;
3413 }
3414
3415 COMMAND_HANDLER(ft2232_handle_vid_pid_command)
3416 {
3417         if (CMD_ARGC > MAX_USB_IDS * 2)
3418         {
3419                 LOG_WARNING("ignoring extra IDs in ft2232_vid_pid "
3420                                         "(maximum is %d pairs)", MAX_USB_IDS);
3421                 CMD_ARGC = MAX_USB_IDS * 2;
3422         }
3423         if (CMD_ARGC < 2 || (CMD_ARGC & 1))
3424         {
3425                 LOG_WARNING("incomplete ft2232_vid_pid configuration directive");
3426                 if (CMD_ARGC < 2)
3427                         return ERROR_COMMAND_SYNTAX_ERROR;
3428                 /* remove the incomplete trailing id */
3429                 CMD_ARGC -= 1;
3430         }
3431
3432         unsigned i;
3433         for (i = 0; i < CMD_ARGC; i += 2)
3434         {
3435                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], ft2232_vid[i >> 1]);
3436                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], ft2232_pid[i >> 1]);
3437         }
3438
3439         /*
3440          * Explicitly terminate, in case there are multiples instances of
3441          * ft2232_vid_pid.
3442          */
3443         ft2232_vid[i >> 1] = ft2232_pid[i >> 1] = 0;
3444
3445         return ERROR_OK;
3446 }
3447
3448 COMMAND_HANDLER(ft2232_handle_latency_command)
3449 {
3450         if (CMD_ARGC == 1)
3451         {
3452                 ft2232_latency = atoi(CMD_ARGV[0]);
3453         }
3454         else
3455         {
3456                 LOG_ERROR("expected exactly one argument to ft2232_latency <ms>");
3457         }
3458
3459         return ERROR_OK;
3460 }
3461
3462 static int ft2232_stableclocks(int num_cycles, struct jtag_command* cmd)
3463 {
3464         int retval = 0;
3465
3466         /* 7 bits of either ones or zeros. */
3467         uint8_t  tms = (tap_get_state() == TAP_RESET ? 0x7F : 0x00);
3468
3469         while (num_cycles > 0)
3470         {
3471                 /* the command 0x4b, "Clock Data to TMS/CS Pin (no Read)" handles
3472                  * at most 7 bits per invocation.  Here we invoke it potentially
3473                  * several times.
3474                  */
3475                 int bitcount_per_command = (num_cycles > 7) ? 7 : num_cycles;
3476
3477                 if (ft2232_buffer_size + 3 >= FT2232_BUFFER_SIZE)
3478                 {
3479                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
3480                                 retval = ERROR_JTAG_QUEUE_FAILED;
3481
3482                         first_unsent = cmd;
3483                 }
3484
3485                 /* there are no state transitions in this code, so omit state tracking */
3486
3487                 /* command "Clock Data to TMS/CS Pin (no Read)" */
3488                 buffer_write(0x4b);
3489
3490                 /* scan 7 bit */
3491                 buffer_write(bitcount_per_command - 1);
3492
3493                 /* TMS data bits are either all zeros or ones to stay in the current stable state */
3494                 buffer_write(tms);
3495
3496                 require_send = 1;
3497
3498                 num_cycles -= bitcount_per_command;
3499         }
3500
3501         return retval;
3502 }
3503
3504 /* ---------------------------------------------------------------------
3505  * Support for IceBear JTAG adapter from Section5:
3506  *      http://section5.ch/icebear
3507  *
3508  * Author: Sten, debian@sansys-electronic.com
3509  */
3510
3511 /* Icebear pin layout
3512  *
3513  * ADBUS5 (nEMU) nSRST  | 2   1|        GND (10k->VCC)
3514  * GND GND              | 4   3|        n.c.
3515  * ADBUS3 TMS           | 6   5|        ADBUS6 VCC
3516  * ADBUS0 TCK           | 8   7|        ADBUS7 (GND)
3517  * ADBUS4 nTRST         |10   9|        ACBUS0 (GND)
3518  * ADBUS1 TDI           |12  11|        ACBUS1 (GND)
3519  * ADBUS2 TDO           |14  13|        GND GND
3520  *
3521  * ADBUS0 O L TCK               ACBUS0 GND
3522  * ADBUS1 O L TDI               ACBUS1 GND
3523  * ADBUS2 I   TDO               ACBUS2 n.c.
3524  * ADBUS3 O H TMS               ACBUS3 n.c.
3525  * ADBUS4 O H nTRST
3526  * ADBUS5 O H nSRST
3527  * ADBUS6 -   VCC
3528  * ADBUS7 -   GND
3529  */
3530 static int icebear_jtag_init(void) {
3531         low_direction   = 0x0b; /* output: TCK TDI TMS; input: TDO */
3532         low_output      = 0x08; /* high: TMS; low: TCK TDI */
3533         nTRST           = 0x10;
3534         nSRST           = 0x20;
3535
3536         enum reset_types jtag_reset_config = jtag_get_reset_config();
3537         if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0) {
3538                 low_direction   &= ~nTRST;      /* nTRST high impedance */
3539         }
3540         else {
3541                 low_direction   |= nTRST;
3542                 low_output      |= nTRST;
3543         }
3544
3545         low_direction   |= nSRST;
3546         low_output      |= nSRST;
3547
3548         /* initialize low byte for jtag */
3549         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK) {
3550                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (low)");
3551                 return ERROR_JTAG_INIT_FAILED;
3552         }
3553
3554         high_output    = 0x0;
3555         high_direction = 0x00;
3556
3557         /* initialize high byte for jtag */
3558         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK) {
3559                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (high)");
3560                 return ERROR_JTAG_INIT_FAILED;
3561         }
3562
3563         return ERROR_OK;
3564 }
3565
3566 static void icebear_jtag_reset(int trst, int srst) {
3567
3568         if (trst == 1) {
3569                 low_direction   |= nTRST;
3570                 low_output      &= ~nTRST;
3571         }
3572         else if (trst == 0) {
3573                 enum reset_types jtag_reset_config = jtag_get_reset_config();
3574                 if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0)
3575                         low_direction   &= ~nTRST;
3576                 else
3577                         low_output      |= nTRST;
3578         }
3579
3580         if (srst == 1) {
3581                 low_output &= ~nSRST;
3582         }
3583         else if (srst == 0) {
3584                 low_output |= nSRST;
3585         }
3586
3587         /* command "set data bits low byte" */
3588         buffer_write(0x80);
3589         buffer_write(low_output);
3590         buffer_write(low_direction);
3591
3592         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
3593 }
3594
3595 /* ---------------------------------------------------------------------
3596  * Support for Signalyzer H2 and Signalyzer H4
3597  * JTAG adapter from Xverve Technologies Inc.
3598  * http://www.signalyzer.com or http://www.xverve.com
3599  *
3600  * Author: Oleg Seiljus, oleg@signalyzer.com
3601  */
3602 static unsigned char signalyzer_h_side;
3603 static unsigned int signalyzer_h_adapter_type;
3604
3605 static int signalyzer_h_ctrl_write(int address, unsigned short value);
3606
3607 #if BUILD_FT2232_FTD2XX == 1
3608 static int signalyzer_h_ctrl_read(int address, unsigned short *value);
3609 #endif
3610
3611 #define SIGNALYZER_COMMAND_ADDR                                 128
3612 #define SIGNALYZER_DATA_BUFFER_ADDR                             129
3613
3614 #define SIGNALYZER_COMMAND_VERSION                              0x41
3615 #define SIGNALYZER_COMMAND_RESET                                0x42
3616 #define SIGNALYZER_COMMAND_POWERCONTROL_GET             0x50
3617 #define SIGNALYZER_COMMAND_POWERCONTROL_SET             0x51
3618 #define SIGNALYZER_COMMAND_PWM_SET                              0x52
3619 #define SIGNALYZER_COMMAND_LED_SET                              0x53
3620 #define SIGNALYZER_COMMAND_ADC                                  0x54
3621 #define SIGNALYZER_COMMAND_GPIO_STATE                   0x55
3622 #define SIGNALYZER_COMMAND_GPIO_MODE                    0x56
3623 #define SIGNALYZER_COMMAND_GPIO_PORT                    0x57
3624 #define SIGNALYZER_COMMAND_I2C                                  0x58
3625
3626 #define SIGNALYZER_CHAN_A                                               1
3627 #define SIGNALYZER_CHAN_B                                               2
3628 /* LEDS use channel C */
3629 #define SIGNALYZER_CHAN_C                                               4
3630
3631 #define SIGNALYZER_LED_GREEN                                    1
3632 #define SIGNALYZER_LED_RED                                              2
3633
3634 #define SIGNALYZER_MODULE_TYPE_EM_LT16_A                0x0301
3635 #define SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG              0x0302
3636 #define SIGNALYZER_MODULE_TYPE_EM_JTAG                  0x0303
3637 #define SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P    0x0304
3638 #define SIGNALYZER_MODULE_TYPE_EM_JTAG_P                0x0305
3639
3640
3641 static int signalyzer_h_ctrl_write(int address, unsigned short value)
3642 {
3643 #if BUILD_FT2232_FTD2XX == 1
3644         return FT_WriteEE(ftdih, address, value);
3645 #elif BUILD_FT2232_LIBFTDI == 1
3646         return 0;
3647 #endif
3648 }
3649
3650 #if BUILD_FT2232_FTD2XX == 1
3651 static int signalyzer_h_ctrl_read(int address, unsigned short *value)
3652 {
3653         return FT_ReadEE(ftdih, address, value);
3654 }
3655 #endif
3656
3657 static int signalyzer_h_led_set(unsigned char channel, unsigned char led,
3658         int on_time_ms, int off_time_ms, unsigned char cycles)
3659 {
3660         unsigned char on_time;
3661         unsigned char off_time;
3662
3663         if (on_time_ms < 0xFFFF)
3664                 on_time = (unsigned char)(on_time_ms / 62);
3665         else
3666                 on_time = 0xFF;
3667
3668         off_time = (unsigned char)(off_time_ms / 62);
3669
3670 #if BUILD_FT2232_FTD2XX == 1
3671         FT_STATUS status;
3672
3673         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3674                         ((uint32_t)(channel << 8) | led))) != FT_OK)
3675         {
3676                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %s",
3677                                 ftd2xx_status_string(status));
3678                 return ERROR_JTAG_DEVICE_ERROR;
3679         }
3680
3681         if ((status = signalyzer_h_ctrl_write(
3682                         (SIGNALYZER_DATA_BUFFER_ADDR + 1),
3683                         ((uint32_t)(on_time << 8) | off_time))) != FT_OK)
3684         {
3685                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %s",
3686                                 ftd2xx_status_string(status));
3687                 return ERROR_JTAG_DEVICE_ERROR;
3688         }
3689
3690         if ((status = signalyzer_h_ctrl_write(
3691                         (SIGNALYZER_DATA_BUFFER_ADDR + 2),
3692                         ((uint32_t)cycles))) != FT_OK)
3693         {
3694                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %s",
3695                                 ftd2xx_status_string(status));
3696                 return ERROR_JTAG_DEVICE_ERROR;
3697         }
3698
3699         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3700                         SIGNALYZER_COMMAND_LED_SET)) != FT_OK)
3701         {
3702                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %s",
3703                                 ftd2xx_status_string(status));
3704                 return ERROR_JTAG_DEVICE_ERROR;
3705         }
3706
3707         return ERROR_OK;
3708 #elif BUILD_FT2232_LIBFTDI == 1
3709         int retval;
3710
3711         if ((retval = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3712                         ((uint32_t)(channel << 8) | led))) < 0)
3713         {
3714                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3715                                 ftdi_get_error_string(&ftdic));
3716                 return ERROR_JTAG_DEVICE_ERROR;
3717         }
3718
3719         if ((retval = signalyzer_h_ctrl_write(
3720                         (SIGNALYZER_DATA_BUFFER_ADDR + 1),
3721                         ((uint32_t)(on_time << 8) | off_time))) < 0)
3722         {
3723                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3724                                 ftdi_get_error_string(&ftdic));
3725                 return ERROR_JTAG_DEVICE_ERROR;
3726         }
3727
3728         if ((retval = signalyzer_h_ctrl_write(
3729                         (SIGNALYZER_DATA_BUFFER_ADDR + 2),
3730                         (uint32_t)cycles)) < 0)
3731         {
3732                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3733                                 ftdi_get_error_string(&ftdic));
3734                 return ERROR_JTAG_DEVICE_ERROR;
3735         }
3736
3737         if ((retval = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3738                         SIGNALYZER_COMMAND_LED_SET)) < 0)
3739         {
3740                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3741                                 ftdi_get_error_string(&ftdic));
3742                 return ERROR_JTAG_DEVICE_ERROR;
3743         }
3744
3745         return ERROR_OK;
3746 #endif
3747 }
3748
3749 static int signalyzer_h_init(void)
3750 {
3751 #if BUILD_FT2232_FTD2XX == 1
3752         FT_STATUS status;
3753         int i;
3754 #endif
3755
3756         char *end_of_desc;
3757
3758         uint16_t read_buf[12] = { 0 };
3759
3760         /* turn on center green led */
3761         signalyzer_h_led_set(SIGNALYZER_CHAN_C, SIGNALYZER_LED_GREEN,
3762                         0xFFFF, 0x00, 0x00);
3763
3764         /* determine what channel config wants to open
3765          * TODO: change me... current implementation is made to work
3766          * with openocd description parsing.
3767          */
3768         end_of_desc = strrchr(ft2232_device_desc, 0x00);
3769
3770         if (end_of_desc)
3771         {
3772                 signalyzer_h_side = *(end_of_desc - 1);
3773                 if (signalyzer_h_side == 'B')
3774                         signalyzer_h_side = SIGNALYZER_CHAN_B;
3775                 else
3776                         signalyzer_h_side = SIGNALYZER_CHAN_A;
3777         }
3778         else
3779         {
3780                 LOG_ERROR("No Channel was specified");
3781                 return ERROR_FAIL;
3782         }
3783
3784         signalyzer_h_led_set(signalyzer_h_side, SIGNALYZER_LED_GREEN,
3785                         1000, 1000, 0xFF);
3786
3787 #if BUILD_FT2232_FTD2XX == 1
3788         /* read signalyzer versionining information */
3789         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3790                         SIGNALYZER_COMMAND_VERSION)) != FT_OK)
3791         {
3792                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3793                                 ftd2xx_status_string(status));
3794                 return ERROR_JTAG_DEVICE_ERROR;
3795         }
3796
3797         for (i = 0; i < 10; i++)
3798         {
3799                 if ((status = signalyzer_h_ctrl_read(
3800                         (SIGNALYZER_DATA_BUFFER_ADDR + i),
3801                         &read_buf[i])) != FT_OK)
3802                 {
3803                         LOG_ERROR("signalyzer_h_ctrl_read returned: %s",
3804                                         ftd2xx_status_string(status));
3805                         return ERROR_JTAG_DEVICE_ERROR;
3806                 }
3807         }
3808
3809         LOG_INFO("Signalyzer: ID info: { %.4x %.4x %.4x %.4x %.4x %.4x %.4x }",
3810                         read_buf[0], read_buf[1], read_buf[2], read_buf[3],
3811                         read_buf[4], read_buf[5], read_buf[6]);
3812
3813         /* set gpio register */
3814         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3815                         (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3816         {
3817                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3818                                 ftd2xx_status_string(status));
3819                 return ERROR_JTAG_DEVICE_ERROR;
3820         }
3821
3822         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR + 1,
3823                         0x0404)) != FT_OK)
3824         {
3825                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3826                                 ftd2xx_status_string(status));
3827                 return ERROR_JTAG_DEVICE_ERROR;
3828         }
3829
3830         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3831                         SIGNALYZER_COMMAND_GPIO_STATE)) != FT_OK)
3832         {
3833                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3834                                 ftd2xx_status_string(status));
3835                 return ERROR_JTAG_DEVICE_ERROR;
3836         }
3837
3838         /* read adapter type information */
3839         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3840                         ((uint32_t)(signalyzer_h_side << 8) | 0x01))) != FT_OK)
3841         {
3842                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3843                                 ftd2xx_status_string(status));
3844                 return ERROR_JTAG_DEVICE_ERROR;
3845         }
3846
3847         if ((status = signalyzer_h_ctrl_write(
3848                         (SIGNALYZER_DATA_BUFFER_ADDR + 1), 0xA000)) != FT_OK)
3849         {
3850                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3851                                 ftd2xx_status_string(status));
3852                 return ERROR_JTAG_DEVICE_ERROR;
3853         }
3854
3855         if ((status = signalyzer_h_ctrl_write(
3856                         (SIGNALYZER_DATA_BUFFER_ADDR + 2), 0x0008)) != FT_OK)
3857         {
3858                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3859                                 ftd2xx_status_string(status));
3860                 return ERROR_JTAG_DEVICE_ERROR;
3861         }
3862
3863         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3864                         SIGNALYZER_COMMAND_I2C)) != FT_OK)
3865         {
3866                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3867                                 ftd2xx_status_string(status));
3868                 return ERROR_JTAG_DEVICE_ERROR;
3869         }
3870
3871         usleep(100000);
3872
3873         if ((status = signalyzer_h_ctrl_read(SIGNALYZER_COMMAND_ADDR,
3874                         &read_buf[0])) != FT_OK)
3875         {
3876                 LOG_ERROR("signalyzer_h_ctrl_read returned: %s",
3877                                 ftd2xx_status_string(status));
3878                 return ERROR_JTAG_DEVICE_ERROR;
3879         }
3880
3881         if (read_buf[0] != 0x0498)
3882                 signalyzer_h_adapter_type = 0x0000;
3883         else
3884         {
3885                 for (i = 0; i < 4; i++)
3886                 {
3887                         if ((status = signalyzer_h_ctrl_read(
3888                                         (SIGNALYZER_DATA_BUFFER_ADDR + i),
3889                                         &read_buf[i])) != FT_OK)
3890                         {
3891                                 LOG_ERROR("signalyzer_h_ctrl_read returned: %s",
3892                                                 ftd2xx_status_string(status));
3893                                 return ERROR_JTAG_DEVICE_ERROR;
3894                         }
3895                 }
3896
3897                 signalyzer_h_adapter_type = read_buf[0];
3898         }
3899
3900 #elif BUILD_FT2232_LIBFTDI == 1
3901         /* currently libftdi does not allow reading individual eeprom
3902          * locations, therefore adapter type cannot be detected.
3903          * override with most common type
3904          */
3905         signalyzer_h_adapter_type = SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG;
3906 #endif
3907
3908         enum reset_types jtag_reset_config = jtag_get_reset_config();
3909
3910         /* ADAPTOR: EM_LT16_A */
3911         if (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_LT16_A)
3912         {
3913                 LOG_INFO("Signalyzer: EM-LT (16-channel level translator) "
3914                         "detected. (HW: %2x).", (read_buf[1] >> 8));
3915
3916                 nTRST    = 0x10;
3917                 nTRSTnOE = 0x10;
3918                 nSRST    = 0x20;
3919                 nSRSTnOE = 0x20;
3920
3921                 low_output     = 0x08;
3922                 low_direction  = 0x1b;
3923
3924                 high_output    = 0x0;
3925                 high_direction = 0x0;
3926
3927                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3928                 {
3929                         low_direction &= ~nTRSTnOE; /* nTRST input */
3930                         low_output    &= ~nTRST;    /* nTRST = 0 */
3931                 }
3932                 else
3933                 {
3934                         low_direction |= nTRSTnOE;  /* nTRST output */
3935                         low_output    |= nTRST;     /* nTRST = 1 */
3936                 }
3937
3938                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3939                 {
3940                         low_direction |= nSRSTnOE;  /* nSRST output */
3941                         low_output    |= nSRST;     /* nSRST = 1 */
3942                 }
3943                 else
3944                 {
3945                         low_direction &= ~nSRSTnOE; /* nSRST input */
3946                         low_output    &= ~nSRST;    /* nSRST = 0 */
3947                 }
3948
3949 #if BUILD_FT2232_FTD2XX == 1
3950                 /* enable power to the module */
3951                 if ((status = signalyzer_h_ctrl_write(
3952                                 SIGNALYZER_DATA_BUFFER_ADDR,
3953                                 ((uint32_t)(signalyzer_h_side << 8) | 0x01)))
3954                         != FT_OK)
3955                 {
3956                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3957                                         ftd2xx_status_string(status));
3958                         return ERROR_JTAG_DEVICE_ERROR;
3959                 }
3960
3961                 if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3962                                 SIGNALYZER_COMMAND_POWERCONTROL_SET)) != FT_OK)
3963                 {
3964                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3965                                         ftd2xx_status_string(status));
3966                         return ERROR_JTAG_DEVICE_ERROR;
3967                 }
3968
3969                 /* set gpio mode register */
3970                 if ((status = signalyzer_h_ctrl_write(
3971                                 SIGNALYZER_DATA_BUFFER_ADDR,
3972                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3973                 {
3974                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3975                                         ftd2xx_status_string(status));
3976                         return ERROR_JTAG_DEVICE_ERROR;
3977                 }
3978
3979                 if ((status = signalyzer_h_ctrl_write(
3980                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x0000))
3981                         != FT_OK)
3982                 {
3983                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3984                                         ftd2xx_status_string(status));
3985                         return ERROR_JTAG_DEVICE_ERROR;
3986                 }
3987
3988                 if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3989                                 SIGNALYZER_COMMAND_GPIO_MODE)) != FT_OK)
3990                 {
3991                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3992                                         ftd2xx_status_string(status));
3993                         return ERROR_JTAG_DEVICE_ERROR;
3994                 }
3995
3996                 /* set gpio register */
3997                 if ((status = signalyzer_h_ctrl_write(
3998                                 SIGNALYZER_DATA_BUFFER_ADDR,
3999                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
4000                 {
4001                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4002                                         ftd2xx_status_string(status));
4003                         return ERROR_JTAG_DEVICE_ERROR;
4004                 }
4005
4006                 if ((status = signalyzer_h_ctrl_write(
4007                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x4040))
4008                         != FT_OK)
4009                 {
4010                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4011                                         ftd2xx_status_string(status));
4012                         return ERROR_JTAG_DEVICE_ERROR;
4013                 }
4014
4015                 if ((status = signalyzer_h_ctrl_write(
4016                                 SIGNALYZER_COMMAND_ADDR,
4017                                 SIGNALYZER_COMMAND_GPIO_STATE)) != FT_OK)
4018                 {
4019                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4020                                         ftd2xx_status_string(status));
4021                         return ERROR_JTAG_DEVICE_ERROR;
4022                 }
4023 #endif
4024         }
4025
4026         /* ADAPTOR: EM_ARM_JTAG, EM_ARM_JTAG_P, EM_JTAG, EM_JTAG_P */
4027         else if ((signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG) ||
4028                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P) ||
4029                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG)  ||
4030                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG_P))
4031         {
4032                 if (signalyzer_h_adapter_type
4033                                 == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG)
4034                         LOG_INFO("Signalyzer: EM-ARM-JTAG (ARM JTAG) "
4035                                 "detected. (HW: %2x).", (read_buf[1] >> 8));
4036                 else if (signalyzer_h_adapter_type
4037                                 == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P)
4038                         LOG_INFO("Signalyzer: EM-ARM-JTAG_P "
4039                                 "(ARM JTAG with PSU) detected. (HW: %2x).",
4040                                 (read_buf[1] >> 8));
4041                 else if (signalyzer_h_adapter_type
4042                                 == SIGNALYZER_MODULE_TYPE_EM_JTAG)
4043                         LOG_INFO("Signalyzer: EM-JTAG (Generic JTAG) "
4044                                 "detected. (HW: %2x).", (read_buf[1] >> 8));
4045                 else if (signalyzer_h_adapter_type
4046                                 == SIGNALYZER_MODULE_TYPE_EM_JTAG_P)
4047                         LOG_INFO("Signalyzer: EM-JTAG-P "
4048                                 "(Generic JTAG with PSU) detected. (HW: %2x).",
4049                                 (read_buf[1] >> 8));
4050
4051                 nTRST          = 0x02;
4052                 nTRSTnOE       = 0x04;
4053                 nSRST          = 0x08;
4054                 nSRSTnOE       = 0x10;
4055
4056                 low_output     = 0x08;
4057                 low_direction  = 0x1b;
4058
4059                 high_output    = 0x0;
4060                 high_direction = 0x1f;
4061
4062                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4063                 {
4064                         high_output |= nTRSTnOE;
4065                         high_output &= ~nTRST;
4066                 }
4067                 else
4068                 {
4069                         high_output &= ~nTRSTnOE;
4070                         high_output |= nTRST;
4071                 }
4072
4073                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4074                 {
4075                         high_output &= ~nSRSTnOE;
4076                         high_output |= nSRST;
4077                 }
4078                 else
4079                 {
4080                         high_output |= nSRSTnOE;
4081                         high_output &= ~nSRST;
4082                 }
4083
4084 #if BUILD_FT2232_FTD2XX == 1
4085                 /* enable power to the module */
4086                 if ((status = signalyzer_h_ctrl_write(
4087                                 SIGNALYZER_DATA_BUFFER_ADDR,
4088                                 ((uint32_t)(signalyzer_h_side << 8) | 0x01)))
4089                         != FT_OK)
4090                 {
4091                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4092                                         ftd2xx_status_string(status));
4093                         return ERROR_JTAG_DEVICE_ERROR;
4094                 }
4095
4096                 if ((status = signalyzer_h_ctrl_write(
4097                                 SIGNALYZER_COMMAND_ADDR,
4098                                 SIGNALYZER_COMMAND_POWERCONTROL_SET)) != FT_OK)
4099                 {
4100                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4101                                         ftd2xx_status_string(status));
4102                         return ERROR_JTAG_DEVICE_ERROR;
4103                 }
4104
4105                 /* set gpio mode register (IO_16 and IO_17 set as analog
4106                  * inputs, other is gpio)
4107                  */
4108                 if ((status = signalyzer_h_ctrl_write(
4109                                 SIGNALYZER_DATA_BUFFER_ADDR,
4110                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
4111                 {
4112                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4113                                         ftd2xx_status_string(status));
4114                         return ERROR_JTAG_DEVICE_ERROR;
4115                 }
4116
4117                 if ((status = signalyzer_h_ctrl_write(
4118                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x0060))
4119                         != FT_OK)
4120                 {
4121                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4122                                         ftd2xx_status_string(status));
4123                         return ERROR_JTAG_DEVICE_ERROR;
4124                 }
4125
4126                 if ((status = signalyzer_h_ctrl_write(
4127                                 SIGNALYZER_COMMAND_ADDR,
4128                                 SIGNALYZER_COMMAND_GPIO_MODE)) != FT_OK)
4129                 {
4130                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4131                                         ftd2xx_status_string(status));
4132                         return ERROR_JTAG_DEVICE_ERROR;
4133                 }
4134
4135                 /* set gpio register (all inputs, for -P modules,
4136                  * PSU will be turned off)
4137                  */
4138                 if ((status = signalyzer_h_ctrl_write(
4139                                 SIGNALYZER_DATA_BUFFER_ADDR,
4140                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
4141                 {
4142                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4143                                         ftd2xx_status_string(status));
4144                         return ERROR_JTAG_DEVICE_ERROR;
4145                 }
4146
4147                 if ((status = signalyzer_h_ctrl_write(
4148                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x0000))
4149                         != FT_OK)
4150                 {
4151                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4152                                         ftd2xx_status_string(status));
4153                         return ERROR_JTAG_DEVICE_ERROR;
4154                 }
4155
4156                 if ((status = signalyzer_h_ctrl_write(
4157                                 SIGNALYZER_COMMAND_ADDR,
4158                                 SIGNALYZER_COMMAND_GPIO_STATE)) != FT_OK)
4159                 {
4160                         LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
4161                                         ftd2xx_status_string(status));
4162                         return ERROR_JTAG_DEVICE_ERROR;
4163                 }
4164 #endif
4165         }
4166
4167         else if (signalyzer_h_adapter_type == 0x0000)
4168         {
4169                 LOG_INFO("Signalyzer: No external modules were detected.");
4170
4171                 nTRST    = 0x10;
4172                 nTRSTnOE = 0x10;
4173                 nSRST    = 0x20;
4174                 nSRSTnOE = 0x20;
4175
4176                 low_output     = 0x08;
4177                 low_direction  = 0x1b;
4178
4179                 high_output    = 0x0;
4180                 high_direction = 0x0;
4181
4182                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4183                 {
4184                         low_direction &= ~nTRSTnOE; /* nTRST input */
4185                         low_output    &= ~nTRST;    /* nTRST = 0 */
4186                 }
4187                 else
4188                 {
4189                         low_direction |= nTRSTnOE;  /* nTRST output */
4190                         low_output    |= nTRST;     /* nTRST = 1 */
4191                 }
4192
4193                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4194                 {
4195                         low_direction |= nSRSTnOE;  /* nSRST output */
4196                         low_output    |= nSRST;     /* nSRST = 1 */
4197                 }
4198                 else
4199                 {
4200                         low_direction &= ~nSRSTnOE; /* nSRST input */
4201                         low_output    &= ~nSRST;    /* nSRST = 0 */
4202                 }
4203         }
4204         else
4205         {
4206                 LOG_ERROR("Unknown module type is detected: %.4x",
4207                                 signalyzer_h_adapter_type);
4208                 return ERROR_JTAG_DEVICE_ERROR;
4209         }
4210
4211         /* initialize low byte of controller for jtag operation */
4212         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
4213         {
4214                 LOG_ERROR("couldn't initialize Signalyzer-H layout");
4215                 return ERROR_JTAG_INIT_FAILED;
4216         }
4217
4218 #if BUILD_FT2232_FTD2XX == 1
4219         if (ftdi_device == FT_DEVICE_2232H)
4220         {
4221                 /* initialize high byte of controller for jtag operation */
4222                 if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
4223                 {
4224                         LOG_ERROR("couldn't initialize Signalyzer-H layout");
4225                         return ERROR_JTAG_INIT_FAILED;
4226                 }
4227         }
4228 #elif BUILD_FT2232_LIBFTDI == 1
4229         if (ftdi_device == TYPE_2232H)
4230         {
4231                 /* initialize high byte of controller for jtag operation */
4232                 if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
4233                 {
4234                         LOG_ERROR("couldn't initialize Signalyzer-H layout");
4235                         return ERROR_JTAG_INIT_FAILED;
4236                 }
4237         }
4238 #endif
4239         return ERROR_OK;
4240 }
4241
4242 static void signalyzer_h_reset(int trst, int srst)
4243 {
4244         enum reset_types jtag_reset_config = jtag_get_reset_config();
4245
4246         /* ADAPTOR: EM_LT16_A */
4247         if (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_LT16_A)
4248         {
4249                 if (trst == 1)
4250                 {
4251                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4252                                 /* switch to output pin (output is low) */
4253                                 low_direction |= nTRSTnOE;
4254                         else
4255                                 /* switch output low */
4256                                 low_output &= ~nTRST;
4257                 }
4258                 else if (trst == 0)
4259                 {
4260                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4261                                 /* switch to input pin (high-Z + internal
4262                                  * and external pullup) */
4263                                 low_direction &= ~nTRSTnOE;
4264                         else
4265                                 /* switch output high */
4266                                 low_output |= nTRST;
4267                 }
4268
4269                 if (srst == 1)
4270                 {
4271                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4272                                 /* switch output low */
4273                                 low_output &= ~nSRST;
4274                         else
4275                                 /* switch to output pin (output is low) */
4276                                 low_direction |= nSRSTnOE;
4277                 }
4278                 else if (srst == 0)
4279                 {
4280                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4281                                 /* switch output high */
4282                                 low_output |= nSRST;
4283                         else
4284                                 /* switch to input pin (high-Z) */
4285                                 low_direction &= ~nSRSTnOE;
4286                 }
4287
4288                 /* command "set data bits low byte" */
4289                 buffer_write(0x80);
4290                 buffer_write(low_output);
4291                 buffer_write(low_direction);
4292                 LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, "
4293                                 "low_direction: 0x%2.2x",
4294                                 trst, srst, low_output, low_direction);
4295         }
4296         /* ADAPTOR: EM_ARM_JTAG,  EM_ARM_JTAG_P, EM_JTAG, EM_JTAG_P */
4297         else if ((signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG) ||
4298                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P) ||
4299                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG)  ||
4300                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG_P))
4301         {
4302                 if (trst == 1)
4303                 {
4304                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4305                                 high_output &= ~nTRSTnOE;
4306                         else
4307                                 high_output &= ~nTRST;
4308                 }
4309                 else if (trst == 0)
4310                 {
4311                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4312                                 high_output |= nTRSTnOE;
4313                         else
4314                                 high_output |= nTRST;
4315                 }
4316
4317                 if (srst == 1)
4318                 {
4319                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4320                                 high_output &= ~nSRST;
4321                         else
4322                                 high_output &= ~nSRSTnOE;
4323                 }
4324                 else if (srst == 0)
4325                 {
4326                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4327                                 high_output |= nSRST;
4328                         else
4329                                 high_output |= nSRSTnOE;
4330                 }
4331
4332                 /* command "set data bits high byte" */
4333                 buffer_write(0x82);
4334                 buffer_write(high_output);
4335                 buffer_write(high_direction);
4336                 LOG_INFO("trst: %i, srst: %i, high_output: 0x%2.2x, "
4337                                 "high_direction: 0x%2.2x",
4338                                 trst, srst, high_output, high_direction);
4339         }
4340         else if (signalyzer_h_adapter_type == 0x0000)
4341         {
4342                 if (trst == 1)
4343                 {
4344                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4345                                 /* switch to output pin (output is low) */
4346                                 low_direction |= nTRSTnOE;
4347                         else
4348                                 /* switch output low */
4349                                 low_output &= ~nTRST;
4350                 }
4351                 else if (trst == 0)
4352                 {
4353                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4354                                 /* switch to input pin (high-Z + internal
4355                                  * and external pullup) */
4356                                 low_direction &= ~nTRSTnOE;
4357                         else
4358                                 /* switch output high */
4359                                 low_output |= nTRST;
4360                 }
4361
4362                 if (srst == 1)
4363                 {
4364                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4365                                 /* switch output low */
4366                                 low_output &= ~nSRST;
4367                         else
4368                                 /* switch to output pin (output is low) */
4369                                 low_direction |= nSRSTnOE;
4370                 }
4371                 else if (srst == 0)
4372                 {
4373                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4374                                 /* switch output high */
4375                                 low_output |= nSRST;
4376                         else
4377                                 /* switch to input pin (high-Z) */
4378                                 low_direction &= ~nSRSTnOE;
4379                 }
4380
4381                 /* command "set data bits low byte" */
4382                 buffer_write(0x80);
4383                 buffer_write(low_output);
4384                 buffer_write(low_direction);
4385                 LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, "
4386                                 "low_direction: 0x%2.2x",
4387                                 trst, srst, low_output, low_direction);
4388         }
4389 }
4390
4391 static void signalyzer_h_blink(void)
4392 {
4393         signalyzer_h_led_set(signalyzer_h_side, SIGNALYZER_LED_RED, 100, 0, 1);
4394 }
4395
4396 /********************************************************************
4397  * Support for KT-LINK
4398  * JTAG adapter from KRISTECH
4399  * http://www.kristech.eu
4400  *******************************************************************/
4401 static int ktlink_init(void)
4402 {
4403         uint8_t  swd_en = 0x20; //0x20 SWD disable, 0x00 SWD enable (ADBUS5)
4404
4405         low_output    = 0x08 | swd_en; // value; TMS=1,TCK=0,TDI=0,SWD=swd_en
4406         low_direction = 0x3B;          // out=1; TCK/TDI/TMS=out,TDO=in,SWD=out,RTCK=in,SRSTIN=in
4407
4408         /* initialize low byte for jtag */
4409         if (ft2232_set_data_bits_low_byte(low_output,low_direction) != ERROR_OK)
4410         {
4411                 LOG_ERROR("couldn't initialize FT2232 with 'ktlink' layout");
4412                 return ERROR_JTAG_INIT_FAILED;
4413         }
4414
4415         nTRST    = 0x01;
4416         nSRST    = 0x02;
4417         nTRSTnOE = 0x04;
4418         nSRSTnOE = 0x08;
4419
4420         high_output    = 0x80; // turn LED on
4421         high_direction = 0xFF; // all outputs
4422
4423         enum reset_types jtag_reset_config = jtag_get_reset_config();
4424
4425         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN) {
4426                 high_output |= nTRSTnOE;
4427                 high_output &= ~nTRST;
4428         } else {
4429                 high_output &= ~nTRSTnOE;
4430                 high_output |= nTRST;
4431         }
4432
4433         if (jtag_reset_config & RESET_SRST_PUSH_PULL) {
4434                 high_output &= ~nSRSTnOE;
4435                 high_output |= nSRST;
4436         } else {
4437                 high_output |= nSRSTnOE;
4438                 high_output &= ~nSRST;
4439         }
4440
4441         /* initialize high byte for jtag */
4442         if (ft2232_set_data_bits_high_byte(high_output,high_direction) != ERROR_OK)
4443         {
4444                 LOG_ERROR("couldn't initialize FT2232 with 'ktlink' layout");
4445                 return ERROR_JTAG_INIT_FAILED;
4446         }
4447
4448         return ERROR_OK;
4449 }
4450
4451 static void ktlink_reset(int trst, int srst)
4452 {
4453         enum reset_types jtag_reset_config = jtag_get_reset_config();
4454
4455         if (trst == 1) {
4456                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4457                         high_output &= ~nTRSTnOE;
4458                 else
4459                         high_output &= ~nTRST;
4460         } else if (trst == 0) {
4461                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
4462                         high_output |= nTRSTnOE;
4463                 else
4464                         high_output |= nTRST;
4465         }
4466
4467         if (srst == 1) {
4468                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4469                         high_output &= ~nSRST;
4470                 else
4471                         high_output &= ~nSRSTnOE;
4472         } else if (srst == 0) {
4473                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
4474                         high_output |= nSRST;
4475                 else
4476                         high_output |= nSRSTnOE;
4477         }
4478
4479         buffer_write(0x82); // command "set data bits high byte"
4480         buffer_write(high_output);
4481         buffer_write(high_direction);
4482         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,high_direction);
4483 }
4484
4485 static void ktlink_blink(void)
4486 {
4487         /* LED connected to ACBUS7 */
4488         high_output ^= 0x80;
4489
4490         buffer_write(0x82);  // command "set data bits high byte"
4491         buffer_write(high_output);
4492         buffer_write(high_direction);
4493 }
4494
4495 static const struct command_registration ft2232_command_handlers[] = {
4496         {
4497                 .name = "ft2232_device_desc",
4498                 .handler = &ft2232_handle_device_desc_command,
4499                 .mode = COMMAND_CONFIG,
4500                 .help = "set the USB device description of the FTDI FT2232 device",
4501                 .usage = "description_string",
4502         },
4503         {
4504                 .name = "ft2232_serial",
4505                 .handler = &ft2232_handle_serial_command,
4506                 .mode = COMMAND_CONFIG,
4507                 .help = "set the serial number of the FTDI FT2232 device",
4508                 .usage = "serial_string",
4509         },
4510         {
4511                 .name = "ft2232_layout",
4512                 .handler = &ft2232_handle_layout_command,
4513                 .mode = COMMAND_CONFIG,
4514                 .help = "set the layout of the FT2232 GPIO signals used "
4515                         "to control output-enables and reset signals",
4516                 .usage = "layout_name",
4517         },
4518         {
4519                 .name = "ft2232_vid_pid",
4520                 .handler = &ft2232_handle_vid_pid_command,
4521                 .mode = COMMAND_CONFIG,
4522                 .help = "the vendor ID and product ID of the FTDI FT2232 device",
4523                 .usage = "(vid pid)* ",
4524         },
4525         {
4526                 .name = "ft2232_latency",
4527                 .handler = &ft2232_handle_latency_command,
4528                 .mode = COMMAND_CONFIG,
4529                 .help = "set the FT2232 latency timer to a new value",
4530                 .usage = "value",
4531         },
4532         COMMAND_REGISTRATION_DONE
4533 };
4534
4535 struct jtag_interface ft2232_interface = {
4536         .name = "ft2232",
4537         .supported = DEBUG_CAP_TMS_SEQ,
4538         .commands = ft2232_command_handlers,
4539         .transports = jtag_only,
4540
4541         .init = ft2232_init,
4542         .quit = ft2232_quit,
4543         .speed = ft2232_speed,
4544         .speed_div = ft2232_speed_div,
4545         .khz = ft2232_khz,
4546         .execute_queue = ft2232_execute_queue,
4547 };