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