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