]> git.gag.com Git - fw/openocd/blob - src/jtag/ft2232.c
michal smulski <michal.smulski@ooma.com> fix regression in jtag_add_pathmove() which...
[fw/openocd] / src / jtag / ft2232.c
1 /***************************************************************************
2 *   Copyright (C) 2004, 2006 by Dominic Rath                              *
3 *   Dominic.Rath@gmx.de                                                   *
4 *                                                                         *
5 *   Copyright (C) 2008 by Spencer Oliver                                  *
6 *   spen@spen-soft.co.uk                                                  *
7 *                                                                         *
8 *   Copyright (C) 2009 by SoftPLC Corporation.  http://softplc.com        *
9 *       Dick Hollenbeck <dick@softplc.com>                                    *
10 *                                                                         *
11 *   This program is free software; you can redistribute it and/or modify  *
12 *   it under the terms of the GNU General Public License as published by  *
13 *   the Free Software Foundation; either version 2 of the License, or     *
14 *   (at your option) any later version.                                   *
15 *                                                                         *
16 *   This program is distributed in the hope that it will be useful,       *
17 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19 *   GNU General Public License for more details.                          *
20 *                                                                         *
21 *   You should have received a copy of the GNU General Public License     *
22 *   along with this program; if not, write to the                         *
23 *   Free Software Foundation, Inc.,                                       *
24 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
25 ***************************************************************************/
26
27 /* This code uses information contained in the MPSSE specification which was
28  * found here:
29  * http://www.ftdichip.com/Documents/AppNotes/AN2232C-01_MPSSE_Cmnd.pdf
30  * Hereafter this is called the "MPSSE Spec".
31  *
32  * The datasheet for the ftdichip.com's FT2232D part is here:
33  * http://www.ftdichip.com/Documents/DataSheets/DS_FT2232D.pdf
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39
40 /* project specific includes */
41 #include "interface.h"
42 #include "commands.h"
43 #include "time_support.h"
44
45 #if IS_CYGWIN == 1
46 #include <windows.h>
47 #endif
48
49 #include <assert.h>
50
51 #if (BUILD_FT2232_FTD2XX == 1 && BUILD_FT2232_LIBFTDI == 1)
52 #error "BUILD_FT2232_FTD2XX && BUILD_FT2232_LIBFTDI are mutually exclusive"
53 #elif (BUILD_FT2232_FTD2XX != 1 && BUILD_FT2232_LIBFTDI != 1)
54 #error "BUILD_FT2232_FTD2XX || BUILD_FT2232_LIBFTDI must be chosen"
55 #endif
56
57 /* FT2232 access library includes */
58 #if BUILD_FT2232_FTD2XX == 1
59 #include <ftd2xx.h>
60 #elif BUILD_FT2232_LIBFTDI == 1
61 #include <ftdi.h>
62 #endif
63
64 /* max TCK for the high speed devices 30000 kHz */
65 #define FTDI_2232H_4232H_MAX_TCK        30000
66 /* max TCK for the full speed devices 6000 kHz */
67 #define FTDI_2232C_MAX_TCK 6000
68 /* this speed value tells that RTCK is requested */
69 #define RTCK_SPEED -1
70
71 #ifndef BUILD_FT2232_HIGHSPEED
72  #if BUILD_FT2232_FTD2XX == 1
73         enum { FT_DEVICE_2232H = 6, FT_DEVICE_4232H };
74  #elif BUILD_FT2232_LIBFTDI == 1
75         enum { TYPE_2232H = 4, TYPE_4232H = 5 };
76  #endif
77 #endif
78
79 static int ft2232_execute_queue(void);
80 static int ft2232_speed(int speed);
81 static int ft2232_speed_div(int speed, int* khz);
82 static int ft2232_khz(int khz, int* jtag_speed);
83 static int ft2232_register_commands(struct command_context_s* cmd_ctx);
84 static int ft2232_init(void);
85 static int ft2232_quit(void);
86
87 static int ft2232_handle_device_desc_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
88 static int ft2232_handle_serial_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
89 static int ft2232_handle_layout_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
90 static int ft2232_handle_vid_pid_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
91 static int ft2232_handle_latency_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
92
93 /**
94  * Send out \a num_cycles on the TCK line while the TAP(s) are in a
95  * stable state.  Calling code must ensure that current state is stable,
96  * that verification is not done in here.
97  *
98  * @param num_cycles The number of clocks cycles to send.
99  * @param cmd The command to send.
100  *
101  * @returns ERROR_OK on success, or ERROR_JTAG_QUEUE_FAILED on failure.
102  */
103 static int ft2232_stableclocks(int num_cycles, jtag_command_t* cmd);
104
105 static char *       ft2232_device_desc_A = NULL;
106 static char*        ft2232_device_desc = NULL;
107 static char*        ft2232_serial  = NULL;
108 static char*        ft2232_layout  = NULL;
109 static uint8_t          ft2232_latency = 2;
110 static unsigned         ft2232_max_tck = FTDI_2232C_MAX_TCK;
111
112 #define MAX_USB_IDS 8
113 /* vid = pid = 0 marks the end of the list */
114 static uint16_t ft2232_vid[MAX_USB_IDS + 1] = { 0x0403, 0 };
115 static uint16_t ft2232_pid[MAX_USB_IDS + 1] = { 0x6010, 0 };
116
117 typedef struct ft2232_layout_s
118 {
119         char* name;
120         int (*init)(void);
121         void (*reset)(int trst, int srst);
122         void (*blink)(void);
123 } ft2232_layout_t;
124
125 /* init procedures for supported layouts */
126 static int usbjtag_init(void);
127 static int jtagkey_init(void);
128 static int olimex_jtag_init(void);
129 static int flyswatter_init(void);
130 static int turtle_init(void);
131 static int comstick_init(void);
132 static int stm32stick_init(void);
133 static int axm0432_jtag_init(void);
134 static int sheevaplug_init(void);
135 static int icebear_jtag_init(void);
136 static int cortino_jtag_init(void);
137
138 /* reset procedures for supported layouts */
139 static void usbjtag_reset(int trst, int srst);
140 static void jtagkey_reset(int trst, int srst);
141 static void olimex_jtag_reset(int trst, int srst);
142 static void flyswatter_reset(int trst, int srst);
143 static void turtle_reset(int trst, int srst);
144 static void comstick_reset(int trst, int srst);
145 static void stm32stick_reset(int trst, int srst);
146 static void axm0432_jtag_reset(int trst, int srst);
147 static void sheevaplug_reset(int trst, int srst);
148 static void icebear_jtag_reset(int trst, int srst);
149
150 /* blink procedures for layouts that support a blinking led */
151 static void olimex_jtag_blink(void);
152 static void flyswatter_jtag_blink(void);
153 static void turtle_jtag_blink(void);
154
155 static const ft2232_layout_t  ft2232_layouts[] =
156 {
157         { "usbjtag",              usbjtag_init,              usbjtag_reset,      NULL                    },
158         { "jtagkey",              jtagkey_init,              jtagkey_reset,      NULL                    },
159         { "jtagkey_prototype_v1", jtagkey_init,              jtagkey_reset,      NULL                    },
160         { "oocdlink",             jtagkey_init,              jtagkey_reset,      NULL                    },
161         { "signalyzer",           usbjtag_init,              usbjtag_reset,      NULL                    },
162         { "evb_lm3s811",          usbjtag_init,              usbjtag_reset,      NULL                    },
163         { "luminary_icdi",        usbjtag_init,              usbjtag_reset,      NULL                    },
164         { "olimex-jtag",          olimex_jtag_init,          olimex_jtag_reset,  olimex_jtag_blink       },
165         { "flyswatter",           flyswatter_init,           flyswatter_reset,   flyswatter_jtag_blink   },
166         { "turtelizer2",          turtle_init,               turtle_reset,       turtle_jtag_blink       },
167         { "comstick",             comstick_init,             comstick_reset,     NULL                    },
168         { "stm32stick",           stm32stick_init,           stm32stick_reset,   NULL                    },
169         { "axm0432_jtag",         axm0432_jtag_init,         axm0432_jtag_reset, NULL                    },
170         { "sheevaplug",           sheevaplug_init,           sheevaplug_reset,   NULL                    },
171         { "icebear",              icebear_jtag_init,         icebear_jtag_reset, NULL                    },
172         { "cortino",              cortino_jtag_init,         comstick_reset, NULL                        },
173         { NULL,                   NULL,                      NULL,               NULL                    },
174 };
175
176 static uint8_t                  nTRST, nTRSTnOE, nSRST, nSRSTnOE;
177
178 static const ft2232_layout_t *layout;
179 static uint8_t                  low_output     = 0x0;
180 static uint8_t                  low_direction  = 0x0;
181 static uint8_t                  high_output    = 0x0;
182 static uint8_t                  high_direction = 0x0;
183
184 #if BUILD_FT2232_FTD2XX == 1
185 static FT_HANDLE        ftdih = NULL;
186 static FT_DEVICE        ftdi_device = 0;
187 #elif BUILD_FT2232_LIBFTDI == 1
188 static struct ftdi_context ftdic;
189 static enum ftdi_chip_type ftdi_device;
190 #endif
191
192 static jtag_command_t* first_unsent;        /* next command that has to be sent */
193 static int             require_send;
194
195 /*      http://urjtag.wiki.sourceforge.net/Cable + FT2232 says:
196
197         "There is a significant difference between libftdi and libftd2xx. The latter
198         one allows to schedule up to 64*64 bytes of result data while libftdi fails
199         with more than 4*64. As a consequence, the FT2232 driver is forced to
200         perform around 16x more USB transactions for long command streams with TDO
201         capture when running with libftdi."
202
203         No idea how we get
204         #define FT2232_BUFFER_SIZE 131072
205         a comment would have been nice.
206 */
207
208 #define FT2232_BUFFER_SIZE 131072
209
210 static uint8_t*             ft2232_buffer = NULL;
211 static int             ft2232_buffer_size  = 0;
212 static int             ft2232_read_pointer = 0;
213 static int             ft2232_expect_read  = 0;
214
215 /**
216  * Function buffer_write
217  * writes a byte into the byte buffer, "ft2232_buffer", which must be sent later.
218  * @param val is the byte to send.
219  */
220 static inline void buffer_write(uint8_t val)
221 {
222         assert(ft2232_buffer);
223         assert((unsigned) ft2232_buffer_size < (unsigned) FT2232_BUFFER_SIZE);
224         ft2232_buffer[ft2232_buffer_size++] = val;
225 }
226
227 /**
228  * Function buffer_read
229  * returns a byte from the byte buffer.
230  */
231 static inline uint8_t buffer_read(void)
232 {
233         assert(ft2232_buffer);
234         assert(ft2232_read_pointer < ft2232_buffer_size);
235         return ft2232_buffer[ft2232_read_pointer++];
236 }
237
238 /**
239  * Clocks out \a bit_count bits on the TMS line, starting with the least
240  * significant bit of tms_bits and progressing to more significant bits.
241  * Rigorous state transition logging is done here via tap_set_state().
242  *
243  * @param mpsse_cmd One of the MPSSE TMS oriented commands such as
244  *      0x4b or 0x6b.  See the MPSSE spec referenced above for their
245  *      functionality. The MPSSE command "Clock Data to TMS/CS Pin (no Read)"
246  *      is often used for this, 0x4b.
247  *
248  * @param tms_bits Holds the sequence of bits to send.
249  * @param tms_count Tells how many bits in the sequence.
250  * @param tdi_bit A single bit to pass on to TDI before the first TCK
251  *      cycle and held static for the duration of TMS clocking.
252  *
253  * See the MPSSE spec referenced above.
254  */
255 static void clock_tms(uint8_t mpsse_cmd, int tms_bits, int tms_count, bool tdi_bit)
256 {
257         uint8_t tms_byte;
258         int     i;
259         int     tms_ndx;                                /* bit index into tms_byte */
260
261         assert(tms_count > 0);
262
263 #if 0
264         LOG_DEBUG("mpsse cmd=%02x, tms_bits = 0x%08x, bit_count=%d", mpsse_cmd, tms_bits, tms_count);
265 #endif
266
267         for (tms_byte = tms_ndx = i = 0;   i < tms_count;   ++i, tms_bits>>=1)
268         {
269                 bool bit = tms_bits & 1;
270
271                 if (bit)
272                         tms_byte |= (1 << tms_ndx);
273
274                 /* always do state transitions in public view */
275                 tap_set_state(tap_state_transition(tap_get_state(), bit));
276
277                 /*      we wrote a bit to tms_byte just above, increment bit index.  if bit was zero
278                         also increment.
279                 */
280                 ++tms_ndx;
281
282                 if (tms_ndx == 7  || i == tms_count-1)
283                 {
284                         buffer_write(mpsse_cmd);
285                         buffer_write(tms_ndx - 1);
286
287                         /*      Bit 7 of the byte is passed on to TDI/DO before the first TCK/SK of
288                                 TMS/CS and is held static for the duration of TMS/CS clocking.
289                         */
290                         buffer_write(tms_byte | (tdi_bit << 7));
291                 }
292         }
293 }
294
295 /**
296  * Function get_tms_buffer_requirements
297  * returns what clock_tms() will consume if called with
298  * same \a bit_count.
299  */
300 static inline int get_tms_buffer_requirements(int bit_count)
301 {
302         return ((bit_count + 6)/7) * 3;
303 }
304
305 /**
306  * Function move_to_state
307  * moves the TAP controller from the current state to a
308  * \a goal_state through a path given by tap_get_tms_path().  State transition
309  * logging is performed by delegation to clock_tms().
310  *
311  * @param goal_state is the destination state for the move.
312  */
313 static void move_to_state(tap_state_t goal_state)
314 {
315         tap_state_t     start_state = tap_get_state();
316
317         /*      goal_state is 1/2 of a tuple/pair of states which allow convenient
318                 lookup of the required TMS pattern to move to this state from the
319                 start state.
320         */
321
322         /* do the 2 lookups */
323         int tms_bits  = tap_get_tms_path(start_state, goal_state);
324         int tms_count = tap_get_tms_path_len(start_state, goal_state);
325
326         DEBUG_JTAG_IO("start=%s goal=%s", tap_state_name(start_state), tap_state_name(goal_state));
327
328         clock_tms(0x4b,  tms_bits, tms_count, 0);
329 }
330
331 jtag_interface_t ft2232_interface =
332 {
333         .name                   = "ft2232",
334         .execute_queue          = ft2232_execute_queue,
335         .speed                  = ft2232_speed,
336         .speed_div              = ft2232_speed_div,
337         .khz                    = ft2232_khz,
338         .register_commands      = ft2232_register_commands,
339         .init                   = ft2232_init,
340         .quit                   = ft2232_quit,
341 };
342
343 static int ft2232_write(uint8_t* buf, int size, uint32_t* bytes_written)
344 {
345 #if BUILD_FT2232_FTD2XX == 1
346         FT_STATUS status;
347         DWORD dw_bytes_written;
348         if ((status = FT_Write(ftdih, buf, size, &dw_bytes_written)) != FT_OK)
349         {
350                 *bytes_written = dw_bytes_written;
351                 LOG_ERROR("FT_Write returned: %lu", status);
352                 return ERROR_JTAG_DEVICE_ERROR;
353         }
354         else
355         {
356                 *bytes_written = dw_bytes_written;
357                 return ERROR_OK;
358         }
359 #elif BUILD_FT2232_LIBFTDI == 1
360         int retval;
361         if ((retval = ftdi_write_data(&ftdic, buf, size)) < 0)
362         {
363                 *bytes_written = 0;
364                 LOG_ERROR("ftdi_write_data: %s", ftdi_get_error_string(&ftdic));
365                 return ERROR_JTAG_DEVICE_ERROR;
366         }
367         else
368         {
369                 *bytes_written = retval;
370                 return ERROR_OK;
371         }
372 #endif
373 }
374
375 static int ft2232_read(uint8_t* buf, uint32_t size, uint32_t* bytes_read)
376 {
377 #if BUILD_FT2232_FTD2XX == 1
378         DWORD dw_bytes_read;
379         FT_STATUS status;
380         int timeout = 5;
381         *bytes_read = 0;
382
383         while ((*bytes_read < size) && timeout--)
384         {
385                 if ((status = FT_Read(ftdih, buf + *bytes_read, size -
386                                           *bytes_read, &dw_bytes_read)) != FT_OK)
387                 {
388                         *bytes_read = 0;
389                         LOG_ERROR("FT_Read returned: %lu", status);
390                         return ERROR_JTAG_DEVICE_ERROR;
391                 }
392                 *bytes_read += dw_bytes_read;
393         }
394
395 #elif BUILD_FT2232_LIBFTDI == 1
396         int retval;
397         int timeout = 100;
398         *bytes_read = 0;
399
400         while ((*bytes_read < size) && timeout--)
401         {
402                 if ((retval = ftdi_read_data(&ftdic, buf + *bytes_read, size - *bytes_read)) < 0)
403                 {
404                         *bytes_read = 0;
405                         LOG_ERROR("ftdi_read_data: %s", ftdi_get_error_string(&ftdic));
406                         return ERROR_JTAG_DEVICE_ERROR;
407                 }
408                 *bytes_read += retval;
409         }
410
411 #endif
412
413         if (*bytes_read < size)
414         {
415                 LOG_ERROR("couldn't read the requested number of bytes from FT2232 device (%i < %i)",
416                           (unsigned int)(*bytes_read),
417                           (unsigned int)size);
418                 return ERROR_JTAG_DEVICE_ERROR;
419         }
420
421         return ERROR_OK;
422 }
423
424 static bool ft2232_device_is_highspeed(void)
425 {
426 #if BUILD_FT2232_FTD2XX == 1
427         return (ftdi_device == FT_DEVICE_2232H) || (ftdi_device == FT_DEVICE_4232H);
428 #elif BUILD_FT2232_LIBFTDI == 1
429         return (ftdi_device == TYPE_2232H || ftdi_device == TYPE_4232H);
430 #endif
431 }
432
433 /*
434  * Commands that only apply to the FT2232H and FT4232H devices.
435  * See chapter 6 in http://www.ftdichip.com/Documents/AppNotes/
436  * AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf
437  */
438
439 static int ft2232h_ft4232h_adaptive_clocking(bool enable)
440 {
441         uint8_t buf = enable ? 0x96 : 0x97;
442         LOG_DEBUG("%2.2x", buf);
443
444         uint32_t bytes_written;
445         int retval = ft2232_write(&buf, 1, &bytes_written);
446         if ((ERROR_OK != retval) || (bytes_written != 1))
447         {
448                 LOG_ERROR("couldn't write command to %s adaptive clocking"
449                         , enable ? "enable" : "disable");
450                 return retval;
451         }
452
453         return ERROR_OK;
454 }
455
456 /**
457  * Enable/disable the clk divide by 5 of the 60MHz master clock.
458  * This result in a JTAG clock speed range of 91.553Hz-6MHz
459  * respective 457.763Hz-30MHz.
460  */
461 static int ft2232h_ft4232h_clk_divide_by_5(bool enable)
462 {
463         uint32_t bytes_written;
464         uint8_t buf = enable ?  0x8b : 0x8a;
465         int retval = ft2232_write(&buf, 1, &bytes_written);
466         if ((ERROR_OK != retval) || (bytes_written != 1))
467         {
468                 LOG_ERROR("couldn't write command to %s clk divide by 5"
469                         , enable ? "enable" : "disable");
470                 return ERROR_JTAG_INIT_FAILED;
471         }
472         ft2232_max_tck = enable ? FTDI_2232C_MAX_TCK : FTDI_2232H_4232H_MAX_TCK;
473         LOG_INFO("max TCK change to: %u kHz", ft2232_max_tck);
474
475         return ERROR_OK;
476 }
477
478 static int ft2232_speed(int speed)
479 {
480         uint8_t buf[3];
481         int retval;
482         uint32_t bytes_written;
483
484         retval = ERROR_OK;
485         bool enable_adaptive_clocking = (RTCK_SPEED == speed);
486         if (ft2232_device_is_highspeed())
487                 retval = ft2232h_ft4232h_adaptive_clocking(enable_adaptive_clocking);
488         else if (enable_adaptive_clocking)
489         {
490                 LOG_ERROR("ft2232 device %lu does not support RTCK"
491                         , (long unsigned int)ftdi_device);
492                 return ERROR_FAIL;
493         }
494
495         if ((enable_adaptive_clocking) || (ERROR_OK != retval))
496                 return retval;
497
498         buf[0] = 0x86;                                  /* command "set divisor" */
499         buf[1] = speed & 0xff;                  /* valueL (0 = 6MHz, 1 = 3MHz, 2 = 2.0MHz, ...*/
500         buf[2] = (speed >> 8) & 0xff;   /* valueH */
501
502         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
503         if (((retval = ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
504         {
505                 LOG_ERROR("couldn't set FT2232 TCK speed");
506                 return retval;
507         }
508
509         return ERROR_OK;
510 }
511
512 static int ft2232_speed_div(int speed, int* khz)
513 {
514         /* Take a look in the FT2232 manual,
515          * AN2232C-01 Command Processor for
516          * MPSSE and MCU Host Bus. Chapter 3.8 */
517
518         *khz = (RTCK_SPEED == speed) ? 0 : ft2232_max_tck / (1 + speed);
519
520         return ERROR_OK;
521 }
522
523 static int ft2232_khz(int khz, int* jtag_speed)
524 {
525         if (khz == 0)
526         {
527                 if (ft2232_device_is_highspeed())
528                 {
529                         *jtag_speed = RTCK_SPEED;
530                         return ERROR_OK;
531                 }
532                 else
533                 {
534                         LOG_DEBUG("RCLK not supported");
535                         return ERROR_FAIL;
536                 }
537         }
538
539         /* Take a look in the FT2232 manual,
540          * AN2232C-01 Command Processor for
541          * MPSSE and MCU Host Bus. Chapter 3.8
542          *
543          * We will calc here with a multiplier
544          * of 10 for better rounding later. */
545
546         /* Calc speed, (ft2232_max_tck / khz) - 1 */
547         /* Use 65000 for better rounding */
548         *jtag_speed = ((ft2232_max_tck*10) / khz) - 10;
549
550         /* Add 0.9 for rounding */
551         *jtag_speed += 9;
552
553         /* Calc real speed */
554         *jtag_speed = *jtag_speed / 10;
555
556         /* Check if speed is greater than 0 */
557         if (*jtag_speed < 0)
558         {
559                 *jtag_speed = 0;
560         }
561
562         /* Check max value */
563         if (*jtag_speed > 0xFFFF)
564         {
565                 *jtag_speed = 0xFFFF;
566         }
567
568         return ERROR_OK;
569 }
570
571 static int ft2232_register_commands(struct command_context_s* cmd_ctx)
572 {
573         register_command(cmd_ctx, NULL, "ft2232_device_desc", ft2232_handle_device_desc_command,
574                         COMMAND_CONFIG, "the USB device description of the FTDI FT2232 device");
575         register_command(cmd_ctx, NULL, "ft2232_serial", ft2232_handle_serial_command,
576                         COMMAND_CONFIG, "the serial number of the FTDI FT2232 device");
577         register_command(cmd_ctx, NULL, "ft2232_layout", ft2232_handle_layout_command,
578                         COMMAND_CONFIG, "the layout of the FT2232 GPIO signals used to control output-enables and reset signals");
579         register_command(cmd_ctx, NULL, "ft2232_vid_pid", ft2232_handle_vid_pid_command,
580                         COMMAND_CONFIG, "the vendor ID and product ID of the FTDI FT2232 device");
581         register_command(cmd_ctx, NULL, "ft2232_latency", ft2232_handle_latency_command,
582                         COMMAND_CONFIG, "set the FT2232 latency timer to a new value");
583         return ERROR_OK;
584 }
585
586 static void ft2232_end_state(tap_state_t state)
587 {
588         if (tap_is_state_stable(state))
589                 tap_set_end_state(state);
590         else
591         {
592                 LOG_ERROR("BUG: %s is not a stable end state", tap_state_name(state));
593                 exit(-1);
594         }
595 }
596
597 static void ft2232_read_scan(enum scan_type type, uint8_t* buffer, int scan_size)
598 {
599         int num_bytes = (scan_size + 7) / 8;
600         int bits_left = scan_size;
601         int cur_byte  = 0;
602
603         while (num_bytes-- > 1)
604         {
605                 buffer[cur_byte++] = buffer_read();
606                 bits_left -= 8;
607         }
608
609         buffer[cur_byte] = 0x0;
610
611         /* There is one more partial byte left from the clock data in/out instructions */
612         if (bits_left > 1)
613         {
614                 buffer[cur_byte] = buffer_read() >> 1;
615         }
616         /* 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 */
617         buffer[cur_byte] = (buffer[cur_byte] | (((buffer_read()) << 1) & 0x80)) >> (8 - bits_left);
618 }
619
620 static void ft2232_debug_dump_buffer(void)
621 {
622         int i;
623         char line[256];
624         char* line_p = line;
625
626         for (i = 0; i < ft2232_buffer_size; i++)
627         {
628                 line_p += snprintf(line_p, 256 - (line_p - line), "%2.2x ", ft2232_buffer[i]);
629                 if (i % 16 == 15)
630                 {
631                         LOG_DEBUG("%s", line);
632                         line_p = line;
633                 }
634         }
635
636         if (line_p != line)
637                 LOG_DEBUG("%s", line);
638 }
639
640 static int ft2232_send_and_recv(jtag_command_t* first, jtag_command_t* last)
641 {
642         jtag_command_t* cmd;
643         uint8_t* buffer;
644         int scan_size;
645         enum scan_type  type;
646         int retval;
647         uint32_t bytes_written = 0;
648         uint32_t bytes_read = 0;
649
650 #ifdef _DEBUG_USB_IO_
651         struct timeval  start, inter, inter2, end;
652         struct timeval  d_inter, d_inter2, d_end;
653 #endif
654
655 #ifdef _DEBUG_USB_COMMS_
656         LOG_DEBUG("write buffer (size %i):", ft2232_buffer_size);
657         ft2232_debug_dump_buffer();
658 #endif
659
660 #ifdef _DEBUG_USB_IO_
661         gettimeofday(&start, NULL);
662 #endif
663
664         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
665         {
666                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
667                 return retval;
668         }
669
670 #ifdef _DEBUG_USB_IO_
671         gettimeofday(&inter, NULL);
672 #endif
673
674         if (ft2232_expect_read)
675         {
676                 int timeout = 100;
677                 ft2232_buffer_size = 0;
678
679 #ifdef _DEBUG_USB_IO_
680                 gettimeofday(&inter2, NULL);
681 #endif
682
683                 if ((retval = ft2232_read(ft2232_buffer, ft2232_expect_read, &bytes_read)) != ERROR_OK)
684                 {
685                         LOG_ERROR("couldn't read from FT2232");
686                         return retval;
687                 }
688
689 #ifdef _DEBUG_USB_IO_
690                 gettimeofday(&end, NULL);
691
692                 timeval_subtract(&d_inter, &inter, &start);
693                 timeval_subtract(&d_inter2, &inter2, &start);
694                 timeval_subtract(&d_end, &end, &start);
695
696                 LOG_INFO("inter: %u.%06u, inter2: %u.%06u end: %u.%06u",
697                         (unsigned)d_inter.tv_sec, (unsigned)d_inter.tv_usec,
698                         (unsigned)d_inter2.tv_sec, (unsigned)d_inter2.tv_usec,
699                         (unsigned)d_end.tv_sec, (unsigned)d_end.tv_usec);
700 #endif
701
702                 ft2232_buffer_size = bytes_read;
703
704                 if (ft2232_expect_read != ft2232_buffer_size)
705                 {
706                         LOG_ERROR("ft2232_expect_read (%i) != ft2232_buffer_size (%i) (%i retries)", ft2232_expect_read,
707                                         ft2232_buffer_size,
708                                         100 - timeout);
709                         ft2232_debug_dump_buffer();
710
711                         exit(-1);
712                 }
713
714 #ifdef _DEBUG_USB_COMMS_
715                 LOG_DEBUG("read buffer (%i retries): %i bytes", 100 - timeout, ft2232_buffer_size);
716                 ft2232_debug_dump_buffer();
717 #endif
718         }
719
720         ft2232_expect_read  = 0;
721         ft2232_read_pointer = 0;
722
723         /* return ERROR_OK, unless a jtag_read_buffer returns a failed check
724          * that wasn't handled by a caller-provided error handler
725          */
726         retval = ERROR_OK;
727
728         cmd = first;
729         while (cmd != last)
730         {
731                 switch (cmd->type)
732                 {
733                 case JTAG_SCAN:
734                         type = jtag_scan_type(cmd->cmd.scan);
735                         if (type != SCAN_OUT)
736                         {
737                                 scan_size = jtag_scan_size(cmd->cmd.scan);
738                                 buffer    = calloc(CEIL(scan_size, 8), 1);
739                                 ft2232_read_scan(type, buffer, scan_size);
740                                 if (jtag_read_buffer(buffer, cmd->cmd.scan) != ERROR_OK)
741                                         retval = ERROR_JTAG_QUEUE_FAILED;
742                                 free(buffer);
743                         }
744                         break;
745
746                 default:
747                         break;
748                 }
749
750                 cmd = cmd->next;
751         }
752
753         ft2232_buffer_size = 0;
754
755         return retval;
756 }
757
758 /**
759  * Function ft2232_add_pathmove
760  * moves the TAP controller from the current state to a new state through the
761  * given path, where path is an array of tap_state_t's.
762  *
763  * @param path is an array of tap_stat_t which gives the states to traverse through
764  *   ending with the last state at path[num_states-1]
765  * @param num_states is the count of state steps to move through
766  */
767 static void ft2232_add_pathmove(tap_state_t* path, int num_states)
768 {
769         int state_count = 0;
770
771         assert((unsigned) num_states <= 32u);           /* tms_bits only holds 32 bits */
772
773         /* this loop verifies that the path is legal and logs each state in the path */
774         while (num_states)
775         {
776                 unsigned char  tms_byte = 0;       /* zero this on each MPSSE batch */
777
778                 int bit_count = 0;
779
780                 int num_states_batch = num_states > 7 ? 7 : num_states;
781
782                 /* command "Clock Data to TMS/CS Pin (no Read)" */
783                 buffer_write(0x4b);
784
785                 /* number of states remaining */
786                 buffer_write(num_states_batch - 1);
787
788                 while (num_states_batch--)
789                 {
790                   if (tap_state_transition(tap_get_state(), false) == path[state_count])
791                                 buf_set_u32(&tms_byte, bit_count++, 1, 0x0);
792                   else if (tap_state_transition(tap_get_state(), true) == path[state_count])
793                                 buf_set_u32(&tms_byte, bit_count++, 1, 0x1);
794                         else
795                         {
796                                 LOG_ERROR( "BUG: %s -> %s isn't a valid TAP transition", tap_state_name(
797                                                                  tap_get_state() ), tap_state_name(path[state_count]) );
798                                 exit(-1);
799                         }
800
801                   tap_set_state(path[state_count]);
802                         state_count++;
803                         num_states--;
804                 }
805
806                 buffer_write(tms_byte);
807         }       
808         tap_set_end_state(tap_get_state());
809 }
810
811 static void ft2232_add_scan(bool ir_scan, enum scan_type type, uint8_t* buffer, int scan_size)
812 {
813         int num_bytes = (scan_size + 7) / 8;
814         int bits_left = scan_size;
815         int cur_byte  = 0;
816         int last_bit;
817
818         if (!ir_scan)
819         {
820                 if (tap_get_state() != TAP_DRSHIFT)
821                 {
822                         move_to_state(TAP_DRSHIFT);
823                 }
824         }
825         else
826         {
827                 if (tap_get_state() != TAP_IRSHIFT)
828                 {
829                         move_to_state(TAP_IRSHIFT);
830                 }
831         }
832
833         /* add command for complete bytes */
834         while (num_bytes > 1)
835         {
836                 int thisrun_bytes;
837                 if (type == SCAN_IO)
838                 {
839                         /* Clock Data Bytes In and Out LSB First */
840                         buffer_write(0x39);
841                         /* LOG_DEBUG("added TDI bytes (io %i)", num_bytes); */
842                 }
843                 else if (type == SCAN_OUT)
844                 {
845                         /* Clock Data Bytes Out on -ve Clock Edge LSB First (no Read) */
846                         buffer_write(0x19);
847                         /* LOG_DEBUG("added TDI bytes (o)"); */
848                 }
849                 else if (type == SCAN_IN)
850                 {
851                         /* Clock Data Bytes In on +ve Clock Edge LSB First (no Write) */
852                         buffer_write(0x28);
853                         /* LOG_DEBUG("added TDI bytes (i %i)", num_bytes); */
854                 }
855
856                 thisrun_bytes = (num_bytes > 65537) ? 65536 : (num_bytes - 1);
857                 num_bytes    -= thisrun_bytes;
858
859                 buffer_write((uint8_t) (thisrun_bytes - 1));
860                 buffer_write((uint8_t) ((thisrun_bytes - 1) >> 8));
861
862                 if (type != SCAN_IN)
863                 {
864                         /* add complete bytes */
865                         while (thisrun_bytes-- > 0)
866                         {
867                                 buffer_write(buffer[cur_byte++]);
868                                 bits_left -= 8;
869                         }
870                 }
871                 else /* (type == SCAN_IN) */
872                 {
873                         bits_left -= 8 * (thisrun_bytes);
874                 }
875         }
876
877         /* the most signifcant bit is scanned during TAP movement */
878         if (type != SCAN_IN)
879                 last_bit = (buffer[cur_byte] >> (bits_left - 1)) & 0x1;
880         else
881                 last_bit = 0;
882
883         /* process remaining bits but the last one */
884         if (bits_left > 1)
885         {
886                 if (type == SCAN_IO)
887                 {
888                         /* Clock Data Bits In and Out LSB First */
889                         buffer_write(0x3b);
890                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
891                 }
892                 else if (type == SCAN_OUT)
893                 {
894                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
895                         buffer_write(0x1b);
896                         /* LOG_DEBUG("added TDI bits (o)"); */
897                 }
898                 else if (type == SCAN_IN)
899                 {
900                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
901                         buffer_write(0x2a);
902                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
903                 }
904
905                 buffer_write(bits_left - 2);
906                 if (type != SCAN_IN)
907                         buffer_write(buffer[cur_byte]);
908         }
909
910         if ((ir_scan && (tap_get_end_state() == TAP_IRSHIFT))
911           || (!ir_scan && (tap_get_end_state() == TAP_DRSHIFT)))
912         {
913                 if (type == SCAN_IO)
914                 {
915                         /* Clock Data Bits In and Out LSB First */
916                         buffer_write(0x3b);
917                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
918                 }
919                 else if (type == SCAN_OUT)
920                 {
921                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
922                         buffer_write(0x1b);
923                         /* LOG_DEBUG("added TDI bits (o)"); */
924                 }
925                 else if (type == SCAN_IN)
926                 {
927                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
928                         buffer_write(0x2a);
929                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
930                 }
931                 buffer_write(0x0);
932                 buffer_write(last_bit);
933         }
934         else
935         {
936                 int tms_bits;
937                 int tms_count;
938                 uint8_t mpsse_cmd;
939
940                 /* move from Shift-IR/DR to end state */
941                 if (type != SCAN_OUT)
942                 {
943                         /* We always go to the PAUSE state in two step at the end of an IN or IO scan */
944                         /* This must be coordinated with the bit shifts in ft2232_read_scan    */
945                         tms_bits  = 0x01;
946                         tms_count = 2;
947                         /* Clock Data to TMS/CS Pin with Read */
948                         mpsse_cmd = 0x6b;
949                         /* LOG_DEBUG("added TMS scan (read)"); */
950                 }
951                 else
952                 {
953                         tms_bits  = tap_get_tms_path(tap_get_state(), tap_get_end_state());
954                         tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
955                         /* Clock Data to TMS/CS Pin (no Read) */
956                         mpsse_cmd = 0x4b;
957                         /* LOG_DEBUG("added TMS scan (no read)"); */
958                 }
959
960                 clock_tms(mpsse_cmd, tms_bits, tms_count, last_bit);
961         }
962
963         if (tap_get_state() != tap_get_end_state())
964         {
965                 move_to_state(tap_get_end_state());
966         }
967 }
968
969 static int ft2232_large_scan(scan_command_t* cmd, enum scan_type type, uint8_t* buffer, int scan_size)
970 {
971         int num_bytes = (scan_size + 7) / 8;
972         int bits_left = scan_size;
973         int cur_byte  = 0;
974         int last_bit;
975         uint8_t* receive_buffer  = malloc(CEIL(scan_size, 8));
976         uint8_t* receive_pointer = receive_buffer;
977         uint32_t bytes_written;
978         uint32_t bytes_read;
979         int retval;
980         int thisrun_read = 0;
981
982         if (cmd->ir_scan)
983         {
984                 LOG_ERROR("BUG: large IR scans are not supported");
985                 exit(-1);
986         }
987
988         if (tap_get_state() != TAP_DRSHIFT)
989         {
990                 move_to_state(TAP_DRSHIFT);
991         }
992
993         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
994         {
995                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
996                 exit(-1);
997         }
998         LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
999                   ft2232_buffer_size, (int)bytes_written);
1000         ft2232_buffer_size = 0;
1001
1002         /* add command for complete bytes */
1003         while (num_bytes > 1)
1004         {
1005                 int thisrun_bytes;
1006
1007                 if (type == SCAN_IO)
1008                 {
1009                         /* Clock Data Bytes In and Out LSB First */
1010                         buffer_write(0x39);
1011                         /* LOG_DEBUG("added TDI bytes (io %i)", num_bytes); */
1012                 }
1013                 else if (type == SCAN_OUT)
1014                 {
1015                         /* Clock Data Bytes Out on -ve Clock Edge LSB First (no Read) */
1016                         buffer_write(0x19);
1017                         /* LOG_DEBUG("added TDI bytes (o)"); */
1018                 }
1019                 else if (type == SCAN_IN)
1020                 {
1021                         /* Clock Data Bytes In on +ve Clock Edge LSB First (no Write) */
1022                         buffer_write(0x28);
1023                         /* LOG_DEBUG("added TDI bytes (i %i)", num_bytes); */
1024                 }
1025
1026                 thisrun_bytes = (num_bytes > 65537) ? 65536 : (num_bytes - 1);
1027                 thisrun_read  = thisrun_bytes;
1028                 num_bytes    -= thisrun_bytes;
1029                 buffer_write((uint8_t) (thisrun_bytes - 1));
1030                 buffer_write((uint8_t) ((thisrun_bytes - 1) >> 8));
1031
1032                 if (type != SCAN_IN)
1033                 {
1034                         /* add complete bytes */
1035                         while (thisrun_bytes-- > 0)
1036                         {
1037                                 buffer_write(buffer[cur_byte]);
1038                                 cur_byte++;
1039                                 bits_left -= 8;
1040                         }
1041                 }
1042                 else /* (type == SCAN_IN) */
1043                 {
1044                         bits_left -= 8 * (thisrun_bytes);
1045                 }
1046
1047                 if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1048                 {
1049                         LOG_ERROR("couldn't write MPSSE commands to FT2232");
1050                         exit(-1);
1051                 }
1052                 LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1053                           ft2232_buffer_size,
1054                           (int)bytes_written);
1055                 ft2232_buffer_size = 0;
1056
1057                 if (type != SCAN_OUT)
1058                 {
1059                         if ((retval = ft2232_read(receive_pointer, thisrun_read, &bytes_read)) != ERROR_OK)
1060                         {
1061                                 LOG_ERROR("couldn't read from FT2232");
1062                                 exit(-1);
1063                         }
1064                         LOG_DEBUG("thisrun_read: %i, bytes_read: %i",
1065                                   thisrun_read,
1066                                   (int)bytes_read);
1067                         receive_pointer += bytes_read;
1068                 }
1069         }
1070
1071         thisrun_read = 0;
1072
1073         /* the most signifcant bit is scanned during TAP movement */
1074         if (type != SCAN_IN)
1075                 last_bit = (buffer[cur_byte] >> (bits_left - 1)) & 0x1;
1076         else
1077                 last_bit = 0;
1078
1079         /* process remaining bits but the last one */
1080         if (bits_left > 1)
1081         {
1082                 if (type == SCAN_IO)
1083                 {
1084                         /* Clock Data Bits In and Out LSB First */
1085                         buffer_write(0x3b);
1086                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
1087                 }
1088                 else if (type == SCAN_OUT)
1089                 {
1090                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
1091                         buffer_write(0x1b);
1092                         /* LOG_DEBUG("added TDI bits (o)"); */
1093                 }
1094                 else if (type == SCAN_IN)
1095                 {
1096                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
1097                         buffer_write(0x2a);
1098                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
1099                 }
1100                 buffer_write(bits_left - 2);
1101                 if (type != SCAN_IN)
1102                         buffer_write(buffer[cur_byte]);
1103
1104                 if (type != SCAN_OUT)
1105                         thisrun_read += 2;
1106         }
1107
1108         if (tap_get_end_state() == TAP_DRSHIFT)
1109         {
1110                 if (type == SCAN_IO)
1111                 {
1112                         /* Clock Data Bits In and Out LSB First */
1113                         buffer_write(0x3b);
1114                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
1115                 }
1116                 else if (type == SCAN_OUT)
1117                 {
1118                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
1119                         buffer_write(0x1b);
1120                         /* LOG_DEBUG("added TDI bits (o)"); */
1121                 }
1122                 else if (type == SCAN_IN)
1123                 {
1124                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
1125                         buffer_write(0x2a);
1126                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
1127                 }
1128                 buffer_write(0x0);
1129                 buffer_write(last_bit);
1130         }
1131         else
1132         {
1133                 int tms_bits  = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1134                 int tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1135                 uint8_t mpsse_cmd;
1136
1137                 /* move from Shift-IR/DR to end state */
1138                 if (type != SCAN_OUT)
1139                 {
1140                         /* Clock Data to TMS/CS Pin with Read */
1141                         mpsse_cmd = 0x6b;
1142                         /* LOG_DEBUG("added TMS scan (read)"); */
1143                 }
1144                 else
1145                 {
1146                         /* Clock Data to TMS/CS Pin (no Read) */
1147                         mpsse_cmd = 0x4b;
1148                         /* LOG_DEBUG("added TMS scan (no read)"); */
1149                 }
1150
1151                 clock_tms(mpsse_cmd, tms_bits, tms_count, last_bit);
1152         }
1153
1154         if (type != SCAN_OUT)
1155                 thisrun_read += 1;
1156
1157         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1158         {
1159                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
1160                 exit(-1);
1161         }
1162         LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1163                   ft2232_buffer_size,
1164                   (int)bytes_written);
1165         ft2232_buffer_size = 0;
1166
1167         if (type != SCAN_OUT)
1168         {
1169                 if ((retval = ft2232_read(receive_pointer, thisrun_read, &bytes_read)) != ERROR_OK)
1170                 {
1171                         LOG_ERROR("couldn't read from FT2232");
1172                         exit(-1);
1173                 }
1174                 LOG_DEBUG("thisrun_read: %i, bytes_read: %i",
1175                           thisrun_read,
1176                           (int)bytes_read);
1177                 receive_pointer += bytes_read;
1178         }
1179
1180         return ERROR_OK;
1181 }
1182
1183 static int ft2232_predict_scan_out(int scan_size, enum scan_type type)
1184 {
1185         int predicted_size = 3;
1186         int num_bytes = (scan_size - 1) / 8;
1187
1188         if (tap_get_state() != TAP_DRSHIFT)
1189                 predicted_size += get_tms_buffer_requirements(tap_get_tms_path_len(tap_get_state(), TAP_DRSHIFT));
1190
1191         if (type == SCAN_IN)    /* only from device to host */
1192         {
1193                 /* complete bytes */
1194                 predicted_size += CEIL(num_bytes, 65536) * 3;
1195
1196                 /* remaining bits - 1 (up to 7) */
1197                 predicted_size += ((scan_size - 1) % 8) ? 2 : 0;
1198         }
1199         else    /* host to device, or bidirectional */
1200         {
1201                 /* complete bytes */
1202                 predicted_size += num_bytes + CEIL(num_bytes, 65536) * 3;
1203
1204                 /* remaining bits -1 (up to 7) */
1205                 predicted_size += ((scan_size - 1) % 8) ? 3 : 0;
1206         }
1207
1208         return predicted_size;
1209 }
1210
1211 static int ft2232_predict_scan_in(int scan_size, enum scan_type type)
1212 {
1213         int predicted_size = 0;
1214
1215         if (type != SCAN_OUT)
1216         {
1217                 /* complete bytes */
1218                 predicted_size += (CEIL(scan_size, 8) > 1) ? (CEIL(scan_size, 8) - 1) : 0;
1219
1220                 /* remaining bits - 1 */
1221                 predicted_size += ((scan_size - 1) % 8) ? 1 : 0;
1222
1223                 /* last bit (from TMS scan) */
1224                 predicted_size += 1;
1225         }
1226
1227         /* LOG_DEBUG("scan_size: %i, predicted_size: %i", scan_size, predicted_size); */
1228
1229         return predicted_size;
1230 }
1231
1232 static void usbjtag_reset(int trst, int srst)
1233 {
1234         enum reset_types jtag_reset_config = jtag_get_reset_config();
1235         if (trst == 1)
1236         {
1237                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1238                         low_direction |= nTRSTnOE;      /* switch to output pin (output is low) */
1239                 else
1240                         low_output &= ~nTRST;           /* switch output low */
1241         }
1242         else if (trst == 0)
1243         {
1244                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1245                         low_direction &= ~nTRSTnOE;     /* switch to input pin (high-Z + internal and external pullup) */
1246                 else
1247                         low_output |= nTRST;            /* switch output high */
1248         }
1249
1250         if (srst == 1)
1251         {
1252                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1253                         low_output &= ~nSRST;           /* switch output low */
1254                 else
1255                         low_direction |= nSRSTnOE;      /* switch to output pin (output is low) */
1256         }
1257         else if (srst == 0)
1258         {
1259                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1260                         low_output |= nSRST;            /* switch output high */
1261                 else
1262                         low_direction &= ~nSRSTnOE;     /* switch to input pin (high-Z) */
1263         }
1264
1265         /* command "set data bits low byte" */
1266         buffer_write(0x80);
1267         buffer_write(low_output);
1268         buffer_write(low_direction);
1269 }
1270
1271 static void jtagkey_reset(int trst, int srst)
1272 {
1273         enum reset_types jtag_reset_config = jtag_get_reset_config();
1274         if (trst == 1)
1275         {
1276                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1277                         high_output &= ~nTRSTnOE;
1278                 else
1279                         high_output &= ~nTRST;
1280         }
1281         else if (trst == 0)
1282         {
1283                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1284                         high_output |= nTRSTnOE;
1285                 else
1286                         high_output |= nTRST;
1287         }
1288
1289         if (srst == 1)
1290         {
1291                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1292                         high_output &= ~nSRST;
1293                 else
1294                         high_output &= ~nSRSTnOE;
1295         }
1296         else if (srst == 0)
1297         {
1298                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1299                         high_output |= nSRST;
1300                 else
1301                         high_output |= nSRSTnOE;
1302         }
1303
1304         /* command "set data bits high byte" */
1305         buffer_write(0x82);
1306         buffer_write(high_output);
1307         buffer_write(high_direction);
1308         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1309                         high_direction);
1310 }
1311
1312 static void olimex_jtag_reset(int trst, int srst)
1313 {
1314         enum reset_types jtag_reset_config = jtag_get_reset_config();
1315         if (trst == 1)
1316         {
1317                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1318                         high_output &= ~nTRSTnOE;
1319                 else
1320                         high_output &= ~nTRST;
1321         }
1322         else if (trst == 0)
1323         {
1324                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1325                         high_output |= nTRSTnOE;
1326                 else
1327                         high_output |= nTRST;
1328         }
1329
1330         if (srst == 1)
1331         {
1332                 high_output |= nSRST;
1333         }
1334         else if (srst == 0)
1335         {
1336                 high_output &= ~nSRST;
1337         }
1338
1339         /* command "set data bits high byte" */
1340         buffer_write(0x82);
1341         buffer_write(high_output);
1342         buffer_write(high_direction);
1343         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1344                         high_direction);
1345 }
1346
1347 static void axm0432_jtag_reset(int trst, int srst)
1348 {
1349         if (trst == 1)
1350         {
1351                 tap_set_state(TAP_RESET);
1352                 high_output &= ~nTRST;
1353         }
1354         else if (trst == 0)
1355         {
1356                 high_output |= nTRST;
1357         }
1358
1359         if (srst == 1)
1360         {
1361                 high_output &= ~nSRST;
1362         }
1363         else if (srst == 0)
1364         {
1365                 high_output |= nSRST;
1366         }
1367
1368         /* command "set data bits low byte" */
1369         buffer_write(0x82);
1370         buffer_write(high_output);
1371         buffer_write(high_direction);
1372         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1373                         high_direction);
1374 }
1375
1376 static void flyswatter_reset(int trst, int srst)
1377 {
1378         if (trst == 1)
1379         {
1380                 low_output &= ~nTRST;
1381         }
1382         else if (trst == 0)
1383         {
1384                 low_output |= nTRST;
1385         }
1386
1387         if (srst == 1)
1388         {
1389                 low_output |= nSRST;
1390         }
1391         else if (srst == 0)
1392         {
1393                 low_output &= ~nSRST;
1394         }
1395
1396         /* command "set data bits low byte" */
1397         buffer_write(0x80);
1398         buffer_write(low_output);
1399         buffer_write(low_direction);
1400         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
1401 }
1402
1403 static void turtle_reset(int trst, int srst)
1404 {
1405         trst = trst;
1406
1407         if (srst == 1)
1408         {
1409                 low_output |= nSRST;
1410         }
1411         else if (srst == 0)
1412         {
1413                 low_output &= ~nSRST;
1414         }
1415
1416         /* command "set data bits low byte" */
1417         buffer_write(0x80);
1418         buffer_write(low_output);
1419         buffer_write(low_direction);
1420         LOG_DEBUG("srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", srst, low_output, low_direction);
1421 }
1422
1423 static void comstick_reset(int trst, int srst)
1424 {
1425         if (trst == 1)
1426         {
1427                 high_output &= ~nTRST;
1428         }
1429         else if (trst == 0)
1430         {
1431                 high_output |= nTRST;
1432         }
1433
1434         if (srst == 1)
1435         {
1436                 high_output &= ~nSRST;
1437         }
1438         else if (srst == 0)
1439         {
1440                 high_output |= nSRST;
1441         }
1442
1443         /* command "set data bits high byte" */
1444         buffer_write(0x82);
1445         buffer_write(high_output);
1446         buffer_write(high_direction);
1447         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1448                         high_direction);
1449 }
1450
1451 static void stm32stick_reset(int trst, int srst)
1452 {
1453         if (trst == 1)
1454         {
1455                 high_output &= ~nTRST;
1456         }
1457         else if (trst == 0)
1458         {
1459                 high_output |= nTRST;
1460         }
1461
1462         if (srst == 1)
1463         {
1464                 low_output &= ~nSRST;
1465         }
1466         else if (srst == 0)
1467         {
1468                 low_output |= nSRST;
1469         }
1470
1471         /* command "set data bits low byte" */
1472         buffer_write(0x80);
1473         buffer_write(low_output);
1474         buffer_write(low_direction);
1475
1476         /* command "set data bits high byte" */
1477         buffer_write(0x82);
1478         buffer_write(high_output);
1479         buffer_write(high_direction);
1480         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1481                         high_direction);
1482 }
1483
1484 static void sheevaplug_reset(int trst, int srst)
1485 {
1486         if (trst == 1)
1487                 high_output &= ~nTRST;
1488         else if (trst == 0)
1489                 high_output |= nTRST;
1490
1491         if (srst == 1)
1492                 high_output &= ~nSRSTnOE;
1493         else if (srst == 0)
1494                 high_output |= nSRSTnOE;
1495
1496         /* command "set data bits high byte" */
1497         buffer_write(0x82);
1498         buffer_write(high_output);
1499         buffer_write(high_direction);
1500         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output, high_direction);
1501 }
1502
1503 static int ft2232_execute_runtest(jtag_command_t *cmd)
1504 {
1505         int retval;
1506         int i;
1507         int predicted_size = 0;
1508         retval = ERROR_OK;
1509
1510         DEBUG_JTAG_IO("runtest %i cycles, end in %s",
1511                         cmd->cmd.runtest->num_cycles,
1512                         tap_state_name(cmd->cmd.runtest->end_state));
1513
1514         /* only send the maximum buffer size that FT2232C can handle */
1515         predicted_size = 0;
1516         if (tap_get_state() != TAP_IDLE)
1517                 predicted_size += 3;
1518         predicted_size += 3 * CEIL(cmd->cmd.runtest->num_cycles, 7);
1519         if (cmd->cmd.runtest->end_state != TAP_IDLE)
1520                 predicted_size += 3;
1521         if (tap_get_end_state() != TAP_IDLE)
1522                 predicted_size += 3;
1523         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1524         {
1525                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1526                         retval = ERROR_JTAG_QUEUE_FAILED;
1527                 require_send = 0;
1528                 first_unsent = cmd;
1529         }
1530         if (tap_get_state() != TAP_IDLE)
1531         {
1532                 move_to_state(TAP_IDLE);
1533                 require_send = 1;
1534         }
1535         i = cmd->cmd.runtest->num_cycles;
1536         while (i > 0)
1537         {
1538                 /* there are no state transitions in this code, so omit state tracking */
1539
1540                 /* command "Clock Data to TMS/CS Pin (no Read)" */
1541                 buffer_write(0x4b);
1542
1543                 /* scan 7 bits */
1544                 buffer_write((i > 7) ? 6 : (i - 1));
1545
1546                 /* TMS data bits */
1547                 buffer_write(0x0);
1548                 tap_set_state(TAP_IDLE);
1549
1550                 i -= (i > 7) ? 7 : i;
1551                 /* LOG_DEBUG("added TMS scan (no read)"); */
1552         }
1553
1554         ft2232_end_state(cmd->cmd.runtest->end_state);
1555
1556         if (tap_get_state() != tap_get_end_state())
1557         {
1558                 move_to_state(tap_get_end_state());
1559         }
1560
1561         require_send = 1;
1562 #ifdef _DEBUG_JTAG_IO_
1563         LOG_DEBUG("runtest: %i, end in %s", cmd->cmd.runtest->num_cycles, tap_state_name(tap_get_end_state()));
1564 #endif
1565
1566         return retval;
1567 }
1568
1569 static int ft2232_execute_statemove(jtag_command_t *cmd)
1570 {
1571         int     predicted_size = 0;
1572         int     retval = ERROR_OK;
1573
1574         DEBUG_JTAG_IO("statemove end in %i", cmd->cmd.statemove->end_state);
1575
1576         /* only send the maximum buffer size that FT2232C can handle */
1577         predicted_size = 3;
1578         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1579         {
1580                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1581                         retval = ERROR_JTAG_QUEUE_FAILED;
1582                 require_send = 0;
1583                 first_unsent = cmd;
1584         }
1585         ft2232_end_state(cmd->cmd.statemove->end_state);
1586
1587         /* move to end state */
1588         if (tap_get_state() != tap_get_end_state())
1589         {
1590                 move_to_state(tap_get_end_state());
1591                 require_send = 1;
1592         }
1593
1594         return retval;
1595 }
1596
1597 static int ft2232_execute_pathmove(jtag_command_t *cmd)
1598 {
1599         int     predicted_size = 0;
1600         int     retval = ERROR_OK;
1601
1602         tap_state_t*     path = cmd->cmd.pathmove->path;
1603         int     num_states    = cmd->cmd.pathmove->num_states;
1604
1605         DEBUG_JTAG_IO("pathmove: %i states, current: %s  end: %s", num_states,
1606                         tap_state_name(tap_get_state()),
1607                         tap_state_name(path[num_states-1]));
1608
1609         /* only send the maximum buffer size that FT2232C can handle */
1610         predicted_size = 3 * CEIL(num_states, 7);
1611         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1612         {
1613                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1614                         retval = ERROR_JTAG_QUEUE_FAILED;
1615
1616                 require_send = 0;
1617                 first_unsent = cmd;
1618         }
1619
1620         ft2232_add_pathmove(path, num_states);
1621         require_send = 1;
1622
1623         return retval;
1624 }
1625
1626 static int ft2232_execute_scan(jtag_command_t *cmd)
1627 {
1628         uint8_t* buffer;
1629         int scan_size;                          /* size of IR or DR scan */
1630         int predicted_size = 0;
1631         int retval = ERROR_OK;
1632
1633         enum scan_type  type = jtag_scan_type(cmd->cmd.scan);
1634
1635         DEBUG_JTAG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN", type);
1636
1637         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
1638
1639         predicted_size = ft2232_predict_scan_out(scan_size, type);
1640         if ((predicted_size + 1) > FT2232_BUFFER_SIZE)
1641         {
1642                 LOG_DEBUG("oversized ft2232 scan (predicted_size > FT2232_BUFFER_SIZE)");
1643                 /* unsent commands before this */
1644                 if (first_unsent != cmd)
1645                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1646                                 retval = ERROR_JTAG_QUEUE_FAILED;
1647
1648                 /* current command */
1649                 ft2232_end_state(cmd->cmd.scan->end_state);
1650                 ft2232_large_scan(cmd->cmd.scan, type, buffer, scan_size);
1651                 require_send = 0;
1652                 first_unsent = cmd->next;
1653                 if (buffer)
1654                         free(buffer);
1655                 return retval;
1656         }
1657         else if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1658         {
1659                 LOG_DEBUG("ft2232 buffer size reached, sending queued commands (first_unsent: %p, cmd: %p)",
1660                                 first_unsent,
1661                                 cmd);
1662                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1663                         retval = ERROR_JTAG_QUEUE_FAILED;
1664                 require_send = 0;
1665                 first_unsent = cmd;
1666         }
1667         ft2232_expect_read += ft2232_predict_scan_in(scan_size, type);
1668         /* LOG_DEBUG("new read size: %i", ft2232_expect_read); */
1669         ft2232_end_state(cmd->cmd.scan->end_state);
1670         ft2232_add_scan(cmd->cmd.scan->ir_scan, type, buffer, scan_size);
1671         require_send = 1;
1672         if (buffer)
1673                 free(buffer);
1674 #ifdef _DEBUG_JTAG_IO_
1675         LOG_DEBUG("%s scan, %i bits, end in %s", (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1676                         tap_state_name(tap_get_end_state()));
1677 #endif
1678         return retval;
1679
1680 }
1681
1682 static int ft2232_execute_reset(jtag_command_t *cmd)
1683 {
1684         int retval;
1685         int predicted_size = 0;
1686         retval = ERROR_OK;
1687
1688         DEBUG_JTAG_IO("reset trst: %i srst %i",
1689                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1690
1691         /* only send the maximum buffer size that FT2232C can handle */
1692         predicted_size = 3;
1693         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1694         {
1695                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1696                         retval = ERROR_JTAG_QUEUE_FAILED;
1697                 require_send = 0;
1698                 first_unsent = cmd;
1699         }
1700
1701         layout->reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1702         require_send = 1;
1703
1704 #ifdef _DEBUG_JTAG_IO_
1705         LOG_DEBUG("trst: %i, srst: %i", cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1706 #endif
1707         return retval;
1708 }
1709
1710 static int ft2232_execute_sleep(jtag_command_t *cmd)
1711 {
1712         int retval;
1713         retval = ERROR_OK;
1714
1715         DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
1716
1717         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1718                                 retval = ERROR_JTAG_QUEUE_FAILED;
1719         first_unsent = cmd->next;
1720         jtag_sleep(cmd->cmd.sleep->us);
1721 #ifdef _DEBUG_JTAG_IO_
1722                         LOG_DEBUG("sleep %i usec while in %s", cmd->cmd.sleep->us, tap_state_name(tap_get_state()));
1723 #endif
1724
1725         return retval;
1726 }
1727
1728 static int ft2232_execute_stableclocks(jtag_command_t *cmd)
1729 {
1730         int retval;
1731         retval = ERROR_OK;
1732
1733         /* this is only allowed while in a stable state.  A check for a stable
1734          * state was done in jtag_add_clocks()
1735          */
1736         if (ft2232_stableclocks(cmd->cmd.stableclocks->num_cycles, cmd) != ERROR_OK)
1737                 retval = ERROR_JTAG_QUEUE_FAILED;
1738 #ifdef _DEBUG_JTAG_IO_
1739         LOG_DEBUG("clocks %i while in %s", cmd->cmd.stableclocks->num_cycles, tap_state_name(tap_get_state()));
1740 #endif
1741
1742         return retval;
1743 }
1744
1745 static int ft2232_execute_command(jtag_command_t *cmd)
1746 {
1747         int retval;
1748         retval = ERROR_OK;
1749
1750         switch (cmd->type)
1751         {
1752         case JTAG_RESET:        retval = ft2232_execute_reset(cmd); break;
1753         case JTAG_RUNTEST:      retval = ft2232_execute_runtest(cmd); break;
1754         case JTAG_STATEMOVE: retval = ft2232_execute_statemove(cmd); break;
1755         case JTAG_PATHMOVE:     retval = ft2232_execute_pathmove(cmd); break;
1756         case JTAG_SCAN:         retval = ft2232_execute_scan(cmd); break;
1757         case JTAG_SLEEP:        retval = ft2232_execute_sleep(cmd); break;
1758         case JTAG_STABLECLOCKS: retval = ft2232_execute_stableclocks(cmd); break;
1759         default:
1760                 LOG_ERROR("BUG: unknown JTAG command type encountered");
1761                 exit(-1);
1762         }
1763         return retval;
1764 }
1765
1766 static int ft2232_execute_queue()
1767 {
1768         jtag_command_t* cmd = jtag_command_queue;       /* currently processed command */
1769         int retval;
1770
1771         first_unsent = cmd;             /* next command that has to be sent */
1772         require_send = 0;
1773
1774         /* return ERROR_OK, unless ft2232_send_and_recv reports a failed check
1775          * that wasn't handled by a caller-provided error handler
1776          */
1777         retval = ERROR_OK;
1778
1779         ft2232_buffer_size = 0;
1780         ft2232_expect_read = 0;
1781
1782         /* blink, if the current layout has that feature */
1783         if (layout->blink)
1784                 layout->blink();
1785
1786         while (cmd)
1787         {
1788                 if (ft2232_execute_command(cmd) != ERROR_OK)
1789                         retval = ERROR_JTAG_QUEUE_FAILED;
1790                 /* Start reading input before FT2232 TX buffer fills up */
1791                 cmd = cmd->next;
1792                 if (ft2232_expect_read > 256)
1793                 {
1794                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1795                                 retval = ERROR_JTAG_QUEUE_FAILED;
1796                         first_unsent = cmd;
1797                 }
1798         }
1799
1800         if (require_send > 0)
1801                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1802                         retval = ERROR_JTAG_QUEUE_FAILED;
1803
1804         return retval;
1805 }
1806
1807 #if BUILD_FT2232_FTD2XX == 1
1808 static int ft2232_init_ftd2xx(uint16_t vid, uint16_t pid, int more, int* try_more)
1809 {
1810         FT_STATUS       status;
1811         DWORD           deviceID;
1812         char            SerialNumber[16];
1813         char            Description[64];
1814         DWORD   openex_flags  = 0;
1815         char*   openex_string = NULL;
1816         uint8_t latency_timer;
1817
1818         LOG_DEBUG("'ft2232' interface using FTD2XX with '%s' layout (%4.4x:%4.4x)", ft2232_layout, vid, pid);
1819
1820 #if IS_WIN32 == 0
1821         /* Add non-standard Vid/Pid to the linux driver */
1822         if ((status = FT_SetVIDPID(vid, pid)) != FT_OK)
1823         {
1824                 LOG_WARNING("couldn't add %4.4x:%4.4x", vid, pid);
1825         }
1826 #endif
1827
1828         if (ft2232_device_desc && ft2232_serial)
1829         {
1830                 LOG_WARNING("can't open by device description and serial number, giving precedence to serial");
1831                 ft2232_device_desc = NULL;
1832         }
1833
1834         if (ft2232_device_desc)
1835         {
1836                 openex_string = ft2232_device_desc;
1837                 openex_flags  = FT_OPEN_BY_DESCRIPTION;
1838         }
1839         else if (ft2232_serial)
1840         {
1841                 openex_string = ft2232_serial;
1842                 openex_flags  = FT_OPEN_BY_SERIAL_NUMBER;
1843         }
1844         else
1845         {
1846                 LOG_ERROR("neither device description nor serial number specified");
1847                 LOG_ERROR("please add \"ft2232_device_desc <string>\" or \"ft2232_serial <string>\" to your .cfg file");
1848
1849                 return ERROR_JTAG_INIT_FAILED;
1850         }
1851
1852         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
1853         if (status != FT_OK) {
1854                 /* under Win32, the FTD2XX driver appends an "A" to the end
1855                  * of the description, if we tried by the desc, then
1856                  * try by the alternate "A" description. */
1857                 if (openex_string == ft2232_device_desc) {
1858                         /* Try the alternate method. */
1859                         openex_string = ft2232_device_desc_A;
1860                         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
1861                         if (status == FT_OK) {
1862                                 /* yea, the "alternate" method worked! */
1863                         } else {
1864                                 /* drat, give the user a meaningfull message.
1865                                  * telling the use we tried *BOTH* methods. */
1866                                 LOG_WARNING("Unable to open FTDI Device tried: '%s' and '%s'\n",
1867                                                         ft2232_device_desc,
1868                                                         ft2232_device_desc_A);
1869                         }
1870                 }
1871         }
1872
1873         if (status != FT_OK)
1874         {
1875                 DWORD num_devices;
1876
1877                 if (more)
1878                 {
1879                         LOG_WARNING("unable to open ftdi device (trying more): %lu", status);
1880                         *try_more = 1;
1881                         return ERROR_JTAG_INIT_FAILED;
1882                 }
1883                 LOG_ERROR("unable to open ftdi device: %lu", status);
1884                 status = FT_ListDevices(&num_devices, NULL, FT_LIST_NUMBER_ONLY);
1885                 if (status == FT_OK)
1886                 {
1887                         char** desc_array = malloc(sizeof(char*) * (num_devices + 1));
1888                         uint32_t i;
1889
1890                         for (i = 0; i < num_devices; i++)
1891                                 desc_array[i] = malloc(64);
1892
1893                         desc_array[num_devices] = NULL;
1894
1895                         status = FT_ListDevices(desc_array, &num_devices, FT_LIST_ALL | openex_flags);
1896
1897                         if (status == FT_OK)
1898                         {
1899                                 LOG_ERROR("ListDevices: %lu\n", num_devices);
1900                                 for (i = 0; i < num_devices; i++)
1901                                         LOG_ERROR("%" PRIu32 ": \"%s\"", i, desc_array[i]);
1902                         }
1903
1904                         for (i = 0; i < num_devices; i++)
1905                                 free(desc_array[i]);
1906
1907                         free(desc_array);
1908                 }
1909                 else
1910                 {
1911                         LOG_ERROR("ListDevices: NONE\n");
1912                 }
1913                 return ERROR_JTAG_INIT_FAILED;
1914         }
1915
1916         if ((status = FT_SetLatencyTimer(ftdih, ft2232_latency)) != FT_OK)
1917         {
1918                 LOG_ERROR("unable to set latency timer: %lu", status);
1919                 return ERROR_JTAG_INIT_FAILED;
1920         }
1921
1922         if ((status = FT_GetLatencyTimer(ftdih, &latency_timer)) != FT_OK)
1923         {
1924                 LOG_ERROR("unable to get latency timer: %lu", status);
1925                 return ERROR_JTAG_INIT_FAILED;
1926         }
1927         else
1928         {
1929                 LOG_DEBUG("current latency timer: %i", latency_timer);
1930         }
1931
1932         if ((status = FT_SetTimeouts(ftdih, 5000, 5000)) != FT_OK)
1933         {
1934                 LOG_ERROR("unable to set timeouts: %lu", status);
1935                 return ERROR_JTAG_INIT_FAILED;
1936         }
1937
1938         if ((status = FT_SetBitMode(ftdih, 0x0b, 2)) != FT_OK)
1939         {
1940                 LOG_ERROR("unable to enable bit i/o mode: %lu", status);
1941                 return ERROR_JTAG_INIT_FAILED;
1942         }
1943
1944         if ((status = FT_GetDeviceInfo(ftdih, &ftdi_device, &deviceID, SerialNumber, Description, NULL)) != FT_OK)
1945         {
1946                 LOG_ERROR("unable to get FT_GetDeviceInfo: %lu", status);
1947                 return ERROR_JTAG_INIT_FAILED;
1948         }
1949         else
1950         {
1951                 static const char* type_str[] =
1952                         {"BM", "AM", "100AX", "UNKNOWN", "2232C", "232R", "2232H", "4232H"};
1953                 unsigned no_of_known_types = sizeof(type_str) / sizeof(type_str[0]) - 1;
1954                 unsigned type_index = ((unsigned)ftdi_device <= no_of_known_types)
1955                         ? ftdi_device : FT_DEVICE_UNKNOWN;
1956                 LOG_INFO("device: %lu \"%s\"", ftdi_device, type_str[type_index]);
1957                 LOG_INFO("deviceID: %lu", deviceID);
1958                 LOG_INFO("SerialNumber: %s", SerialNumber);
1959                 LOG_INFO("Description: %s", Description);
1960         }
1961
1962         return ERROR_OK;
1963 }
1964
1965 static int ft2232_purge_ftd2xx(void)
1966 {
1967         FT_STATUS status;
1968
1969         if ((status = FT_Purge(ftdih, FT_PURGE_RX | FT_PURGE_TX)) != FT_OK)
1970         {
1971                 LOG_ERROR("error purging ftd2xx device: %lu", status);
1972                 return ERROR_JTAG_INIT_FAILED;
1973         }
1974
1975         return ERROR_OK;
1976 }
1977
1978 #endif /* BUILD_FT2232_FTD2XX == 1 */
1979
1980 #if BUILD_FT2232_LIBFTDI == 1
1981 static int ft2232_init_libftdi(uint16_t vid, uint16_t pid, int more, int* try_more)
1982 {
1983         uint8_t latency_timer;
1984
1985         LOG_DEBUG("'ft2232' interface using libftdi with '%s' layout (%4.4x:%4.4x)",
1986                         ft2232_layout, vid, pid);
1987
1988         if (ftdi_init(&ftdic) < 0)
1989                 return ERROR_JTAG_INIT_FAILED;
1990
1991         if (ftdi_set_interface(&ftdic, INTERFACE_A) < 0)
1992         {
1993                 LOG_ERROR("unable to select FT2232 channel A: %s", ftdic.error_str);
1994                 return ERROR_JTAG_INIT_FAILED;
1995         }
1996
1997         /* context, vendor id, product id */
1998         if (ftdi_usb_open_desc(&ftdic, vid, pid, ft2232_device_desc,
1999                                 ft2232_serial) < 0)
2000         {
2001                 if (more)
2002                         LOG_WARNING("unable to open ftdi device (trying more): %s",
2003                                         ftdic.error_str);
2004                 else
2005                         LOG_ERROR("unable to open ftdi device: %s", ftdic.error_str);
2006                 *try_more = 1;
2007                 return ERROR_JTAG_INIT_FAILED;
2008         }
2009
2010         /* There is already a reset in ftdi_usb_open_desc, this should be redundant */
2011         if (ftdi_usb_reset(&ftdic) < 0)
2012         {
2013                 LOG_ERROR("unable to reset ftdi device");
2014                 return ERROR_JTAG_INIT_FAILED;
2015         }
2016
2017         if (ftdi_set_latency_timer(&ftdic, ft2232_latency) < 0)
2018         {
2019                 LOG_ERROR("unable to set latency timer");
2020                 return ERROR_JTAG_INIT_FAILED;
2021         }
2022
2023         if (ftdi_get_latency_timer(&ftdic, &latency_timer) < 0)
2024         {
2025                 LOG_ERROR("unable to get latency timer");
2026                 return ERROR_JTAG_INIT_FAILED;
2027         }
2028         else
2029         {
2030                 LOG_DEBUG("current latency timer: %i", latency_timer);
2031         }
2032
2033         ftdi_set_bitmode(&ftdic, 0x0b, 2); /* ctx, JTAG I/O mask */
2034
2035         ftdi_device = ftdic.type;
2036         static const char* type_str[] =
2037                 {"AM", "BM", "2232C", "R", "2232H", "4232H", "Unknown"};
2038         unsigned no_of_known_types = sizeof(type_str) / sizeof(type_str[0]) - 1;
2039         unsigned type_index = ((unsigned)ftdi_device < no_of_known_types)
2040                 ? ftdi_device : no_of_known_types;
2041         LOG_DEBUG("FTDI chip type: %i \"%s\"", (int)ftdi_device, type_str[type_index]);
2042         return ERROR_OK;
2043 }
2044
2045 static int ft2232_purge_libftdi(void)
2046 {
2047         if (ftdi_usb_purge_buffers(&ftdic) < 0)
2048         {
2049                 LOG_ERROR("ftdi_purge_buffers: %s", ftdic.error_str);
2050                 return ERROR_JTAG_INIT_FAILED;
2051         }
2052
2053         return ERROR_OK;
2054 }
2055
2056 #endif /* BUILD_FT2232_LIBFTDI == 1 */
2057
2058 static int ft2232_init(void)
2059 {
2060         uint8_t  buf[1];
2061         int retval;
2062         uint32_t bytes_written;
2063         const ft2232_layout_t* cur_layout = ft2232_layouts;
2064         int i;
2065
2066         if (tap_get_tms_path_len(TAP_IRPAUSE,TAP_IRPAUSE) == 7)
2067         {
2068                 LOG_DEBUG("ft2232 interface using 7 step jtag state transitions");
2069         }
2070         else
2071         {
2072                 LOG_DEBUG("ft2232 interface using shortest path jtag state transitions");
2073
2074         }
2075         if ((ft2232_layout == NULL) || (ft2232_layout[0] == 0))
2076         {
2077                 ft2232_layout = "usbjtag";
2078                 LOG_WARNING("No ft2232 layout specified, using default 'usbjtag'");
2079         }
2080
2081         while (cur_layout->name)
2082         {
2083                 if (strcmp(cur_layout->name, ft2232_layout) == 0)
2084                 {
2085                         layout = cur_layout;
2086                         break;
2087                 }
2088                 cur_layout++;
2089         }
2090
2091         if (!layout)
2092         {
2093                 LOG_ERROR("No matching layout found for %s", ft2232_layout);
2094                 return ERROR_JTAG_INIT_FAILED;
2095         }
2096
2097         for (i = 0; 1; i++)
2098         {
2099                 /*
2100                  * "more indicates that there are more IDs to try, so we should
2101                  * not print an error for an ID mismatch (but for anything
2102                  * else, we should).
2103                  *
2104                  * try_more indicates that the error code returned indicates an
2105                  * ID mismatch (and nothing else) and that we should proceeed
2106                  * with the next ID pair.
2107                  */
2108                 int more     = ft2232_vid[i + 1] || ft2232_pid[i + 1];
2109                 int try_more = 0;
2110
2111 #if BUILD_FT2232_FTD2XX == 1
2112                 retval = ft2232_init_ftd2xx(ft2232_vid[i], ft2232_pid[i],
2113                                 more, &try_more);
2114 #elif BUILD_FT2232_LIBFTDI == 1
2115                 retval = ft2232_init_libftdi(ft2232_vid[i], ft2232_pid[i],
2116                                 more, &try_more);
2117 #endif
2118                 if (retval >= 0)
2119                         break;
2120                 if (!more || !try_more)
2121                         return retval;
2122         }
2123
2124         ft2232_buffer_size = 0;
2125         ft2232_buffer = malloc(FT2232_BUFFER_SIZE);
2126
2127         if (layout->init() != ERROR_OK)
2128                 return ERROR_JTAG_INIT_FAILED;
2129
2130         if (ft2232_device_is_highspeed())
2131         {
2132 #ifndef BUILD_FT2232_HIGHSPEED
2133  #if BUILD_FT2232_FTD2XX == 1
2134                 LOG_WARNING("High Speed device found - You need a newer FTD2XX driver (version 2.04.16 or later)");
2135  #elif BUILD_FT2232_LIBFTDI == 1
2136                 LOG_WARNING("High Speed device found - You need a newer libftdi version (0.16 or later)");
2137  #endif
2138 #endif
2139                 /* make sure the legacy mode is disabled */
2140                 if (ft2232h_ft4232h_clk_divide_by_5(false) != ERROR_OK)
2141                         return ERROR_JTAG_INIT_FAILED;
2142         }
2143
2144         ft2232_speed(jtag_get_speed());
2145
2146         buf[0] = 0x85; /* Disconnect TDI/DO to TDO/DI for Loopback */
2147         if (((retval = ft2232_write(buf, 1, &bytes_written)) != ERROR_OK) || (bytes_written != 1))
2148         {
2149                 LOG_ERROR("couldn't write to FT2232 to disable loopback");
2150                 return ERROR_JTAG_INIT_FAILED;
2151         }
2152
2153 #if BUILD_FT2232_FTD2XX == 1
2154         return ft2232_purge_ftd2xx();
2155 #elif BUILD_FT2232_LIBFTDI == 1
2156         return ft2232_purge_libftdi();
2157 #endif
2158
2159         return ERROR_OK;
2160 }
2161
2162 static int usbjtag_init(void)
2163 {
2164         uint8_t  buf[3];
2165         uint32_t bytes_written;
2166
2167         low_output    = 0x08;
2168         low_direction = 0x0b;
2169
2170         if (strcmp(ft2232_layout, "usbjtag") == 0)
2171         {
2172                 nTRST    = 0x10;
2173                 nTRSTnOE = 0x10;
2174                 nSRST    = 0x40;
2175                 nSRSTnOE = 0x40;
2176         }
2177         else if (strcmp(ft2232_layout, "signalyzer") == 0)
2178         {
2179                 nTRST    = 0x10;
2180                 nTRSTnOE = 0x10;
2181                 nSRST    = 0x20;
2182                 nSRSTnOE = 0x20;
2183         }
2184         else if (strcmp(ft2232_layout, "evb_lm3s811") == 0)
2185         {
2186                 nTRST = 0x0;
2187                 nTRSTnOE = 0x00;
2188                 nSRST = 0x20;
2189                 nSRSTnOE = 0x20;
2190                 low_output    = 0x88;
2191                 low_direction = 0x8b;
2192         }
2193         else if (strcmp(ft2232_layout, "luminary_icdi") == 0)
2194         {
2195                 nTRST = 0x0;
2196                 nTRSTnOE = 0x00;
2197                 nSRST = 0x20;
2198                 nSRSTnOE = 0x20;
2199                 low_output    = 0x88;
2200                 low_direction = 0xcb;
2201         }
2202         else
2203         {
2204                 LOG_ERROR("BUG: usbjtag_init called for unknown layout '%s'", ft2232_layout);
2205                 return ERROR_JTAG_INIT_FAILED;
2206         }
2207
2208         enum reset_types jtag_reset_config = jtag_get_reset_config();
2209         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2210         {
2211                 low_direction &= ~nTRSTnOE; /* nTRST input */
2212                 low_output    &= ~nTRST;    /* nTRST = 0 */
2213         }
2214         else
2215         {
2216                 low_direction |= nTRSTnOE;  /* nTRST output */
2217                 low_output    |= nTRST;     /* nTRST = 1 */
2218         }
2219
2220         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2221         {
2222                 low_direction |= nSRSTnOE;  /* nSRST output */
2223                 low_output    |= nSRST;     /* nSRST = 1 */
2224         }
2225         else
2226         {
2227                 low_direction &= ~nSRSTnOE; /* nSRST input */
2228                 low_output    &= ~nSRST;    /* nSRST = 0 */
2229         }
2230
2231         /* initialize low byte for jtag */
2232         buf[0] = 0x80;          /* command "set data bits low byte" */
2233         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, xRST high) */
2234         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in */
2235         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2236
2237         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2238         {
2239                 LOG_ERROR("couldn't initialize FT2232 with 'USBJTAG' layout");
2240                 return ERROR_JTAG_INIT_FAILED;
2241         }
2242
2243         return ERROR_OK;
2244 }
2245
2246 static int axm0432_jtag_init(void)
2247 {
2248         uint8_t  buf[3];
2249         uint32_t bytes_written;
2250
2251         low_output    = 0x08;
2252         low_direction = 0x2b;
2253
2254         /* initialize low byte for jtag */
2255         buf[0] = 0x80;          /* command "set data bits low byte" */
2256         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2257         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2258         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2259
2260         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2261         {
2262                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2263                 return ERROR_JTAG_INIT_FAILED;
2264         }
2265
2266         if (strcmp(layout->name, "axm0432_jtag") == 0)
2267         {
2268                 nTRST    = 0x08;
2269                 nTRSTnOE = 0x0;     /* No output enable for TRST*/
2270                 nSRST    = 0x04;
2271                 nSRSTnOE = 0x0;     /* No output enable for SRST*/
2272         }
2273         else
2274         {
2275                 LOG_ERROR("BUG: axm0432_jtag_init called for non axm0432 layout");
2276                 exit(-1);
2277         }
2278
2279         high_output    = 0x0;
2280         high_direction = 0x0c;
2281
2282         enum reset_types jtag_reset_config = jtag_get_reset_config();
2283         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2284         {
2285                 LOG_ERROR("can't set nTRSTOE to push-pull on the Dicarlo jtag");
2286         }
2287         else
2288         {
2289                 high_output |= nTRST;
2290         }
2291
2292         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2293         {
2294                 LOG_ERROR("can't set nSRST to push-pull on the Dicarlo jtag");
2295         }
2296         else
2297         {
2298                 high_output |= nSRST;
2299         }
2300
2301         /* initialize high port */
2302         buf[0] = 0x82;              /* command "set data bits high byte" */
2303         buf[1] = high_output;       /* value */
2304         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2305         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2306
2307         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2308         {
2309                 LOG_ERROR("couldn't initialize FT2232 with 'Dicarlo' layout");
2310                 return ERROR_JTAG_INIT_FAILED;
2311         }
2312
2313         return ERROR_OK;
2314 }
2315
2316 static int jtagkey_init(void)
2317 {
2318         uint8_t  buf[3];
2319         uint32_t bytes_written;
2320
2321         low_output    = 0x08;
2322         low_direction = 0x1b;
2323
2324         /* initialize low byte for jtag */
2325         buf[0] = 0x80;          /* command "set data bits low byte" */
2326         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2327         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2328         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2329
2330         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2331         {
2332                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2333                 return ERROR_JTAG_INIT_FAILED;
2334         }
2335
2336         if (strcmp(layout->name, "jtagkey") == 0)
2337         {
2338                 nTRST    = 0x01;
2339                 nTRSTnOE = 0x4;
2340                 nSRST    = 0x02;
2341                 nSRSTnOE = 0x08;
2342         }
2343         else if ((strcmp(layout->name, "jtagkey_prototype_v1") == 0)
2344                          || (strcmp(layout->name, "oocdlink") == 0))
2345         {
2346                 nTRST    = 0x02;
2347                 nTRSTnOE = 0x1;
2348                 nSRST    = 0x08;
2349                 nSRSTnOE = 0x04;
2350         }
2351         else
2352         {
2353                 LOG_ERROR("BUG: jtagkey_init called for non jtagkey layout");
2354                 exit(-1);
2355         }
2356
2357         high_output    = 0x0;
2358         high_direction = 0x0f;
2359
2360         enum reset_types jtag_reset_config = jtag_get_reset_config();
2361         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2362         {
2363                 high_output |= nTRSTnOE;
2364                 high_output &= ~nTRST;
2365         }
2366         else
2367         {
2368                 high_output &= ~nTRSTnOE;
2369                 high_output |= nTRST;
2370         }
2371
2372         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2373         {
2374                 high_output &= ~nSRSTnOE;
2375                 high_output |= nSRST;
2376         }
2377         else
2378         {
2379                 high_output |= nSRSTnOE;
2380                 high_output &= ~nSRST;
2381         }
2382
2383         /* initialize high port */
2384         buf[0] = 0x82;              /* command "set data bits high byte" */
2385         buf[1] = high_output;       /* value */
2386         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2387         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2388
2389         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2390         {
2391                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2392                 return ERROR_JTAG_INIT_FAILED;
2393         }
2394
2395         return ERROR_OK;
2396 }
2397
2398 static int olimex_jtag_init(void)
2399 {
2400         uint8_t  buf[3];
2401         uint32_t bytes_written;
2402
2403         low_output    = 0x08;
2404         low_direction = 0x1b;
2405
2406         /* initialize low byte for jtag */
2407         buf[0] = 0x80;          /* command "set data bits low byte" */
2408         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2409         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2410         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2411
2412         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2413         {
2414                 LOG_ERROR("couldn't initialize FT2232 with 'Olimex' layout");
2415                 return ERROR_JTAG_INIT_FAILED;
2416         }
2417
2418         nTRST    = 0x01;
2419         nTRSTnOE = 0x4;
2420         nSRST    = 0x02;
2421         nSRSTnOE = 0x00; /* no output enable for nSRST */
2422
2423         high_output    = 0x0;
2424         high_direction = 0x0f;
2425
2426         enum reset_types jtag_reset_config = jtag_get_reset_config();
2427         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2428         {
2429                 high_output |= nTRSTnOE;
2430                 high_output &= ~nTRST;
2431         }
2432         else
2433         {
2434                 high_output &= ~nTRSTnOE;
2435                 high_output |= nTRST;
2436         }
2437
2438         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2439         {
2440                 LOG_ERROR("can't set nSRST to push-pull on the Olimex ARM-USB-OCD");
2441         }
2442         else
2443         {
2444                 high_output &= ~nSRST;
2445         }
2446
2447         /* turn red LED on */
2448         high_output |= 0x08;
2449
2450         /* initialize high port */
2451         buf[0] = 0x82;              /* command "set data bits high byte" */
2452         buf[1] = high_output;       /* value */
2453         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2454         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2455
2456         if ((ft2232_write(buf, 3, &bytes_written) != ERROR_OK) || (bytes_written != 3))
2457         {
2458                 LOG_ERROR("couldn't initialize FT2232 with 'Olimex' layout");
2459                 return ERROR_JTAG_INIT_FAILED;
2460         }
2461
2462         return ERROR_OK;
2463 }
2464
2465 static int flyswatter_init(void)
2466 {
2467         uint8_t  buf[3];
2468         uint32_t bytes_written;
2469
2470         low_output    = 0x18;
2471         low_direction = 0xfb;
2472
2473         /* initialize low byte for jtag */
2474         buf[0] = 0x80;          /* command "set data bits low byte" */
2475         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2476         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE[12]=out, n[ST]srst = out */
2477         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2478
2479         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2480         {
2481                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2482                 return ERROR_JTAG_INIT_FAILED;
2483         }
2484
2485         nTRST    = 0x10;
2486         nTRSTnOE = 0x0;     /* not output enable for nTRST */
2487         nSRST    = 0x20;
2488         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2489
2490         high_output    = 0x00;
2491         high_direction = 0x0c;
2492
2493         /* turn red LED3 on, LED2 off */
2494         high_output |= 0x08;
2495
2496         /* initialize high port */
2497         buf[0] = 0x82;              /* command "set data bits high byte" */
2498         buf[1] = high_output;       /* value */
2499         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2500         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2501
2502         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2503         {
2504                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2505                 return ERROR_JTAG_INIT_FAILED;
2506         }
2507
2508         return ERROR_OK;
2509 }
2510
2511 static int turtle_init(void)
2512 {
2513         uint8_t  buf[3];
2514         uint32_t bytes_written;
2515
2516         low_output    = 0x08;
2517         low_direction = 0x5b;
2518
2519         /* initialize low byte for jtag */
2520         buf[0] = 0x80;          /* command "set data bits low byte" */
2521         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2522         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2523         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2524
2525         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2526         {
2527                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2528                 return ERROR_JTAG_INIT_FAILED;
2529         }
2530
2531         nSRST = 0x40;
2532
2533         high_output    = 0x00;
2534         high_direction = 0x0C;
2535
2536         /* initialize high port */
2537         buf[0] = 0x82; /* command "set data bits high byte" */
2538         buf[1] = high_output;
2539         buf[2] = high_direction;
2540         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2541
2542         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2543         {
2544                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2545                 return ERROR_JTAG_INIT_FAILED;
2546         }
2547
2548         return ERROR_OK;
2549 }
2550
2551 static int comstick_init(void)
2552 {
2553         uint8_t  buf[3];
2554         uint32_t bytes_written;
2555
2556         low_output    = 0x08;
2557         low_direction = 0x0b;
2558
2559         /* initialize low byte for jtag */
2560         buf[0] = 0x80;          /* command "set data bits low byte" */
2561         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2562         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2563         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2564
2565         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2566         {
2567                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2568                 return ERROR_JTAG_INIT_FAILED;
2569         }
2570
2571         nTRST    = 0x01;
2572         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2573         nSRST    = 0x02;
2574         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2575
2576         high_output    = 0x03;
2577         high_direction = 0x03;
2578
2579         /* initialize high port */
2580         buf[0] = 0x82; /* command "set data bits high byte" */
2581         buf[1] = high_output;
2582         buf[2] = high_direction;
2583         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2584
2585         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2586         {
2587                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2588                 return ERROR_JTAG_INIT_FAILED;
2589         }
2590
2591         return ERROR_OK;
2592 }
2593
2594 static int stm32stick_init(void)
2595 {
2596         uint8_t  buf[3];
2597         uint32_t bytes_written;
2598
2599         low_output    = 0x88;
2600         low_direction = 0x8b;
2601
2602         /* initialize low byte for jtag */
2603         buf[0] = 0x80;          /* command "set data bits low byte" */
2604         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2605         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2606         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2607
2608         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2609         {
2610                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2611                 return ERROR_JTAG_INIT_FAILED;
2612         }
2613
2614         nTRST    = 0x01;
2615         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2616         nSRST    = 0x80;
2617         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2618
2619         high_output    = 0x01;
2620         high_direction = 0x03;
2621
2622         /* initialize high port */
2623         buf[0] = 0x82; /* command "set data bits high byte" */
2624         buf[1] = high_output;
2625         buf[2] = high_direction;
2626         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2627
2628         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2629         {
2630                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2631                 return ERROR_JTAG_INIT_FAILED;
2632         }
2633
2634         return ERROR_OK;
2635 }
2636
2637 static int sheevaplug_init(void)
2638 {
2639         uint8_t buf[3];
2640         uint32_t bytes_written;
2641
2642         low_output = 0x08;
2643         low_direction = 0x1b;
2644
2645         /* initialize low byte for jtag */
2646         buf[0] = 0x80; /* command "set data bits low byte" */
2647         buf[1] = low_output; /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2648         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in */
2649         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2650
2651         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2652         {
2653                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2654                 return ERROR_JTAG_INIT_FAILED;
2655         }
2656
2657         nTRSTnOE = 0x1;
2658         nTRST = 0x02;
2659         nSRSTnOE = 0x4;
2660         nSRST = 0x08;
2661
2662         high_output = 0x0;
2663         high_direction = 0x0f;
2664
2665         /* nTRST is always push-pull */
2666         high_output &= ~nTRSTnOE;
2667         high_output |= nTRST;
2668
2669         /* nSRST is always open-drain */
2670         high_output |= nSRSTnOE;
2671         high_output &= ~nSRST;
2672
2673         /* initialize high port */
2674         buf[0] = 0x82; /* command "set data bits high byte" */
2675         buf[1] = high_output; /* value */
2676         buf[2] = high_direction;   /* all outputs - xRST */
2677         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2678
2679         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2680         {
2681                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2682                 return ERROR_JTAG_INIT_FAILED;
2683         }
2684
2685         return ERROR_OK;
2686 }
2687
2688 static int cortino_jtag_init(void)
2689 {
2690         uint8_t  buf[3];
2691         uint32_t bytes_written;
2692
2693         low_output    = 0x08;
2694         low_direction = 0x1b;
2695
2696         /* initialize low byte for jtag */
2697         buf[0] = 0x80;          /* command "set data bits low byte" */
2698         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2699         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2700         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2701
2702         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2703         {
2704                 LOG_ERROR("couldn't initialize FT2232 with 'cortino' layout");
2705                 return ERROR_JTAG_INIT_FAILED;
2706         }
2707
2708         nTRST    = 0x01;
2709         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2710         nSRST    = 0x02;
2711         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2712
2713         high_output    = 0x03;
2714         high_direction = 0x03;
2715
2716         /* initialize high port */
2717         buf[0] = 0x82; /* command "set data bits high byte" */
2718         buf[1] = high_output;
2719         buf[2] = high_direction;
2720         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2721
2722         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2723         {
2724                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2725                 return ERROR_JTAG_INIT_FAILED;
2726         }
2727
2728         return ERROR_OK;
2729 }
2730
2731 static void olimex_jtag_blink(void)
2732 {
2733         /* Olimex ARM-USB-OCD has a LED connected to ACBUS3
2734          * ACBUS3 is bit 3 of the GPIOH port
2735          */
2736         if (high_output & 0x08)
2737         {
2738                 /* set port pin high */
2739                 high_output &= 0x07;
2740         }
2741         else
2742         {
2743                 /* set port pin low */
2744                 high_output |= 0x08;
2745         }
2746
2747         buffer_write(0x82);
2748         buffer_write(high_output);
2749         buffer_write(high_direction);
2750 }
2751
2752 static void flyswatter_jtag_blink(void)
2753 {
2754         /*
2755          * Flyswatter has two LEDs connected to ACBUS2 and ACBUS3
2756          */
2757         high_output ^= 0x0c;
2758
2759         buffer_write(0x82);
2760         buffer_write(high_output);
2761         buffer_write(high_direction);
2762 }
2763
2764 static void turtle_jtag_blink(void)
2765 {
2766         /*
2767          * Turtelizer2 has two LEDs connected to ACBUS2 and ACBUS3
2768          */
2769         if (high_output & 0x08)
2770         {
2771                 high_output = 0x04;
2772         }
2773         else
2774         {
2775                 high_output = 0x08;
2776         }
2777
2778         buffer_write(0x82);
2779         buffer_write(high_output);
2780         buffer_write(high_direction);
2781 }
2782
2783 static int ft2232_quit(void)
2784 {
2785 #if BUILD_FT2232_FTD2XX == 1
2786         FT_STATUS status;
2787
2788         status = FT_Close(ftdih);
2789 #elif BUILD_FT2232_LIBFTDI == 1
2790         ftdi_usb_close(&ftdic);
2791
2792         ftdi_deinit(&ftdic);
2793 #endif
2794
2795         free(ft2232_buffer);
2796         ft2232_buffer = NULL;
2797
2798         return ERROR_OK;
2799 }
2800
2801 static int ft2232_handle_device_desc_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2802 {
2803         char *cp;
2804         char buf[200];
2805         if (argc == 1)
2806         {
2807                 ft2232_device_desc = strdup(args[0]);
2808                 cp = strchr(ft2232_device_desc, 0);
2809                 /* under Win32, the FTD2XX driver appends an "A" to the end
2810                  * of the description, this examines the given desc
2811                  * and creates the 'missing' _A or non_A variable. */
2812                 if ((cp[-1] == 'A') && (cp[-2]==' ')) {
2813                         /* it was, so make this the "A" version. */
2814                         ft2232_device_desc_A = ft2232_device_desc;
2815                         /* and *CREATE* the non-A version. */
2816                         strcpy(buf, ft2232_device_desc);
2817                         cp = strchr(buf, 0);
2818                         cp[-2] = 0;
2819                         ft2232_device_desc =  strdup(buf);
2820                 } else {
2821                         /* <space > A not defined
2822                          * so create it */
2823                         sprintf(buf, "%s A", ft2232_device_desc);
2824                         ft2232_device_desc_A = strdup(buf);
2825                 }
2826         }
2827         else
2828         {
2829                 LOG_ERROR("expected exactly one argument to ft2232_device_desc <description>");
2830         }
2831
2832         return ERROR_OK;
2833 }
2834
2835 static int ft2232_handle_serial_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2836 {
2837         if (argc == 1)
2838         {
2839                 ft2232_serial = strdup(args[0]);
2840         }
2841         else
2842         {
2843                 LOG_ERROR("expected exactly one argument to ft2232_serial <serial-number>");
2844         }
2845
2846         return ERROR_OK;
2847 }
2848
2849 static int ft2232_handle_layout_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2850 {
2851         if (argc == 0)
2852                 return ERROR_OK;
2853
2854         ft2232_layout = malloc(strlen(args[0]) + 1);
2855         strcpy(ft2232_layout, args[0]);
2856
2857         return ERROR_OK;
2858 }
2859
2860 static int ft2232_handle_vid_pid_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2861 {
2862         if (argc > MAX_USB_IDS * 2)
2863         {
2864                 LOG_WARNING("ignoring extra IDs in ft2232_vid_pid "
2865                                         "(maximum is %d pairs)", MAX_USB_IDS);
2866                 argc = MAX_USB_IDS * 2;
2867         }
2868         if (argc < 2 || (argc & 1))
2869         {
2870                 LOG_WARNING("incomplete ft2232_vid_pid configuration directive");
2871                 if (argc < 2)
2872                         return ERROR_COMMAND_SYNTAX_ERROR;
2873                 /* remove the incomplete trailing id */
2874                 argc -= 1;
2875         }
2876
2877         int i;
2878         int retval = ERROR_OK;
2879         for (i = 0; i < argc; i += 2)
2880         {
2881                 retval = parse_u16(args[i], &ft2232_vid[i >> 1]);
2882                 if (ERROR_OK != retval)
2883                         break;
2884                 retval = parse_u16(args[i + 1], &ft2232_pid[i >> 1]);
2885                 if (ERROR_OK != retval)
2886                         break;
2887         }
2888
2889         /*
2890          * Explicitly terminate, in case there are multiples instances of
2891          * ft2232_vid_pid.
2892          */
2893         ft2232_vid[i >> 1] = ft2232_pid[i >> 1] = 0;
2894
2895         return retval;
2896 }
2897
2898 static int ft2232_handle_latency_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2899 {
2900         if (argc == 1)
2901         {
2902                 ft2232_latency = atoi(args[0]);
2903         }
2904         else
2905         {
2906                 LOG_ERROR("expected exactly one argument to ft2232_latency <ms>");
2907         }
2908
2909         return ERROR_OK;
2910 }
2911
2912 static int ft2232_stableclocks(int num_cycles, jtag_command_t* cmd)
2913 {
2914         int retval = 0;
2915
2916         /* 7 bits of either ones or zeros. */
2917         uint8_t  tms = (tap_get_state() == TAP_RESET ? 0x7F : 0x00);
2918
2919         while (num_cycles > 0)
2920         {
2921                 /* the command 0x4b, "Clock Data to TMS/CS Pin (no Read)" handles
2922                  * at most 7 bits per invocation.  Here we invoke it potentially
2923                  * several times.
2924                  */
2925                 int bitcount_per_command = (num_cycles > 7) ? 7 : num_cycles;
2926
2927                 if (ft2232_buffer_size + 3 >= FT2232_BUFFER_SIZE)
2928                 {
2929                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
2930                                 retval = ERROR_JTAG_QUEUE_FAILED;
2931
2932                         first_unsent = cmd;
2933                 }
2934
2935                 /* there are no state transitions in this code, so omit state tracking */
2936
2937                 /* command "Clock Data to TMS/CS Pin (no Read)" */
2938                 buffer_write(0x4b);
2939
2940                 /* scan 7 bit */
2941                 buffer_write(bitcount_per_command - 1);
2942
2943                 /* TMS data bits are either all zeros or ones to stay in the current stable state */
2944                 buffer_write(tms);
2945
2946                 require_send = 1;
2947
2948                 num_cycles -= bitcount_per_command;
2949         }
2950
2951         return retval;
2952 }
2953
2954 /* ---------------------------------------------------------------------
2955  * Support for IceBear JTAG adapter from Section5:
2956  *      http://section5.ch/icebear
2957  *
2958  * Author: Sten, debian@sansys-electronic.com
2959  */
2960
2961 /* Icebear pin layout
2962  *
2963  * ADBUS5 (nEMU) nSRST  | 2   1|        GND (10k->VCC)
2964  * GND GND              | 4   3|        n.c.
2965  * ADBUS3 TMS           | 6   5|        ADBUS6 VCC
2966  * ADBUS0 TCK           | 8   7|        ADBUS7 (GND)
2967  * ADBUS4 nTRST         |10   9|        ACBUS0 (GND)
2968  * ADBUS1 TDI           |12  11|        ACBUS1 (GND)
2969  * ADBUS2 TDO           |14  13|        GND GND
2970  *
2971  * ADBUS0 O L TCK               ACBUS0 GND
2972  * ADBUS1 O L TDI               ACBUS1 GND
2973  * ADBUS2 I   TDO               ACBUS2 n.c.
2974  * ADBUS3 O H TMS               ACBUS3 n.c.
2975  * ADBUS4 O H nTRST
2976  * ADBUS5 O H nSRST
2977  * ADBUS6 -   VCC
2978  * ADBUS7 -   GND
2979  */
2980 static int icebear_jtag_init(void) {
2981         uint8_t  buf[3];
2982         uint32_t bytes_written;
2983
2984         low_direction   = 0x0b; /* output: TCK TDI TMS; input: TDO */
2985         low_output      = 0x08; /* high: TMS; low: TCK TDI */
2986         nTRST           = 0x10;
2987         nSRST           = 0x20;
2988
2989         enum reset_types jtag_reset_config = jtag_get_reset_config();
2990         if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0) {
2991                 low_direction   &= ~nTRST;      /* nTRST high impedance */
2992         }
2993         else {
2994                 low_direction   |= nTRST;
2995                 low_output      |= nTRST;
2996         }
2997
2998         low_direction   |= nSRST;
2999         low_output      |= nSRST;
3000
3001         /* initialize low byte for jtag */
3002         buf[0] = 0x80;          /* command "set data bits low byte" */
3003         buf[1] = low_output;
3004         buf[2] = low_direction;
3005         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
3006
3007         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3)) {
3008                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (low)");
3009                 return ERROR_JTAG_INIT_FAILED;
3010         }
3011
3012         high_output    = 0x0;
3013         high_direction = 0x00;
3014
3015
3016         /* initialize high port */
3017         buf[0] = 0x82;              /* command "set data bits high byte" */
3018         buf[1] = high_output;       /* value */
3019         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
3020         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
3021
3022         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3)) {
3023                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (high)");
3024                 return ERROR_JTAG_INIT_FAILED;
3025         }
3026
3027         return ERROR_OK;
3028 }
3029
3030 static void icebear_jtag_reset(int trst, int srst) {
3031
3032         if (trst == 1) {
3033                 low_direction   |= nTRST;
3034                 low_output      &= ~nTRST;
3035         }
3036         else if (trst == 0) {
3037                 enum reset_types jtag_reset_config = jtag_get_reset_config();
3038                 if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0)
3039                         low_direction   &= ~nTRST;
3040                 else
3041                         low_output      |= nTRST;
3042         }
3043
3044         if (srst == 1) {
3045                 low_output &= ~nSRST;
3046         }
3047         else if (srst == 0) {
3048                 low_output |= nSRST;
3049         }
3050
3051         /* command "set data bits low byte" */
3052         buffer_write(0x80);
3053         buffer_write(low_output);
3054         buffer_write(low_direction);
3055
3056         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
3057 }