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