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