]> git.sur5r.net Git - openocd/blob - src/jtag/ft2232.c
David Brownell <david-b@pacbell.net>:
[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_DEBUG("RTCK 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         layout->reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1633         require_send = 1;
1634
1635 #ifdef _DEBUG_JTAG_IO_
1636         LOG_DEBUG("trst: %i, srst: %i", cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1637 #endif
1638         return retval;
1639 }
1640
1641 static int ft2232_execute_sleep(jtag_command_t *cmd)
1642 {
1643         int             retval;
1644         retval = ERROR_OK;
1645
1646         DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
1647
1648         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1649                                 retval = ERROR_JTAG_QUEUE_FAILED;
1650         first_unsent = cmd->next;
1651         jtag_sleep(cmd->cmd.sleep->us);
1652 #ifdef _DEBUG_JTAG_IO_
1653                         LOG_DEBUG( "sleep %i usec while in %s", cmd->cmd.sleep->us, tap_state_name( tap_get_state() ) );
1654 #endif
1655
1656         return retval;
1657 }
1658
1659 static int ft2232_execute_stableclocks(jtag_command_t *cmd)
1660 {
1661         int             retval;
1662         retval = ERROR_OK;
1663
1664         /* this is only allowed while in a stable state.  A check for a stable
1665          * state was done in jtag_add_clocks()
1666          */
1667         if (ft2232_stableclocks(cmd->cmd.stableclocks->num_cycles, cmd) != ERROR_OK)
1668                 retval = ERROR_JTAG_QUEUE_FAILED;
1669 #ifdef _DEBUG_JTAG_IO_
1670         LOG_DEBUG( "clocks %i while in %s", cmd->cmd.stableclocks->num_cycles, tap_state_name( tap_get_state() ) );
1671 #endif
1672
1673         return retval;
1674 }
1675
1676 static int ft2232_execute_command(jtag_command_t *cmd)
1677 {
1678         int             retval;
1679         retval = ERROR_OK;
1680
1681         switch (cmd->type)
1682         {
1683         case JTAG_END_STATE:    retval = ft2232_execute_end_state(cmd); break;
1684         case JTAG_RESET:                        retval = ft2232_execute_reset(cmd); break;
1685         case JTAG_RUNTEST:      retval = ft2232_execute_runtest(cmd); break;
1686         case JTAG_STATEMOVE:    retval = ft2232_execute_statemove(cmd); break;
1687         case JTAG_PATHMOVE:     retval = ft2232_execute_pathmove(cmd); break;
1688         case JTAG_SCAN:                         retval = ft2232_execute_scan(cmd); break;
1689         case JTAG_SLEEP:                        retval = ft2232_execute_sleep(cmd); break;
1690         case JTAG_STABLECLOCKS:         retval = ft2232_execute_stableclocks(cmd); break;
1691         default:
1692                 LOG_ERROR("BUG: unknown JTAG command type encountered");
1693                 exit(-1);
1694         }
1695         return retval;
1696 }
1697
1698 static int ft2232_execute_queue()
1699 {
1700         jtag_command_t* cmd = jtag_command_queue;   /* currently processed command */
1701         int             retval;
1702
1703         first_unsent = cmd;         /* next command that has to be sent */
1704         require_send = 0;
1705
1706         /* return ERROR_OK, unless ft2232_send_and_recv reports a failed check
1707          * that wasn't handled by a caller-provided error handler
1708          */
1709         retval = ERROR_OK;
1710
1711         ft2232_buffer_size = 0;
1712         ft2232_expect_read = 0;
1713
1714         /* blink, if the current layout has that feature */
1715         if (layout->blink)
1716                 layout->blink();
1717
1718         while (cmd)
1719         {
1720                 if (ft2232_execute_command(cmd) != ERROR_OK)
1721                         retval = ERROR_JTAG_QUEUE_FAILED;
1722                 /* Start reading input before FT2232 TX buffer fills up */
1723                 cmd = cmd->next;
1724                 if (ft2232_expect_read > 256)
1725                 {
1726                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1727                                 retval = ERROR_JTAG_QUEUE_FAILED;
1728                         first_unsent = cmd;
1729                 }
1730         }
1731
1732         if (require_send > 0)
1733                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1734                         retval = ERROR_JTAG_QUEUE_FAILED;
1735
1736         return retval;
1737 }
1738
1739
1740 #if BUILD_FT2232_FTD2XX == 1
1741 static int ft2232_init_ftd2xx(u16 vid, u16 pid, int more, int* try_more)
1742 {
1743         FT_STATUS       status;
1744         DWORD           openex_flags  = 0;
1745         char*           openex_string = NULL;
1746         u8              latency_timer;
1747
1748         LOG_DEBUG("'ft2232' interface using FTD2XX with '%s' layout (%4.4x:%4.4x)", ft2232_layout, vid, pid);
1749
1750 #if IS_WIN32 == 0
1751         /* Add non-standard Vid/Pid to the linux driver */
1752         if ( ( status = FT_SetVIDPID(vid, pid) ) != FT_OK )
1753         {
1754                 LOG_WARNING("couldn't add %4.4x:%4.4x", vid, pid);
1755         }
1756 #endif
1757
1758         if (ft2232_device_desc && ft2232_serial)
1759         {
1760                 LOG_WARNING("can't open by device description and serial number, giving precedence to serial");
1761                 ft2232_device_desc = NULL;
1762         }
1763
1764         if (ft2232_device_desc)
1765         {
1766                 openex_string = ft2232_device_desc;
1767                 openex_flags  = FT_OPEN_BY_DESCRIPTION;
1768         }
1769         else if (ft2232_serial)
1770         {
1771                 openex_string = ft2232_serial;
1772                 openex_flags  = FT_OPEN_BY_SERIAL_NUMBER;
1773         }
1774         else
1775         {
1776                 LOG_ERROR("neither device description nor serial number specified");
1777                 LOG_ERROR("please add \"ft2232_device_desc <string>\" or \"ft2232_serial <string>\" to your .cfg file");
1778
1779                 return ERROR_JTAG_INIT_FAILED;
1780         }
1781
1782         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
1783         if( status != FT_OK ){
1784                 // under Win32, the FTD2XX driver appends an "A" to the end
1785                 // of the description, if we tried by the desc, then
1786                 // try by the alternate "A" description.
1787                 if( openex_string == ft2232_device_desc ){
1788                         // Try the alternate method.
1789                         openex_string = ft2232_device_desc_A;
1790                         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
1791                         if( status == FT_OK ){
1792                                 // yea, the "alternate" method worked!
1793                         } else {
1794                                 // drat, give the user a meaningfull message.
1795                                 // telling the use we tried *BOTH* methods.
1796                                 LOG_WARNING("Unable to open FTDI Device tried: '%s' and '%s'\n",
1797                                                         ft2232_device_desc,
1798                                                         ft2232_device_desc_A );
1799                         }
1800                 }
1801         }
1802
1803         if ( status != FT_OK )
1804         {
1805                 DWORD num_devices;
1806
1807                 if (more)
1808                 {
1809                         LOG_WARNING("unable to open ftdi device (trying more): %lu", status);
1810                         *try_more = 1;
1811                         return ERROR_JTAG_INIT_FAILED;
1812                 }
1813                 LOG_ERROR("unable to open ftdi device: %lu", status);
1814                 status = FT_ListDevices(&num_devices, NULL, FT_LIST_NUMBER_ONLY);
1815                 if (status == FT_OK)
1816                 {
1817                         char** desc_array = malloc( sizeof(char*) * (num_devices + 1) );
1818                         u32 i;
1819
1820                         for (i = 0; i < num_devices; i++)
1821                                 desc_array[i] = malloc(64);
1822
1823                         desc_array[num_devices] = NULL;
1824
1825                         status = FT_ListDevices(desc_array, &num_devices, FT_LIST_ALL | openex_flags);
1826
1827                         if (status == FT_OK)
1828                         {
1829                                 LOG_ERROR("ListDevices: %lu\n", num_devices);
1830                                 for (i = 0; i < num_devices; i++)
1831                                         LOG_ERROR("%i: \"%s\"", i, desc_array[i]);
1832                         }
1833
1834                         for (i = 0; i < num_devices; i++)
1835                                 free(desc_array[i]);
1836
1837                         free(desc_array);
1838                 }
1839                 else
1840                 {
1841                         LOG_ERROR("ListDevices: NONE\n");
1842                 }
1843                 return ERROR_JTAG_INIT_FAILED;
1844         }
1845
1846         if ( ( status = FT_SetLatencyTimer(ftdih, ft2232_latency) ) != FT_OK )
1847         {
1848                 LOG_ERROR("unable to set latency timer: %lu", status);
1849                 return ERROR_JTAG_INIT_FAILED;
1850         }
1851
1852         if ( ( status = FT_GetLatencyTimer(ftdih, &latency_timer) ) != FT_OK )
1853         {
1854                 LOG_ERROR("unable to get latency timer: %lu", status);
1855                 return ERROR_JTAG_INIT_FAILED;
1856         }
1857         else
1858         {
1859                 LOG_DEBUG("current latency timer: %i", latency_timer);
1860         }
1861
1862         if ( ( status = FT_SetTimeouts(ftdih, 5000, 5000) ) != FT_OK )
1863         {
1864                 LOG_ERROR("unable to set timeouts: %lu", status);
1865                 return ERROR_JTAG_INIT_FAILED;
1866         }
1867
1868         if ( ( status = FT_SetBitMode(ftdih, 0x0b, 2) ) != FT_OK )
1869         {
1870                 LOG_ERROR("unable to enable bit i/o mode: %lu", status);
1871                 return ERROR_JTAG_INIT_FAILED;
1872         }
1873
1874         return ERROR_OK;
1875 }
1876
1877
1878 static int ft2232_purge_ftd2xx(void)
1879 {
1880         FT_STATUS status;
1881
1882         if ( ( status = FT_Purge(ftdih, FT_PURGE_RX | FT_PURGE_TX) ) != FT_OK )
1883         {
1884                 LOG_ERROR("error purging ftd2xx device: %lu", status);
1885                 return ERROR_JTAG_INIT_FAILED;
1886         }
1887
1888         return ERROR_OK;
1889 }
1890
1891
1892 #endif /* BUILD_FT2232_FTD2XX == 1 */
1893
1894 #if BUILD_FT2232_LIBFTDI == 1
1895 static int ft2232_init_libftdi(u16 vid, u16 pid, int more, int* try_more)
1896 {
1897         u8 latency_timer;
1898
1899         LOG_DEBUG("'ft2232' interface using libftdi with '%s' layout (%4.4x:%4.4x)",
1900                         ft2232_layout, vid, pid);
1901
1902         if (ftdi_init(&ftdic) < 0)
1903                 return ERROR_JTAG_INIT_FAILED;
1904
1905         if (ftdi_set_interface(&ftdic, INTERFACE_A) < 0)
1906         {
1907                 LOG_ERROR("unable to select FT2232 channel A: %s", ftdic.error_str);
1908                 return ERROR_JTAG_INIT_FAILED;
1909         }
1910
1911         /* context, vendor id, product id */
1912         if (ftdi_usb_open_desc(&ftdic, vid, pid, ft2232_device_desc,
1913                                 ft2232_serial) < 0)
1914         {
1915                 if (more)
1916                         LOG_WARNING("unable to open ftdi device (trying more): %s",
1917                                         ftdic.error_str);
1918                 else
1919                         LOG_ERROR("unable to open ftdi device: %s", ftdic.error_str);
1920                 *try_more = 1;
1921                 return ERROR_JTAG_INIT_FAILED;
1922         }
1923
1924         /* There is already a reset in ftdi_usb_open_desc, this should be redundant */
1925         if (ftdi_usb_reset(&ftdic) < 0)
1926         {
1927                 LOG_ERROR("unable to reset ftdi device");
1928                 return ERROR_JTAG_INIT_FAILED;
1929         }
1930
1931         if (ftdi_set_latency_timer(&ftdic, ft2232_latency) < 0)
1932         {
1933                 LOG_ERROR("unable to set latency timer");
1934                 return ERROR_JTAG_INIT_FAILED;
1935         }
1936
1937         if (ftdi_get_latency_timer(&ftdic, &latency_timer) < 0)
1938         {
1939                 LOG_ERROR("unable to get latency timer");
1940                 return ERROR_JTAG_INIT_FAILED;
1941         }
1942         else
1943         {
1944                 LOG_DEBUG("current latency timer: %i", latency_timer);
1945         }
1946
1947         ftdi_set_bitmode(&ftdic, 0x0b, 2); /* ctx, JTAG I/O mask */
1948
1949         return ERROR_OK;
1950 }
1951
1952
1953 static int ft2232_purge_libftdi(void)
1954 {
1955         if (ftdi_usb_purge_buffers(&ftdic) < 0)
1956         {
1957                 LOG_ERROR("ftdi_purge_buffers: %s", ftdic.error_str);
1958                 return ERROR_JTAG_INIT_FAILED;
1959         }
1960
1961         return ERROR_OK;
1962 }
1963
1964
1965 #endif /* BUILD_FT2232_LIBFTDI == 1 */
1966
1967 static int ft2232_init(void)
1968 {
1969         u8  buf[1];
1970         int retval;
1971         u32 bytes_written;
1972         ft2232_layout_t* cur_layout = ft2232_layouts;
1973         int i;
1974
1975         if (tap_get_tms_path_len(TAP_IRPAUSE,TAP_IRPAUSE)==7)
1976         { 
1977                 LOG_DEBUG("ft2232 interface using 7 step jtag state transitions");
1978         }
1979         else
1980         {
1981                 LOG_DEBUG("ft2232 interface using shortest path jtag state transitions");
1982         
1983         }
1984         if ( (ft2232_layout == NULL) || (ft2232_layout[0] == 0) )
1985         {
1986                 ft2232_layout = "usbjtag";
1987                 LOG_WARNING("No ft2232 layout specified, using default 'usbjtag'");
1988         }
1989
1990         while (cur_layout->name)
1991         {
1992                 if (strcmp(cur_layout->name, ft2232_layout) == 0)
1993                 {
1994                         layout = cur_layout;
1995                         break;
1996                 }
1997                 cur_layout++;
1998         }
1999
2000         if (!layout)
2001         {
2002                 LOG_ERROR("No matching layout found for %s", ft2232_layout);
2003                 return ERROR_JTAG_INIT_FAILED;
2004         }
2005
2006         for (i = 0; 1; i++)
2007         {
2008                 /*
2009                  * "more indicates that there are more IDs to try, so we should
2010                  * not print an error for an ID mismatch (but for anything
2011                  * else, we should).
2012                  *
2013                  * try_more indicates that the error code returned indicates an
2014                  * ID mismatch (and nothing else) and that we should proceeed
2015                  * with the next ID pair.
2016                  */
2017                 int more     = ft2232_vid[i + 1] || ft2232_pid[i + 1];
2018                 int try_more = 0;
2019
2020 #if BUILD_FT2232_FTD2XX == 1
2021                 retval = ft2232_init_ftd2xx(ft2232_vid[i], ft2232_pid[i],
2022                                 more, &try_more);
2023 #elif BUILD_FT2232_LIBFTDI == 1
2024                 retval = ft2232_init_libftdi(ft2232_vid[i], ft2232_pid[i],
2025                                 more, &try_more);
2026 #endif
2027                 if (retval >= 0)
2028                         break;
2029                 if (!more || !try_more)
2030                         return retval;
2031         }
2032
2033         ft2232_buffer_size = 0;
2034         ft2232_buffer = malloc(FT2232_BUFFER_SIZE);
2035
2036         if (layout->init() != ERROR_OK)
2037                 return ERROR_JTAG_INIT_FAILED;
2038
2039         ft2232_speed(jtag_speed);
2040
2041         buf[0] = 0x85; /* Disconnect TDI/DO to TDO/DI for Loopback */
2042         if ( ( ( retval = ft2232_write(buf, 1, &bytes_written) ) != ERROR_OK ) || (bytes_written != 1) )
2043         {
2044                 LOG_ERROR("couldn't write to FT2232 to disable loopback");
2045                 return ERROR_JTAG_INIT_FAILED;
2046         }
2047
2048 #if BUILD_FT2232_FTD2XX == 1
2049         return ft2232_purge_ftd2xx();
2050 #elif BUILD_FT2232_LIBFTDI == 1
2051         return ft2232_purge_libftdi();
2052 #endif
2053
2054         return ERROR_OK;
2055 }
2056
2057
2058 static int usbjtag_init(void)
2059 {
2060         u8  buf[3];
2061         u32 bytes_written;
2062
2063         low_output    = 0x08;
2064         low_direction = 0x0b;
2065
2066         if (strcmp(ft2232_layout, "usbjtag") == 0)
2067         {
2068                 nTRST    = 0x10;
2069                 nTRSTnOE = 0x10;
2070                 nSRST    = 0x40;
2071                 nSRSTnOE = 0x40;
2072         }
2073         else if (strcmp(ft2232_layout, "signalyzer") == 0)
2074         {
2075                 nTRST    = 0x10;
2076                 nTRSTnOE = 0x10;
2077                 nSRST    = 0x20;
2078                 nSRSTnOE = 0x20;
2079         }
2080         else if (strcmp(ft2232_layout, "evb_lm3s811") == 0)
2081         {
2082                 nTRST = 0x0;
2083                 nTRSTnOE = 0x00;
2084                 nSRST = 0x20;
2085                 nSRSTnOE = 0x20;
2086                 low_output    = 0x88;
2087                 low_direction = 0x8b;
2088         }
2089         else
2090         {
2091                 LOG_ERROR("BUG: usbjtag_init called for unknown layout '%s'", ft2232_layout);
2092                 return ERROR_JTAG_INIT_FAILED;
2093         }
2094
2095         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2096         {
2097                 low_direction &= ~nTRSTnOE; /* nTRST input */
2098                 low_output    &= ~nTRST;    /* nTRST = 0 */
2099         }
2100         else
2101         {
2102                 low_direction |= nTRSTnOE;  /* nTRST output */
2103                 low_output    |= nTRST;     /* nTRST = 1 */
2104         }
2105
2106         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2107         {
2108                 low_direction |= nSRSTnOE;  /* nSRST output */
2109                 low_output    |= nSRST;     /* nSRST = 1 */
2110         }
2111         else
2112         {
2113                 low_direction &= ~nSRSTnOE; /* nSRST input */
2114                 low_output    &= ~nSRST;    /* nSRST = 0 */
2115         }
2116
2117         /* initialize low byte for jtag */
2118         buf[0] = 0x80;          /* command "set data bits low byte" */
2119         buf[1] = low_output;    /* value (TMS=1,TCK=0, TDI=0, xRST high) */
2120         buf[2] = low_direction; /* dir (output=1), TCK/TDI/TMS=out, TDO=in */
2121         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2122
2123         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2124         {
2125                 LOG_ERROR("couldn't initialize FT2232 with 'USBJTAG' layout");
2126                 return ERROR_JTAG_INIT_FAILED;
2127         }
2128
2129         return ERROR_OK;
2130 }
2131
2132
2133 static int axm0432_jtag_init(void)
2134 {
2135         u8  buf[3];
2136         u32 bytes_written;
2137
2138         low_output    = 0x08;
2139         low_direction = 0x2b;
2140
2141         /* initialize low byte for jtag */
2142         buf[0] = 0x80;          /* command "set data bits low byte" */
2143         buf[1] = low_output;    /* value (TMS=1,TCK=0, TDI=0, nOE=0) */
2144         buf[2] = low_direction; /* dir (output=1), TCK/TDI/TMS=out, TDO=in, nOE=out */
2145         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2146
2147         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2148         {
2149                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2150                 return ERROR_JTAG_INIT_FAILED;
2151         }
2152
2153         if (strcmp(layout->name, "axm0432_jtag") == 0)
2154         {
2155                 nTRST    = 0x08;
2156                 nTRSTnOE = 0x0;     /* No output enable for TRST*/
2157                 nSRST    = 0x04;
2158                 nSRSTnOE = 0x0;     /* No output enable for SRST*/
2159         }
2160         else
2161         {
2162                 LOG_ERROR("BUG: axm0432_jtag_init called for non axm0432 layout");
2163                 exit(-1);
2164         }
2165
2166         high_output    = 0x0;
2167         high_direction = 0x0c;
2168
2169         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2170         {
2171                 LOG_ERROR("can't set nTRSTOE to push-pull on the Dicarlo jtag");
2172         }
2173         else
2174         {
2175                 high_output |= nTRST;
2176         }
2177
2178         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2179         {
2180                 LOG_ERROR("can't set nSRST to push-pull on the Dicarlo jtag");
2181         }
2182         else
2183         {
2184                 high_output |= nSRST;
2185         }
2186
2187         /* initialize high port */
2188         buf[0] = 0x82;              /* command "set data bits high byte" */
2189         buf[1] = high_output;       /* value */
2190         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2191         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2192
2193         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2194         {
2195                 LOG_ERROR("couldn't initialize FT2232 with 'Dicarlo' layout");
2196                 return ERROR_JTAG_INIT_FAILED;
2197         }
2198
2199         return ERROR_OK;
2200 }
2201
2202
2203 static int jtagkey_init(void)
2204 {
2205         u8  buf[3];
2206         u32 bytes_written;
2207
2208         low_output    = 0x08;
2209         low_direction = 0x1b;
2210
2211         /* initialize low byte for jtag */
2212         buf[0] = 0x80;          /* command "set data bits low byte" */
2213         buf[1] = low_output;    /* value (TMS=1,TCK=0, TDI=0, nOE=0) */
2214         buf[2] = low_direction; /* dir (output=1), TCK/TDI/TMS=out, TDO=in, nOE=out */
2215         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2216
2217         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2218         {
2219                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2220                 return ERROR_JTAG_INIT_FAILED;
2221         }
2222
2223         if (strcmp(layout->name, "jtagkey") == 0)
2224         {
2225                 nTRST    = 0x01;
2226                 nTRSTnOE = 0x4;
2227                 nSRST    = 0x02;
2228                 nSRSTnOE = 0x08;
2229         }
2230         else if ( (strcmp(layout->name, "jtagkey_prototype_v1") == 0)
2231                          || (strcmp(layout->name, "oocdlink") == 0) )
2232         {
2233                 nTRST    = 0x02;
2234                 nTRSTnOE = 0x1;
2235                 nSRST    = 0x08;
2236                 nSRSTnOE = 0x04;
2237         }
2238         else
2239         {
2240                 LOG_ERROR("BUG: jtagkey_init called for non jtagkey layout");
2241                 exit(-1);
2242         }
2243
2244         high_output    = 0x0;
2245         high_direction = 0x0f;
2246
2247         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2248         {
2249                 high_output |= nTRSTnOE;
2250                 high_output &= ~nTRST;
2251         }
2252         else
2253         {
2254                 high_output &= ~nTRSTnOE;
2255                 high_output |= nTRST;
2256         }
2257
2258         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2259         {
2260                 high_output &= ~nSRSTnOE;
2261                 high_output |= nSRST;
2262         }
2263         else
2264         {
2265                 high_output |= nSRSTnOE;
2266                 high_output &= ~nSRST;
2267         }
2268
2269         /* initialize high port */
2270         buf[0] = 0x82;              /* command "set data bits high byte" */
2271         buf[1] = high_output;       /* value */
2272         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2273         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2274
2275         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2276         {
2277                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2278                 return ERROR_JTAG_INIT_FAILED;
2279         }
2280
2281         return ERROR_OK;
2282 }
2283
2284
2285 static int olimex_jtag_init(void)
2286 {
2287         u8  buf[3];
2288         u32 bytes_written;
2289
2290         low_output    = 0x08;
2291         low_direction = 0x1b;
2292
2293         /* initialize low byte for jtag */
2294         buf[0] = 0x80;          /* command "set data bits low byte" */
2295         buf[1] = low_output;    /* value (TMS=1,TCK=0, TDI=0, nOE=0) */
2296         buf[2] = low_direction; /* dir (output=1), TCK/TDI/TMS=out, TDO=in, nOE=out */
2297         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2298
2299         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2300         {
2301                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2302                 return ERROR_JTAG_INIT_FAILED;
2303         }
2304
2305         nTRST    = 0x01;
2306         nTRSTnOE = 0x4;
2307         nSRST    = 0x02;
2308         nSRSTnOE = 0x00; /* no output enable for nSRST */
2309
2310         high_output    = 0x0;
2311         high_direction = 0x0f;
2312
2313         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2314         {
2315                 high_output |= nTRSTnOE;
2316                 high_output &= ~nTRST;
2317         }
2318         else
2319         {
2320                 high_output &= ~nTRSTnOE;
2321                 high_output |= nTRST;
2322         }
2323
2324         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2325         {
2326                 LOG_ERROR("can't set nSRST to push-pull on the Olimex ARM-USB-OCD");
2327         }
2328         else
2329         {
2330                 high_output &= ~nSRST;
2331         }
2332
2333         /* turn red LED on */
2334         high_output |= 0x08;
2335
2336         /* initialize high port */
2337         buf[0] = 0x82;              /* command "set data bits high byte" */
2338         buf[1] = high_output;       /* value */
2339         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2340         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2341
2342         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2343         {
2344                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2345                 return ERROR_JTAG_INIT_FAILED;
2346         }
2347
2348         return ERROR_OK;
2349 }
2350
2351
2352 static int flyswatter_init(void)
2353 {
2354         u8  buf[3];
2355         u32 bytes_written;
2356
2357         low_output    = 0x18;
2358         low_direction = 0xfb;
2359
2360         /* initialize low byte for jtag */
2361         buf[0] = 0x80;          /* command "set data bits low byte" */
2362         buf[1] = low_output;    /* value (TMS=1,TCK=0, TDI=0, nOE=0) */
2363         buf[2] = low_direction; /* dir (output=1), TCK/TDI/TMS=out, TDO=in, nOE[12]=out, n[ST]srst=out */
2364         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2365
2366         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2367         {
2368                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2369                 return ERROR_JTAG_INIT_FAILED;
2370         }
2371
2372         nTRST    = 0x10;
2373         nTRSTnOE = 0x0;     /* not output enable for nTRST */
2374         nSRST    = 0x20;
2375         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2376
2377         high_output    = 0x00;
2378         high_direction = 0x0c;
2379
2380         /* turn red LED3 on, LED2 off */
2381         high_output |= 0x08;
2382
2383         /* initialize high port */
2384         buf[0] = 0x82;              /* command "set data bits high byte" */
2385         buf[1] = high_output;       /* value */
2386         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2387         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2388
2389         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2390         {
2391                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2392                 return ERROR_JTAG_INIT_FAILED;
2393         }
2394
2395         return ERROR_OK;
2396 }
2397
2398
2399 static int turtle_init(void)
2400 {
2401         u8  buf[3];
2402         u32 bytes_written;
2403
2404         low_output    = 0x08;
2405         low_direction = 0x5b;
2406
2407         /* initialize low byte for jtag */
2408         buf[0] = 0x80;          /* command "set data bits low byte" */
2409         buf[1] = low_output;    /* value (TMS=1,TCK=0, TDI=0, nOE=0) */
2410         buf[2] = low_direction; /* dir (output=1), TCK/TDI/TMS=out, TDO=in, nOE=out */
2411         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2412
2413         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2414         {
2415                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2416                 return ERROR_JTAG_INIT_FAILED;
2417         }
2418
2419         nSRST = 0x40;
2420
2421         high_output    = 0x00;
2422         high_direction = 0x0C;
2423
2424         /* initialize high port */
2425         buf[0] = 0x82; /* command "set data bits high byte" */
2426         buf[1] = high_output;
2427         buf[2] = high_direction;
2428         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2429
2430         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2431         {
2432                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2433                 return ERROR_JTAG_INIT_FAILED;
2434         }
2435
2436         return ERROR_OK;
2437 }
2438
2439
2440 static int comstick_init(void)
2441 {
2442         u8  buf[3];
2443         u32 bytes_written;
2444
2445         low_output    = 0x08;
2446         low_direction = 0x0b;
2447
2448         /* initialize low byte for jtag */
2449         buf[0] = 0x80;          /* command "set data bits low byte" */
2450         buf[1] = low_output;    /* value (TMS=1,TCK=0, TDI=0, nOE=0) */
2451         buf[2] = low_direction; /* dir (output=1), TCK/TDI/TMS=out, TDO=in, nOE=out */
2452         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2453
2454         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2455         {
2456                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2457                 return ERROR_JTAG_INIT_FAILED;
2458         }
2459
2460         nTRST    = 0x01;
2461         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2462         nSRST    = 0x02;
2463         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2464
2465         high_output    = 0x03;
2466         high_direction = 0x03;
2467
2468         /* initialize high port */
2469         buf[0] = 0x82; /* command "set data bits high byte" */
2470         buf[1] = high_output;
2471         buf[2] = high_direction;
2472         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2473
2474         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2475         {
2476                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2477                 return ERROR_JTAG_INIT_FAILED;
2478         }
2479
2480         return ERROR_OK;
2481 }
2482
2483
2484 static int stm32stick_init(void)
2485 {
2486         u8  buf[3];
2487         u32 bytes_written;
2488
2489         low_output    = 0x88;
2490         low_direction = 0x8b;
2491
2492         /* initialize low byte for jtag */
2493         buf[0] = 0x80;          /* command "set data bits low byte" */
2494         buf[1] = low_output;    /* value (TMS=1,TCK=0, TDI=0, nOE=0) */
2495         buf[2] = low_direction; /* dir (output=1), TCK/TDI/TMS=out, TDO=in, nOE=out */
2496         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2497
2498         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2499         {
2500                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2501                 return ERROR_JTAG_INIT_FAILED;
2502         }
2503
2504         nTRST    = 0x01;
2505         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2506         nSRST    = 0x80;
2507         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2508
2509         high_output    = 0x01;
2510         high_direction = 0x03;
2511
2512         /* initialize high port */
2513         buf[0] = 0x82; /* command "set data bits high byte" */
2514         buf[1] = high_output;
2515         buf[2] = high_direction;
2516         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2517
2518         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) )
2519         {
2520                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2521                 return ERROR_JTAG_INIT_FAILED;
2522         }
2523
2524         return ERROR_OK;
2525 }
2526
2527
2528 static int sheevaplug_init(void)
2529 {
2530         u8 buf[3];
2531         u32 bytes_written;
2532
2533         low_output = 0x08;
2534         low_direction = 0x1b;
2535
2536         /* initialize low byte for jtag */
2537         buf[0] = 0x80; /* command "set data bits low byte" */
2538         buf[1] = low_output; /* value (TMS=1,TCK=0, TDI=0, nOE=0) */
2539         buf[2] = low_direction; /* dir (output=1), TCK/TDI/TMS=out, TDO=in */
2540         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2541
2542         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2543         {
2544                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2545                 return ERROR_JTAG_INIT_FAILED;
2546         }
2547
2548         nTRSTnOE = 0x1;
2549         nTRST = 0x02;
2550         nSRSTnOE = 0x4;
2551         nSRST = 0x08;
2552
2553         high_output = 0x0;
2554         high_direction = 0x0f;
2555
2556         /* nTRST is always push-pull */
2557         high_output &= ~nTRSTnOE;
2558         high_output |= nTRST;
2559
2560         /* nSRST is always open-drain */
2561         high_output |= nSRSTnOE;
2562         high_output &= ~nSRST;
2563
2564         /* initialize high port */
2565         buf[0] = 0x82; /* command "set data bits high byte" */
2566         buf[1] = high_output; /* value */
2567         buf[2] = high_direction;   /* all outputs - xRST */
2568         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2569
2570         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2571         {
2572                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2573                 return ERROR_JTAG_INIT_FAILED;
2574         }
2575
2576         return ERROR_OK;
2577 }
2578
2579 static void olimex_jtag_blink(void)
2580 {
2581         /* Olimex ARM-USB-OCD has a LED connected to ACBUS3
2582          * ACBUS3 is bit 3 of the GPIOH port
2583          */
2584         if (high_output & 0x08)
2585         {
2586                 /* set port pin high */
2587                 high_output &= 0x07;
2588         }
2589         else
2590         {
2591                 /* set port pin low */
2592                 high_output |= 0x08;
2593         }
2594
2595         buffer_write( 0x82 );
2596         buffer_write( high_output );
2597         buffer_write( high_direction );
2598 }
2599
2600
2601 static void flyswatter_jtag_blink(void)
2602 {
2603         /*
2604          * Flyswatter has two LEDs connected to ACBUS2 and ACBUS3
2605          */
2606         high_output ^= 0x0c;
2607
2608         buffer_write( 0x82 );
2609         buffer_write( high_output );
2610         buffer_write( high_direction );
2611 }
2612
2613
2614 static void turtle_jtag_blink(void)
2615 {
2616         /*
2617          * Turtelizer2 has two LEDs connected to ACBUS2 and ACBUS3
2618          */
2619         if (high_output & 0x08)
2620         {
2621                 high_output = 0x04;
2622         }
2623         else
2624         {
2625                 high_output = 0x08;
2626         }
2627
2628         buffer_write( 0x82 );
2629         buffer_write( high_output );
2630         buffer_write( high_direction );
2631 }
2632
2633
2634 static int ft2232_quit(void)
2635 {
2636 #if BUILD_FT2232_FTD2XX == 1
2637         FT_STATUS status;
2638
2639         status = FT_Close(ftdih);
2640 #elif BUILD_FT2232_LIBFTDI == 1
2641         ftdi_usb_close(&ftdic);
2642
2643         ftdi_deinit(&ftdic);
2644 #endif
2645
2646         free(ft2232_buffer);
2647         ft2232_buffer = NULL;
2648
2649         return ERROR_OK;
2650 }
2651
2652
2653 static int ft2232_handle_device_desc_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2654 {
2655         char *cp;
2656         char buf[200];
2657         if (argc == 1)
2658         {
2659                 ft2232_device_desc = strdup(args[0]);
2660                 cp = strchr( ft2232_device_desc, 0 );
2661                 // under Win32, the FTD2XX driver appends an "A" to the end
2662                 // of the description, this examines the given desc
2663                 // and creates the 'missing' _A or non_A variable.
2664                 if( (cp[-1] == 'A') && (cp[-2]==' ') ){
2665                         // it was, so make this the "A" version.
2666                         ft2232_device_desc_A = ft2232_device_desc;
2667                         // and *CREATE* the non-A version.
2668                         strcpy( buf, ft2232_device_desc );
2669                         cp = strchr( buf, 0 );
2670                         cp[-2] = 0;
2671                         ft2232_device_desc =  strdup( buf );
2672                 } else {
2673                         // <space>A not defined
2674                         // so create it
2675                         sprintf( buf, "%s A", ft2232_device_desc );
2676                         ft2232_device_desc_A = strdup( buf );
2677                 }
2678         }
2679         else
2680         {
2681                 LOG_ERROR("expected exactly one argument to ft2232_device_desc <description>");
2682         }
2683
2684         return ERROR_OK;
2685 }
2686
2687
2688 static int ft2232_handle_serial_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2689 {
2690         if (argc == 1)
2691         {
2692                 ft2232_serial = strdup(args[0]);
2693         }
2694         else
2695         {
2696                 LOG_ERROR("expected exactly one argument to ft2232_serial <serial-number>");
2697         }
2698
2699         return ERROR_OK;
2700 }
2701
2702
2703 static int ft2232_handle_layout_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2704 {
2705         if (argc == 0)
2706                 return ERROR_OK;
2707
2708         ft2232_layout = malloc(strlen(args[0]) + 1);
2709         strcpy(ft2232_layout, args[0]);
2710
2711         return ERROR_OK;
2712 }
2713
2714
2715 static int ft2232_handle_vid_pid_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2716 {
2717         int i;
2718
2719         if (argc > MAX_USB_IDS * 2)
2720         {
2721                 LOG_WARNING("ignoring extra IDs in ft2232_vid_pid "
2722                                         "(maximum is %d pairs)", MAX_USB_IDS);
2723                 argc = MAX_USB_IDS * 2;
2724         }
2725         if ( argc < 2 || (argc & 1) )
2726         {
2727                 LOG_WARNING("incomplete ft2232_vid_pid configuration directive");
2728                 if (argc < 2)
2729                         return ERROR_OK;
2730         }
2731
2732         for (i = 0; i + 1 < argc; i += 2)
2733         {
2734                 ft2232_vid[i >> 1] = strtol(args[i], NULL, 0);
2735                 ft2232_pid[i >> 1] = strtol(args[i + 1], NULL, 0);
2736         }
2737
2738         /*
2739          * Explicitly terminate, in case there are multiples instances of
2740          * ft2232_vid_pid.
2741          */
2742         ft2232_vid[i >> 1] = ft2232_pid[i >> 1] = 0;
2743
2744         return ERROR_OK;
2745 }
2746
2747
2748 static int ft2232_handle_latency_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2749 {
2750         if (argc == 1)
2751         {
2752                 ft2232_latency = atoi(args[0]);
2753         }
2754         else
2755         {
2756                 LOG_ERROR("expected exactly one argument to ft2232_latency <ms>");
2757         }
2758
2759         return ERROR_OK;
2760 }
2761
2762
2763 static int ft2232_stableclocks(int num_cycles, jtag_command_t* cmd)
2764 {
2765         int retval = 0;
2766
2767         /* 7 bits of either ones or zeros. */
2768         u8  tms = (tap_get_state() == TAP_RESET ? 0x7F : 0x00);
2769
2770         while (num_cycles > 0)
2771         {
2772                 /* the command 0x4b, "Clock Data to TMS/CS Pin (no Read)" handles
2773                  * at most 7 bits per invocation.  Here we invoke it potentially
2774                  * several times.
2775                  */
2776                 int bitcount_per_command = (num_cycles > 7) ? 7 : num_cycles;
2777
2778                 if (ft2232_buffer_size + 3 >= FT2232_BUFFER_SIZE)
2779                 {
2780                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
2781                                 retval = ERROR_JTAG_QUEUE_FAILED;
2782
2783                         first_unsent = cmd;
2784                 }
2785
2786                 /* there are no state transitions in this code, so omit state tracking */
2787
2788                 /* command "Clock Data to TMS/CS Pin (no Read)" */
2789                 buffer_write( 0x4b );
2790
2791                 /* scan 7 bit */
2792                 buffer_write( bitcount_per_command - 1 );
2793
2794                 /* TMS data bits are either all zeros or ones to stay in the current stable state */
2795                 buffer_write( tms );
2796
2797                 require_send = 1;
2798
2799                 num_cycles -= bitcount_per_command;
2800         }
2801
2802         return retval;
2803 }
2804
2805
2806 /* ---------------------------------------------------------------------
2807  * Support for IceBear JTAG adapter from Section5:
2808  *      http://section5.ch/icebear
2809  *
2810  * Author: Sten, debian@sansys-electronic.com
2811  */
2812
2813 /* Icebear pin layout
2814  *
2815  * ADBUS5 (nEMU) nSRST  | 2   1|        GND (10k->VCC)
2816  * GND GND              | 4   3|        n.c.
2817  * ADBUS3 TMS           | 6   5|        ADBUS6 VCC
2818  * ADBUS0 TCK           | 8   7|        ADBUS7 (GND)
2819  * ADBUS4 nTRST         |10   9|        ACBUS0 (GND)
2820  * ADBUS1 TDI           |12  11|        ACBUS1 (GND)
2821  * ADBUS2 TDO           |14  13|        GND GND
2822  *
2823  * ADBUS0 O L TCK               ACBUS0 GND
2824  * ADBUS1 O L TDI               ACBUS1 GND
2825  * ADBUS2 I   TDO               ACBUS2 n.c.
2826  * ADBUS3 O H TMS               ACBUS3 n.c.
2827  * ADBUS4 O H nTRST
2828  * ADBUS5 O H nSRST
2829  * ADBUS6 -   VCC
2830  * ADBUS7 -   GND
2831  */
2832 static int icebear_jtag_init(void) {
2833         u8  buf[3];
2834         u32 bytes_written;
2835
2836         low_direction   = 0x0b; /* output: TCK TDI TMS; input: TDO */
2837         low_output      = 0x08; /* high: TMS; low: TCK TDI */
2838         nTRST           = 0x10;
2839         nSRST           = 0x20;
2840
2841         if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0) {
2842                 low_direction   &= ~nTRST;      /* nTRST high impedance */
2843         }
2844         else {
2845                 low_direction   |= nTRST;
2846                 low_output      |= nTRST;
2847         }
2848
2849         low_direction   |= nSRST;
2850         low_output      |= nSRST;
2851
2852         /* initialize low byte for jtag */
2853         buf[0] = 0x80;          /* command "set data bits low byte" */
2854         buf[1] = low_output;
2855         buf[2] = low_direction;
2856         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2857
2858         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) ) {
2859                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (low)");
2860                 return ERROR_JTAG_INIT_FAILED;
2861         }
2862
2863         high_output    = 0x0;
2864         high_direction = 0x00;
2865
2866
2867         /* initialize high port */
2868         buf[0] = 0x82;              /* command "set data bits high byte" */
2869         buf[1] = high_output;       /* value */
2870         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2871         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2872
2873         if ( ( ( ft2232_write(buf, 3, &bytes_written) ) != ERROR_OK ) || (bytes_written != 3) ) {
2874                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (high)");
2875                 return ERROR_JTAG_INIT_FAILED;
2876         }
2877
2878         return ERROR_OK;
2879 }
2880
2881 static void icebear_jtag_reset(int trst, int srst) {
2882
2883         if (trst == 1) {
2884                 low_direction   |= nTRST;
2885                 low_output      &= ~nTRST;
2886         }
2887         else if (trst == 0) {
2888                 if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0)
2889                         low_direction   &= ~nTRST;
2890                 else
2891                         low_output      |= nTRST;
2892         }
2893
2894         if (srst == 1) {
2895                 low_output &= ~nSRST;
2896         }
2897         else if (srst == 0) {
2898                 low_output |= nSRST;
2899         }
2900
2901         /* command "set data bits low byte" */
2902         buffer_write( 0x80 );
2903         buffer_write( low_output );
2904         buffer_write( low_direction );
2905
2906         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
2907 }