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