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