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