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