e570cbe983266a971f3beae93acfdcfc8a64a42c
[fw/openocd] / src / jtag / ft2232.c
1 /***************************************************************************
2 *   Copyright (C) 2009 by Øyvind Harboe                                   *
3 *       Øyvind Harboe <oyvind.harboe@zylin.com>                               *
4 *                                                                         *
5 *   Copyright (C) 2009 by SoftPLC Corporation.  http://softplc.com        *
6 *       Dick Hollenbeck <dick@softplc.com>                                    *
7 *                                                                         *
8 *   Copyright (C) 2004, 2006 by Dominic Rath                              *
9 *   Dominic.Rath@gmx.de                                                   *
10 *                                                                         *
11 *   Copyright (C) 2008 by Spencer Oliver                                  *
12 *   spen@spen-soft.co.uk                                                  *
13 *                                                                         *
14 *   This program is free software; you can redistribute it and/or modify  *
15 *   it under the terms of the GNU General Public License as published by  *
16 *   the Free Software Foundation; either version 2 of the License, or     *
17 *   (at your option) any later version.                                   *
18 *                                                                         *
19 *   This program is distributed in the hope that it will be useful,       *
20 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
21 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
22 *   GNU General Public License for more details.                          *
23 *                                                                         *
24 *   You should have received a copy of the GNU General Public License     *
25 *   along with this program; if not, write to the                         *
26 *   Free Software Foundation, Inc.,                                       *
27 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
28 ***************************************************************************/
29
30 /* This code uses information contained in the MPSSE specification which was
31  * found here:
32  * http://www.ftdichip.com/Documents/AppNotes/AN2232C-01_MPSSE_Cmnd.pdf
33  * Hereafter this is called the "MPSSE Spec".
34  *
35  * The datasheet for the ftdichip.com's FT2232D part is here:
36  * http://www.ftdichip.com/Documents/DataSheets/DS_FT2232D.pdf
37  */
38
39 #ifdef HAVE_CONFIG_H
40 #include "config.h"
41 #endif
42
43 /* project specific includes */
44 #include "interface.h"
45 #include "commands.h"
46 #include "time_support.h"
47
48 #if IS_CYGWIN == 1
49 #include <windows.h>
50 #endif
51
52 #include <assert.h>
53
54 #if (BUILD_FT2232_FTD2XX == 1 && BUILD_FT2232_LIBFTDI == 1)
55 #error "BUILD_FT2232_FTD2XX && BUILD_FT2232_LIBFTDI are mutually exclusive"
56 #elif (BUILD_FT2232_FTD2XX != 1 && BUILD_FT2232_LIBFTDI != 1)
57 #error "BUILD_FT2232_FTD2XX || BUILD_FT2232_LIBFTDI must be chosen"
58 #endif
59
60 /* FT2232 access library includes */
61 #if BUILD_FT2232_FTD2XX == 1
62 #include <ftd2xx.h>
63 #elif BUILD_FT2232_LIBFTDI == 1
64 #include <ftdi.h>
65 #endif
66
67 /* max TCK for the high speed devices 30000 kHz */
68 #define FTDI_2232H_4232H_MAX_TCK        30000
69 /* max TCK for the full speed devices 6000 kHz */
70 #define FTDI_2232C_MAX_TCK 6000
71 /* this speed value tells that RTCK is requested */
72 #define RTCK_SPEED -1
73
74 /*
75  * On my Athlon XP 1900+ EHCI host with FT2232H JTAG dongle I get read timeout
76  * errors with a retry count of 100. Increasing it solves the problem for me.
77  *      - Dimitar
78  *
79  * FIXME There's likely an issue with the usb_read_timeout from libftdi.
80  * Fix that (libusb? kernel? libftdi? here?) and restore the retry count
81  * to something sane.
82  */
83 #define LIBFTDI_READ_RETRY_COUNT                2000
84
85 #ifndef BUILD_FT2232_HIGHSPEED
86  #if BUILD_FT2232_FTD2XX == 1
87         enum { FT_DEVICE_2232H = 6, FT_DEVICE_4232H };
88  #elif BUILD_FT2232_LIBFTDI == 1
89         enum { TYPE_2232H = 4, TYPE_4232H = 5 };
90  #endif
91 #endif
92
93 static int ft2232_execute_queue(void);
94 static int ft2232_speed(int speed);
95 static int ft2232_speed_div(int speed, int* khz);
96 static int ft2232_khz(int khz, int* jtag_speed);
97 static int ft2232_register_commands(struct command_context_s* cmd_ctx);
98 static int ft2232_init(void);
99 static int ft2232_quit(void);
100
101 static int ft2232_handle_device_desc_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
102 static int ft2232_handle_serial_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
103 static int ft2232_handle_layout_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
104 static int ft2232_handle_vid_pid_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
105 static int ft2232_handle_latency_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
106
107 /**
108  * Send out \a num_cycles on the TCK line while the TAP(s) are in a
109  * stable state.  Calling code must ensure that current state is stable,
110  * that verification is not done in here.
111  *
112  * @param num_cycles The number of clocks cycles to send.
113  * @param cmd The command to send.
114  *
115  * @returns ERROR_OK on success, or ERROR_JTAG_QUEUE_FAILED on failure.
116  */
117 static int ft2232_stableclocks(int num_cycles, jtag_command_t* cmd);
118
119 static char *       ft2232_device_desc_A = NULL;
120 static char*        ft2232_device_desc = NULL;
121 static char*        ft2232_serial  = NULL;
122 static char*        ft2232_layout  = NULL;
123 static uint8_t          ft2232_latency = 2;
124 static unsigned         ft2232_max_tck = FTDI_2232C_MAX_TCK;
125
126 #define MAX_USB_IDS 8
127 /* vid = pid = 0 marks the end of the list */
128 static uint16_t ft2232_vid[MAX_USB_IDS + 1] = { 0x0403, 0 };
129 static uint16_t ft2232_pid[MAX_USB_IDS + 1] = { 0x6010, 0 };
130
131 typedef struct ft2232_layout_s
132 {
133         char* name;
134         int (*init)(void);
135         void (*reset)(int trst, int srst);
136         void (*blink)(void);
137 } ft2232_layout_t;
138
139 /* init procedures for supported layouts */
140 static int usbjtag_init(void);
141 static int jtagkey_init(void);
142 static int olimex_jtag_init(void);
143 static int flyswatter_init(void);
144 static int turtle_init(void);
145 static int comstick_init(void);
146 static int stm32stick_init(void);
147 static int axm0432_jtag_init(void);
148 static int sheevaplug_init(void);
149 static int icebear_jtag_init(void);
150 static int cortino_jtag_init(void);
151 static int signalyzer_h_init(void);
152
153 /* reset procedures for supported layouts */
154 static void usbjtag_reset(int trst, int srst);
155 static void jtagkey_reset(int trst, int srst);
156 static void olimex_jtag_reset(int trst, int srst);
157 static void flyswatter_reset(int trst, int srst);
158 static void turtle_reset(int trst, int srst);
159 static void comstick_reset(int trst, int srst);
160 static void stm32stick_reset(int trst, int srst);
161 static void axm0432_jtag_reset(int trst, int srst);
162 static void sheevaplug_reset(int trst, int srst);
163 static void icebear_jtag_reset(int trst, int srst);
164 static void signalyzer_h_reset(int trst, int srst);
165
166 /* blink procedures for layouts that support a blinking led */
167 static void olimex_jtag_blink(void);
168 static void flyswatter_jtag_blink(void);
169 static void turtle_jtag_blink(void);
170 static void signalyzer_h_blink(void);
171
172 static const ft2232_layout_t  ft2232_layouts[] =
173 {
174         { "usbjtag",              usbjtag_init,              usbjtag_reset,      NULL                    },
175         { "jtagkey",              jtagkey_init,              jtagkey_reset,      NULL                    },
176         { "jtagkey_prototype_v1", jtagkey_init,              jtagkey_reset,      NULL                    },
177         { "oocdlink",             jtagkey_init,              jtagkey_reset,      NULL                    },
178         { "signalyzer",           usbjtag_init,              usbjtag_reset,      NULL                    },
179         { "evb_lm3s811",          usbjtag_init,              usbjtag_reset,      NULL                    },
180         { "luminary_icdi",        usbjtag_init,              usbjtag_reset,      NULL                    },
181         { "olimex-jtag",          olimex_jtag_init,          olimex_jtag_reset,  olimex_jtag_blink       },
182         { "flyswatter",           flyswatter_init,           flyswatter_reset,   flyswatter_jtag_blink   },
183         { "turtelizer2",          turtle_init,               turtle_reset,       turtle_jtag_blink       },
184         { "comstick",             comstick_init,             comstick_reset,     NULL                    },
185         { "stm32stick",           stm32stick_init,           stm32stick_reset,   NULL                    },
186         { "axm0432_jtag",         axm0432_jtag_init,         axm0432_jtag_reset, NULL                    },
187         { "sheevaplug",           sheevaplug_init,           sheevaplug_reset,   NULL                    },
188         { "icebear",              icebear_jtag_init,         icebear_jtag_reset, NULL                    },
189         { "cortino",              cortino_jtag_init,         comstick_reset, NULL                        },
190         { "signalyzer-h",         signalyzer_h_init,         signalyzer_h_reset, signalyzer_h_blink      },
191         { NULL,                   NULL,                      NULL,               NULL                    },
192 };
193
194 static uint8_t                  nTRST, nTRSTnOE, nSRST, nSRSTnOE;
195
196 static const ft2232_layout_t *layout;
197 static uint8_t                  low_output     = 0x0;
198 static uint8_t                  low_direction  = 0x0;
199 static uint8_t                  high_output    = 0x0;
200 static uint8_t                  high_direction = 0x0;
201
202 #if BUILD_FT2232_FTD2XX == 1
203 static FT_HANDLE        ftdih = NULL;
204 static FT_DEVICE        ftdi_device = 0;
205 #elif BUILD_FT2232_LIBFTDI == 1
206 static struct ftdi_context ftdic;
207 static enum ftdi_chip_type ftdi_device;
208 #endif
209
210 static jtag_command_t* first_unsent;        /* next command that has to be sent */
211 static int             require_send;
212
213 /*      http://urjtag.wiki.sourceforge.net/Cable + FT2232 says:
214
215         "There is a significant difference between libftdi and libftd2xx. The latter
216         one allows to schedule up to 64*64 bytes of result data while libftdi fails
217         with more than 4*64. As a consequence, the FT2232 driver is forced to
218         perform around 16x more USB transactions for long command streams with TDO
219         capture when running with libftdi."
220
221         No idea how we get
222         #define FT2232_BUFFER_SIZE 131072
223         a comment would have been nice.
224 */
225
226 #define FT2232_BUFFER_SIZE 131072
227
228 static uint8_t*             ft2232_buffer = NULL;
229 static int             ft2232_buffer_size  = 0;
230 static int             ft2232_read_pointer = 0;
231 static int             ft2232_expect_read  = 0;
232
233 /**
234  * Function buffer_write
235  * writes a byte into the byte buffer, "ft2232_buffer", which must be sent later.
236  * @param val is the byte to send.
237  */
238 static inline void buffer_write(uint8_t val)
239 {
240         assert(ft2232_buffer);
241         assert((unsigned) ft2232_buffer_size < (unsigned) FT2232_BUFFER_SIZE);
242         ft2232_buffer[ft2232_buffer_size++] = val;
243 }
244
245 /**
246  * Function buffer_read
247  * returns a byte from the byte buffer.
248  */
249 static inline uint8_t buffer_read(void)
250 {
251         assert(ft2232_buffer);
252         assert(ft2232_read_pointer < ft2232_buffer_size);
253         return ft2232_buffer[ft2232_read_pointer++];
254 }
255
256 /**
257  * Clocks out \a bit_count bits on the TMS line, starting with the least
258  * significant bit of tms_bits and progressing to more significant bits.
259  * Rigorous state transition logging is done here via tap_set_state().
260  *
261  * @param mpsse_cmd One of the MPSSE TMS oriented commands such as
262  *      0x4b or 0x6b.  See the MPSSE spec referenced above for their
263  *      functionality. The MPSSE command "Clock Data to TMS/CS Pin (no Read)"
264  *      is often used for this, 0x4b.
265  *
266  * @param tms_bits Holds the sequence of bits to send.
267  * @param tms_count Tells how many bits in the sequence.
268  * @param tdi_bit A single bit to pass on to TDI before the first TCK
269  *      cycle and held static for the duration of TMS clocking.
270  *
271  * See the MPSSE spec referenced above.
272  */
273 static void clock_tms(uint8_t mpsse_cmd, int tms_bits, int tms_count, bool tdi_bit)
274 {
275         uint8_t tms_byte;
276         int     i;
277         int     tms_ndx;                                /* bit index into tms_byte */
278
279         assert(tms_count > 0);
280
281         DEBUG_JTAG_IO("mpsse cmd=%02x, tms_bits = 0x%08x, bit_count=%d",
282                         mpsse_cmd, tms_bits, tms_count);
283
284         for (tms_byte = tms_ndx = i = 0;   i < tms_count;   ++i, tms_bits>>=1)
285         {
286                 bool bit = tms_bits & 1;
287
288                 if (bit)
289                         tms_byte |= (1 << tms_ndx);
290
291                 /* always do state transitions in public view */
292                 tap_set_state(tap_state_transition(tap_get_state(), bit));
293
294                 /*      we wrote a bit to tms_byte just above, increment bit index.  if bit was zero
295                         also increment.
296                 */
297                 ++tms_ndx;
298
299                 if (tms_ndx == 7  || i == tms_count-1)
300                 {
301                         buffer_write(mpsse_cmd);
302                         buffer_write(tms_ndx - 1);
303
304                         /*      Bit 7 of the byte is passed on to TDI/DO before the first TCK/SK of
305                                 TMS/CS and is held static for the duration of TMS/CS clocking.
306                         */
307                         buffer_write(tms_byte | (tdi_bit << 7));
308                 }
309         }
310 }
311
312 /**
313  * Function get_tms_buffer_requirements
314  * returns what clock_tms() will consume if called with
315  * same \a bit_count.
316  */
317 static inline int get_tms_buffer_requirements(int bit_count)
318 {
319         return ((bit_count + 6)/7) * 3;
320 }
321
322 /**
323  * Function move_to_state
324  * moves the TAP controller from the current state to a
325  * \a goal_state through a path given by tap_get_tms_path().  State transition
326  * logging is performed by delegation to clock_tms().
327  *
328  * @param goal_state is the destination state for the move.
329  */
330 static void move_to_state(tap_state_t goal_state)
331 {
332         tap_state_t     start_state = tap_get_state();
333
334         /*      goal_state is 1/2 of a tuple/pair of states which allow convenient
335                 lookup of the required TMS pattern to move to this state from the
336                 start state.
337         */
338
339         /* do the 2 lookups */
340         int tms_bits  = tap_get_tms_path(start_state, goal_state);
341         int tms_count = tap_get_tms_path_len(start_state, goal_state);
342
343         DEBUG_JTAG_IO("start=%s goal=%s", tap_state_name(start_state), tap_state_name(goal_state));
344
345         clock_tms(0x4b,  tms_bits, tms_count, 0);
346 }
347
348 jtag_interface_t ft2232_interface =
349 {
350         .name                   = "ft2232",
351         .execute_queue          = ft2232_execute_queue,
352         .speed                  = ft2232_speed,
353         .speed_div              = ft2232_speed_div,
354         .khz                    = ft2232_khz,
355         .register_commands      = ft2232_register_commands,
356         .init                   = ft2232_init,
357         .quit                   = ft2232_quit,
358 };
359
360 static int ft2232_write(uint8_t* buf, int size, uint32_t* bytes_written)
361 {
362 #if BUILD_FT2232_FTD2XX == 1
363         FT_STATUS status;
364         DWORD dw_bytes_written;
365         if ((status = FT_Write(ftdih, buf, size, &dw_bytes_written)) != FT_OK)
366         {
367                 *bytes_written = dw_bytes_written;
368                 LOG_ERROR("FT_Write returned: %lu", status);
369                 return ERROR_JTAG_DEVICE_ERROR;
370         }
371         else
372         {
373                 *bytes_written = dw_bytes_written;
374                 return ERROR_OK;
375         }
376 #elif BUILD_FT2232_LIBFTDI == 1
377         int retval;
378         if ((retval = ftdi_write_data(&ftdic, buf, size)) < 0)
379         {
380                 *bytes_written = 0;
381                 LOG_ERROR("ftdi_write_data: %s", ftdi_get_error_string(&ftdic));
382                 return ERROR_JTAG_DEVICE_ERROR;
383         }
384         else
385         {
386                 *bytes_written = retval;
387                 return ERROR_OK;
388         }
389 #endif
390 }
391
392 static int ft2232_read(uint8_t* buf, uint32_t size, uint32_t* bytes_read)
393 {
394 #if BUILD_FT2232_FTD2XX == 1
395         DWORD dw_bytes_read;
396         FT_STATUS status;
397         int timeout = 5;
398         *bytes_read = 0;
399
400         while ((*bytes_read < size) && timeout--)
401         {
402                 if ((status = FT_Read(ftdih, buf + *bytes_read, size -
403                                           *bytes_read, &dw_bytes_read)) != FT_OK)
404                 {
405                         *bytes_read = 0;
406                         LOG_ERROR("FT_Read returned: %lu", status);
407                         return ERROR_JTAG_DEVICE_ERROR;
408                 }
409                 *bytes_read += dw_bytes_read;
410         }
411
412 #elif BUILD_FT2232_LIBFTDI == 1
413         int retval;
414         int timeout = LIBFTDI_READ_RETRY_COUNT;
415         *bytes_read = 0;
416
417         while ((*bytes_read < size) && timeout--)
418         {
419                 if ((retval = ftdi_read_data(&ftdic, buf + *bytes_read, size - *bytes_read)) < 0)
420                 {
421                         *bytes_read = 0;
422                         LOG_ERROR("ftdi_read_data: %s", ftdi_get_error_string(&ftdic));
423                         return ERROR_JTAG_DEVICE_ERROR;
424                 }
425                 *bytes_read += retval;
426         }
427
428 #endif
429
430         if (*bytes_read < size)
431         {
432                 LOG_ERROR("couldn't read enough bytes from "
433                                 "FT2232 device (%i < %i)",
434                                 (unsigned)*bytes_read,
435                                 (unsigned)size);
436                 return ERROR_JTAG_DEVICE_ERROR;
437         }
438
439         return ERROR_OK;
440 }
441
442 static bool ft2232_device_is_highspeed(void)
443 {
444 #if BUILD_FT2232_FTD2XX == 1
445         return (ftdi_device == FT_DEVICE_2232H) || (ftdi_device == FT_DEVICE_4232H);
446 #elif BUILD_FT2232_LIBFTDI == 1
447         return (ftdi_device == TYPE_2232H || ftdi_device == TYPE_4232H);
448 #endif
449 }
450
451 /*
452  * Commands that only apply to the FT2232H and FT4232H devices.
453  * See chapter 6 in http://www.ftdichip.com/Documents/AppNotes/
454  * AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf
455  */
456
457 static int ft2232h_ft4232h_adaptive_clocking(bool enable)
458 {
459         uint8_t buf = enable ? 0x96 : 0x97;
460         LOG_DEBUG("%2.2x", buf);
461
462         uint32_t bytes_written;
463         int retval = ft2232_write(&buf, 1, &bytes_written);
464         if ((ERROR_OK != retval) || (bytes_written != 1))
465         {
466                 LOG_ERROR("couldn't write command to %s adaptive clocking"
467                         , enable ? "enable" : "disable");
468                 return retval;
469         }
470
471         return ERROR_OK;
472 }
473
474 /**
475  * Enable/disable the clk divide by 5 of the 60MHz master clock.
476  * This result in a JTAG clock speed range of 91.553Hz-6MHz
477  * respective 457.763Hz-30MHz.
478  */
479 static int ft2232h_ft4232h_clk_divide_by_5(bool enable)
480 {
481         uint32_t bytes_written;
482         uint8_t buf = enable ?  0x8b : 0x8a;
483         int retval = ft2232_write(&buf, 1, &bytes_written);
484         if ((ERROR_OK != retval) || (bytes_written != 1))
485         {
486                 LOG_ERROR("couldn't write command to %s clk divide by 5"
487                         , enable ? "enable" : "disable");
488                 return ERROR_JTAG_INIT_FAILED;
489         }
490         ft2232_max_tck = enable ? FTDI_2232C_MAX_TCK : FTDI_2232H_4232H_MAX_TCK;
491         LOG_INFO("max TCK change to: %u kHz", ft2232_max_tck);
492
493         return ERROR_OK;
494 }
495
496 static int ft2232_speed(int speed)
497 {
498         uint8_t buf[3];
499         int retval;
500         uint32_t bytes_written;
501
502         retval = ERROR_OK;
503         bool enable_adaptive_clocking = (RTCK_SPEED == speed);
504         if (ft2232_device_is_highspeed())
505                 retval = ft2232h_ft4232h_adaptive_clocking(enable_adaptive_clocking);
506         else if (enable_adaptive_clocking)
507         {
508                 LOG_ERROR("ft2232 device %lu does not support RTCK"
509                         , (long unsigned int)ftdi_device);
510                 return ERROR_FAIL;
511         }
512
513         if ((enable_adaptive_clocking) || (ERROR_OK != retval))
514                 return retval;
515
516         buf[0] = 0x86;                                  /* command "set divisor" */
517         buf[1] = speed & 0xff;                  /* valueL (0 = 6MHz, 1 = 3MHz, 2 = 2.0MHz, ...*/
518         buf[2] = (speed >> 8) & 0xff;   /* valueH */
519
520         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
521         if (((retval = ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
522         {
523                 LOG_ERROR("couldn't set FT2232 TCK speed");
524                 return retval;
525         }
526
527         return ERROR_OK;
528 }
529
530 static int ft2232_speed_div(int speed, int* khz)
531 {
532         /* Take a look in the FT2232 manual,
533          * AN2232C-01 Command Processor for
534          * MPSSE and MCU Host Bus. Chapter 3.8 */
535
536         *khz = (RTCK_SPEED == speed) ? 0 : ft2232_max_tck / (1 + speed);
537
538         return ERROR_OK;
539 }
540
541 static int ft2232_khz(int khz, int* jtag_speed)
542 {
543         if (khz == 0)
544         {
545                 if (ft2232_device_is_highspeed())
546                 {
547                         *jtag_speed = RTCK_SPEED;
548                         return ERROR_OK;
549                 }
550                 else
551                 {
552                         LOG_DEBUG("RCLK not supported");
553                         return ERROR_FAIL;
554                 }
555         }
556
557         /* Take a look in the FT2232 manual,
558          * AN2232C-01 Command Processor for
559          * MPSSE and MCU Host Bus. Chapter 3.8
560          *
561          * We will calc here with a multiplier
562          * of 10 for better rounding later. */
563
564         /* Calc speed, (ft2232_max_tck / khz) - 1 */
565         /* Use 65000 for better rounding */
566         *jtag_speed = ((ft2232_max_tck*10) / khz) - 10;
567
568         /* Add 0.9 for rounding */
569         *jtag_speed += 9;
570
571         /* Calc real speed */
572         *jtag_speed = *jtag_speed / 10;
573
574         /* Check if speed is greater than 0 */
575         if (*jtag_speed < 0)
576         {
577                 *jtag_speed = 0;
578         }
579
580         /* Check max value */
581         if (*jtag_speed > 0xFFFF)
582         {
583                 *jtag_speed = 0xFFFF;
584         }
585
586         return ERROR_OK;
587 }
588
589 static int ft2232_register_commands(struct command_context_s* cmd_ctx)
590 {
591         register_command(cmd_ctx, NULL, "ft2232_device_desc", ft2232_handle_device_desc_command,
592                         COMMAND_CONFIG, "the USB device description of the FTDI FT2232 device");
593         register_command(cmd_ctx, NULL, "ft2232_serial", ft2232_handle_serial_command,
594                         COMMAND_CONFIG, "the serial number of the FTDI FT2232 device");
595         register_command(cmd_ctx, NULL, "ft2232_layout", ft2232_handle_layout_command,
596                         COMMAND_CONFIG, "the layout of the FT2232 GPIO signals used to control output-enables and reset signals");
597         register_command(cmd_ctx, NULL, "ft2232_vid_pid", ft2232_handle_vid_pid_command,
598                         COMMAND_CONFIG, "the vendor ID and product ID of the FTDI FT2232 device");
599         register_command(cmd_ctx, NULL, "ft2232_latency", ft2232_handle_latency_command,
600                         COMMAND_CONFIG, "set the FT2232 latency timer to a new value");
601         return ERROR_OK;
602 }
603
604 static void ft2232_end_state(tap_state_t state)
605 {
606         if (tap_is_state_stable(state))
607                 tap_set_end_state(state);
608         else
609         {
610                 LOG_ERROR("BUG: %s is not a stable end state", tap_state_name(state));
611                 exit(-1);
612         }
613 }
614
615 static void ft2232_read_scan(enum scan_type type, uint8_t* buffer, int scan_size)
616 {
617         int num_bytes = (scan_size + 7) / 8;
618         int bits_left = scan_size;
619         int cur_byte  = 0;
620
621         while (num_bytes-- > 1)
622         {
623                 buffer[cur_byte++] = buffer_read();
624                 bits_left -= 8;
625         }
626
627         buffer[cur_byte] = 0x0;
628
629         /* There is one more partial byte left from the clock data in/out instructions */
630         if (bits_left > 1)
631         {
632                 buffer[cur_byte] = buffer_read() >> 1;
633         }
634         /* 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 */
635         buffer[cur_byte] = (buffer[cur_byte] | (((buffer_read()) << 1) & 0x80)) >> (8 - bits_left);
636 }
637
638 static void ft2232_debug_dump_buffer(void)
639 {
640         int i;
641         char line[256];
642         char* line_p = line;
643
644         for (i = 0; i < ft2232_buffer_size; i++)
645         {
646                 line_p += snprintf(line_p, 256 - (line_p - line), "%2.2x ", ft2232_buffer[i]);
647                 if (i % 16 == 15)
648                 {
649                         LOG_DEBUG("%s", line);
650                         line_p = line;
651                 }
652         }
653
654         if (line_p != line)
655                 LOG_DEBUG("%s", line);
656 }
657
658 static int ft2232_send_and_recv(jtag_command_t* first, jtag_command_t* last)
659 {
660         jtag_command_t* cmd;
661         uint8_t* buffer;
662         int scan_size;
663         enum scan_type  type;
664         int retval;
665         uint32_t bytes_written = 0;
666         uint32_t bytes_read = 0;
667
668 #ifdef _DEBUG_USB_IO_
669         struct timeval  start, inter, inter2, end;
670         struct timeval  d_inter, d_inter2, d_end;
671 #endif
672
673 #ifdef _DEBUG_USB_COMMS_
674         LOG_DEBUG("write buffer (size %i):", ft2232_buffer_size);
675         ft2232_debug_dump_buffer();
676 #endif
677
678 #ifdef _DEBUG_USB_IO_
679         gettimeofday(&start, NULL);
680 #endif
681
682         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
683         {
684                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
685                 return retval;
686         }
687
688 #ifdef _DEBUG_USB_IO_
689         gettimeofday(&inter, NULL);
690 #endif
691
692         if (ft2232_expect_read)
693         {
694                 /* FIXME this "timeout" is never changed ... */
695                 int timeout = LIBFTDI_READ_RETRY_COUNT;
696                 ft2232_buffer_size = 0;
697
698 #ifdef _DEBUG_USB_IO_
699                 gettimeofday(&inter2, NULL);
700 #endif
701
702                 if ((retval = ft2232_read(ft2232_buffer, ft2232_expect_read, &bytes_read)) != ERROR_OK)
703                 {
704                         LOG_ERROR("couldn't read from FT2232");
705                         return retval;
706                 }
707
708 #ifdef _DEBUG_USB_IO_
709                 gettimeofday(&end, NULL);
710
711                 timeval_subtract(&d_inter, &inter, &start);
712                 timeval_subtract(&d_inter2, &inter2, &start);
713                 timeval_subtract(&d_end, &end, &start);
714
715                 LOG_INFO("inter: %u.%06u, inter2: %u.%06u end: %u.%06u",
716                         (unsigned)d_inter.tv_sec, (unsigned)d_inter.tv_usec,
717                         (unsigned)d_inter2.tv_sec, (unsigned)d_inter2.tv_usec,
718                         (unsigned)d_end.tv_sec, (unsigned)d_end.tv_usec);
719 #endif
720
721                 ft2232_buffer_size = bytes_read;
722
723                 if (ft2232_expect_read != ft2232_buffer_size)
724                 {
725                         LOG_ERROR("ft2232_expect_read (%i) != "
726                                         "ft2232_buffer_size (%i) "
727                                         "(%i retries)",
728                                         ft2232_expect_read,
729                                         ft2232_buffer_size,
730                                         LIBFTDI_READ_RETRY_COUNT - timeout);
731                         ft2232_debug_dump_buffer();
732
733                         exit(-1);
734                 }
735
736 #ifdef _DEBUG_USB_COMMS_
737                 LOG_DEBUG("read buffer (%i retries): %i bytes",
738                                 LIBFTDI_READ_RETRY_COUNT - timeout,
739                                 ft2232_buffer_size);
740                 ft2232_debug_dump_buffer();
741 #endif
742         }
743
744         ft2232_expect_read  = 0;
745         ft2232_read_pointer = 0;
746
747         /* return ERROR_OK, unless a jtag_read_buffer returns a failed check
748          * that wasn't handled by a caller-provided error handler
749          */
750         retval = ERROR_OK;
751
752         cmd = first;
753         while (cmd != last)
754         {
755                 switch (cmd->type)
756                 {
757                 case JTAG_SCAN:
758                         type = jtag_scan_type(cmd->cmd.scan);
759                         if (type != SCAN_OUT)
760                         {
761                                 scan_size = jtag_scan_size(cmd->cmd.scan);
762                                 buffer    = calloc(CEIL(scan_size, 8), 1);
763                                 ft2232_read_scan(type, buffer, scan_size);
764                                 if (jtag_read_buffer(buffer, cmd->cmd.scan) != ERROR_OK)
765                                         retval = ERROR_JTAG_QUEUE_FAILED;
766                                 free(buffer);
767                         }
768                         break;
769
770                 default:
771                         break;
772                 }
773
774                 cmd = cmd->next;
775         }
776
777         ft2232_buffer_size = 0;
778
779         return retval;
780 }
781
782 /**
783  * Function ft2232_add_pathmove
784  * moves the TAP controller from the current state to a new state through the
785  * given path, where path is an array of tap_state_t's.
786  *
787  * @param path is an array of tap_stat_t which gives the states to traverse through
788  *   ending with the last state at path[num_states-1]
789  * @param num_states is the count of state steps to move through
790  */
791 static void ft2232_add_pathmove(tap_state_t* path, int num_states)
792 {
793         int state_count = 0;
794
795         assert((unsigned) num_states <= 32u);           /* tms_bits only holds 32 bits */
796
797         DEBUG_JTAG_IO("-");
798
799         /* this loop verifies that the path is legal and logs each state in the path */
800         while (num_states)
801         {
802                 unsigned char   tms_byte = 0;       /* zero this on each MPSSE batch */
803                 int             bit_count = 0;
804                 int             num_states_batch = num_states > 7 ? 7 : num_states;
805
806                 /* command "Clock Data to TMS/CS Pin (no Read)" */
807                 buffer_write(0x4b);
808
809                 /* number of states remaining */
810                 buffer_write(num_states_batch - 1);
811
812                 while (num_states_batch--) {
813                         /* either TMS=0 or TMS=1 must work ... */
814                         if (tap_state_transition(tap_get_state(), false)
815                                                 == path[state_count])
816                                 buf_set_u32(&tms_byte, bit_count++, 1, 0x0);
817                         else if (tap_state_transition(tap_get_state(), true)
818                                                 == path[state_count])
819                                 buf_set_u32(&tms_byte, bit_count++, 1, 0x1);
820
821                         /* ... or else the caller goofed BADLY */
822                         else {
823                                 LOG_ERROR("BUG: %s -> %s isn't a valid "
824                                                 "TAP state transition",
825                                         tap_state_name(tap_get_state()),
826                                         tap_state_name(path[state_count]));
827                                 exit(-1);
828                         }
829
830                         tap_set_state(path[state_count]);
831                         state_count++;
832                         num_states--;
833                 }
834
835                 buffer_write(tms_byte);
836         }
837         tap_set_end_state(tap_get_state());
838 }
839
840 static void ft2232_add_scan(bool ir_scan, enum scan_type type, uint8_t* buffer, int scan_size)
841 {
842         int num_bytes = (scan_size + 7) / 8;
843         int bits_left = scan_size;
844         int cur_byte  = 0;
845         int last_bit;
846
847         if (!ir_scan)
848         {
849                 if (tap_get_state() != TAP_DRSHIFT)
850                 {
851                         move_to_state(TAP_DRSHIFT);
852                 }
853         }
854         else
855         {
856                 if (tap_get_state() != TAP_IRSHIFT)
857                 {
858                         move_to_state(TAP_IRSHIFT);
859                 }
860         }
861
862         /* add command for complete bytes */
863         while (num_bytes > 1)
864         {
865                 int thisrun_bytes;
866                 if (type == SCAN_IO)
867                 {
868                         /* Clock Data Bytes In and Out LSB First */
869                         buffer_write(0x39);
870                         /* LOG_DEBUG("added TDI bytes (io %i)", num_bytes); */
871                 }
872                 else if (type == SCAN_OUT)
873                 {
874                         /* Clock Data Bytes Out on -ve Clock Edge LSB First (no Read) */
875                         buffer_write(0x19);
876                         /* LOG_DEBUG("added TDI bytes (o)"); */
877                 }
878                 else if (type == SCAN_IN)
879                 {
880                         /* Clock Data Bytes In on +ve Clock Edge LSB First (no Write) */
881                         buffer_write(0x28);
882                         /* LOG_DEBUG("added TDI bytes (i %i)", num_bytes); */
883                 }
884
885                 thisrun_bytes = (num_bytes > 65537) ? 65536 : (num_bytes - 1);
886                 num_bytes    -= thisrun_bytes;
887
888                 buffer_write((uint8_t) (thisrun_bytes - 1));
889                 buffer_write((uint8_t) ((thisrun_bytes - 1) >> 8));
890
891                 if (type != SCAN_IN)
892                 {
893                         /* add complete bytes */
894                         while (thisrun_bytes-- > 0)
895                         {
896                                 buffer_write(buffer[cur_byte++]);
897                                 bits_left -= 8;
898                         }
899                 }
900                 else /* (type == SCAN_IN) */
901                 {
902                         bits_left -= 8 * (thisrun_bytes);
903                 }
904         }
905
906         /* the most signifcant bit is scanned during TAP movement */
907         if (type != SCAN_IN)
908                 last_bit = (buffer[cur_byte] >> (bits_left - 1)) & 0x1;
909         else
910                 last_bit = 0;
911
912         /* process remaining bits but the last one */
913         if (bits_left > 1)
914         {
915                 if (type == SCAN_IO)
916                 {
917                         /* Clock Data Bits In and Out LSB First */
918                         buffer_write(0x3b);
919                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
920                 }
921                 else if (type == SCAN_OUT)
922                 {
923                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
924                         buffer_write(0x1b);
925                         /* LOG_DEBUG("added TDI bits (o)"); */
926                 }
927                 else if (type == SCAN_IN)
928                 {
929                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
930                         buffer_write(0x2a);
931                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
932                 }
933
934                 buffer_write(bits_left - 2);
935                 if (type != SCAN_IN)
936                         buffer_write(buffer[cur_byte]);
937         }
938
939         if ((ir_scan && (tap_get_end_state() == TAP_IRSHIFT))
940           || (!ir_scan && (tap_get_end_state() == TAP_DRSHIFT)))
941         {
942                 if (type == SCAN_IO)
943                 {
944                         /* Clock Data Bits In and Out LSB First */
945                         buffer_write(0x3b);
946                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
947                 }
948                 else if (type == SCAN_OUT)
949                 {
950                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
951                         buffer_write(0x1b);
952                         /* LOG_DEBUG("added TDI bits (o)"); */
953                 }
954                 else if (type == SCAN_IN)
955                 {
956                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
957                         buffer_write(0x2a);
958                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
959                 }
960                 buffer_write(0x0);
961                 buffer_write(last_bit);
962         }
963         else
964         {
965                 int tms_bits;
966                 int tms_count;
967                 uint8_t mpsse_cmd;
968
969                 /* move from Shift-IR/DR to end state */
970                 if (type != SCAN_OUT)
971                 {
972                         /* We always go to the PAUSE state in two step at the end of an IN or IO scan */
973                         /* This must be coordinated with the bit shifts in ft2232_read_scan    */
974                         tms_bits  = 0x01;
975                         tms_count = 2;
976                         /* Clock Data to TMS/CS Pin with Read */
977                         mpsse_cmd = 0x6b;
978                 }
979                 else
980                 {
981                         tms_bits  = tap_get_tms_path(tap_get_state(), tap_get_end_state());
982                         tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
983                         /* Clock Data to TMS/CS Pin (no Read) */
984                         mpsse_cmd = 0x4b;
985                 }
986
987                 DEBUG_JTAG_IO("finish %s", (type == SCAN_OUT) ? "without read" : "via PAUSE");
988                 clock_tms(mpsse_cmd, tms_bits, tms_count, last_bit);
989         }
990
991         if (tap_get_state() != tap_get_end_state())
992         {
993                 move_to_state(tap_get_end_state());
994         }
995 }
996
997 static int ft2232_large_scan(scan_command_t* cmd, enum scan_type type, uint8_t* buffer, int scan_size)
998 {
999         int num_bytes = (scan_size + 7) / 8;
1000         int bits_left = scan_size;
1001         int cur_byte  = 0;
1002         int last_bit;
1003         uint8_t* receive_buffer  = malloc(CEIL(scan_size, 8));
1004         uint8_t* receive_pointer = receive_buffer;
1005         uint32_t bytes_written;
1006         uint32_t bytes_read;
1007         int retval;
1008         int thisrun_read = 0;
1009
1010         if (cmd->ir_scan)
1011         {
1012                 LOG_ERROR("BUG: large IR scans are not supported");
1013                 exit(-1);
1014         }
1015
1016         if (tap_get_state() != TAP_DRSHIFT)
1017         {
1018                 move_to_state(TAP_DRSHIFT);
1019         }
1020
1021         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1022         {
1023                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
1024                 exit(-1);
1025         }
1026         LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1027                   ft2232_buffer_size, (int)bytes_written);
1028         ft2232_buffer_size = 0;
1029
1030         /* add command for complete bytes */
1031         while (num_bytes > 1)
1032         {
1033                 int thisrun_bytes;
1034
1035                 if (type == SCAN_IO)
1036                 {
1037                         /* Clock Data Bytes In and Out LSB First */
1038                         buffer_write(0x39);
1039                         /* LOG_DEBUG("added TDI bytes (io %i)", num_bytes); */
1040                 }
1041                 else if (type == SCAN_OUT)
1042                 {
1043                         /* Clock Data Bytes Out on -ve Clock Edge LSB First (no Read) */
1044                         buffer_write(0x19);
1045                         /* LOG_DEBUG("added TDI bytes (o)"); */
1046                 }
1047                 else if (type == SCAN_IN)
1048                 {
1049                         /* Clock Data Bytes In on +ve Clock Edge LSB First (no Write) */
1050                         buffer_write(0x28);
1051                         /* LOG_DEBUG("added TDI bytes (i %i)", num_bytes); */
1052                 }
1053
1054                 thisrun_bytes = (num_bytes > 65537) ? 65536 : (num_bytes - 1);
1055                 thisrun_read  = thisrun_bytes;
1056                 num_bytes    -= thisrun_bytes;
1057                 buffer_write((uint8_t) (thisrun_bytes - 1));
1058                 buffer_write((uint8_t) ((thisrun_bytes - 1) >> 8));
1059
1060                 if (type != SCAN_IN)
1061                 {
1062                         /* add complete bytes */
1063                         while (thisrun_bytes-- > 0)
1064                         {
1065                                 buffer_write(buffer[cur_byte]);
1066                                 cur_byte++;
1067                                 bits_left -= 8;
1068                         }
1069                 }
1070                 else /* (type == SCAN_IN) */
1071                 {
1072                         bits_left -= 8 * (thisrun_bytes);
1073                 }
1074
1075                 if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1076                 {
1077                         LOG_ERROR("couldn't write MPSSE commands to FT2232");
1078                         exit(-1);
1079                 }
1080                 LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1081                           ft2232_buffer_size,
1082                           (int)bytes_written);
1083                 ft2232_buffer_size = 0;
1084
1085                 if (type != SCAN_OUT)
1086                 {
1087                         if ((retval = ft2232_read(receive_pointer, thisrun_read, &bytes_read)) != ERROR_OK)
1088                         {
1089                                 LOG_ERROR("couldn't read from FT2232");
1090                                 exit(-1);
1091                         }
1092                         LOG_DEBUG("thisrun_read: %i, bytes_read: %i",
1093                                   thisrun_read,
1094                                   (int)bytes_read);
1095                         receive_pointer += bytes_read;
1096                 }
1097         }
1098
1099         thisrun_read = 0;
1100
1101         /* the most signifcant bit is scanned during TAP movement */
1102         if (type != SCAN_IN)
1103                 last_bit = (buffer[cur_byte] >> (bits_left - 1)) & 0x1;
1104         else
1105                 last_bit = 0;
1106
1107         /* process remaining bits but the last one */
1108         if (bits_left > 1)
1109         {
1110                 if (type == SCAN_IO)
1111                 {
1112                         /* Clock Data Bits In and Out LSB First */
1113                         buffer_write(0x3b);
1114                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
1115                 }
1116                 else if (type == SCAN_OUT)
1117                 {
1118                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
1119                         buffer_write(0x1b);
1120                         /* LOG_DEBUG("added TDI bits (o)"); */
1121                 }
1122                 else if (type == SCAN_IN)
1123                 {
1124                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
1125                         buffer_write(0x2a);
1126                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
1127                 }
1128                 buffer_write(bits_left - 2);
1129                 if (type != SCAN_IN)
1130                         buffer_write(buffer[cur_byte]);
1131
1132                 if (type != SCAN_OUT)
1133                         thisrun_read += 2;
1134         }
1135
1136         if (tap_get_end_state() == TAP_DRSHIFT)
1137         {
1138                 if (type == SCAN_IO)
1139                 {
1140                         /* Clock Data Bits In and Out LSB First */
1141                         buffer_write(0x3b);
1142                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
1143                 }
1144                 else if (type == SCAN_OUT)
1145                 {
1146                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
1147                         buffer_write(0x1b);
1148                         /* LOG_DEBUG("added TDI bits (o)"); */
1149                 }
1150                 else if (type == SCAN_IN)
1151                 {
1152                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
1153                         buffer_write(0x2a);
1154                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
1155                 }
1156                 buffer_write(0x0);
1157                 buffer_write(last_bit);
1158         }
1159         else
1160         {
1161                 int tms_bits  = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1162                 int tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1163                 uint8_t mpsse_cmd;
1164
1165                 /* move from Shift-IR/DR to end state */
1166                 if (type != SCAN_OUT)
1167                 {
1168                         /* Clock Data to TMS/CS Pin with Read */
1169                         mpsse_cmd = 0x6b;
1170                         /* LOG_DEBUG("added TMS scan (read)"); */
1171                 }
1172                 else
1173                 {
1174                         /* Clock Data to TMS/CS Pin (no Read) */
1175                         mpsse_cmd = 0x4b;
1176                         /* LOG_DEBUG("added TMS scan (no read)"); */
1177                 }
1178
1179                 DEBUG_JTAG_IO("finish, %s", (type == SCAN_OUT) ? "no read" : "read");
1180                 clock_tms(mpsse_cmd, tms_bits, tms_count, last_bit);
1181         }
1182
1183         if (type != SCAN_OUT)
1184                 thisrun_read += 1;
1185
1186         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1187         {
1188                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
1189                 exit(-1);
1190         }
1191         LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1192                   ft2232_buffer_size,
1193                   (int)bytes_written);
1194         ft2232_buffer_size = 0;
1195
1196         if (type != SCAN_OUT)
1197         {
1198                 if ((retval = ft2232_read(receive_pointer, thisrun_read, &bytes_read)) != ERROR_OK)
1199                 {
1200                         LOG_ERROR("couldn't read from FT2232");
1201                         exit(-1);
1202                 }
1203                 LOG_DEBUG("thisrun_read: %i, bytes_read: %i",
1204                           thisrun_read,
1205                           (int)bytes_read);
1206                 receive_pointer += bytes_read;
1207         }
1208
1209         return ERROR_OK;
1210 }
1211
1212 static int ft2232_predict_scan_out(int scan_size, enum scan_type type)
1213 {
1214         int predicted_size = 3;
1215         int num_bytes = (scan_size - 1) / 8;
1216
1217         if (tap_get_state() != TAP_DRSHIFT)
1218                 predicted_size += get_tms_buffer_requirements(tap_get_tms_path_len(tap_get_state(), TAP_DRSHIFT));
1219
1220         if (type == SCAN_IN)    /* only from device to host */
1221         {
1222                 /* complete bytes */
1223                 predicted_size += CEIL(num_bytes, 65536) * 3;
1224
1225                 /* remaining bits - 1 (up to 7) */
1226                 predicted_size += ((scan_size - 1) % 8) ? 2 : 0;
1227         }
1228         else    /* host to device, or bidirectional */
1229         {
1230                 /* complete bytes */
1231                 predicted_size += num_bytes + CEIL(num_bytes, 65536) * 3;
1232
1233                 /* remaining bits -1 (up to 7) */
1234                 predicted_size += ((scan_size - 1) % 8) ? 3 : 0;
1235         }
1236
1237         return predicted_size;
1238 }
1239
1240 static int ft2232_predict_scan_in(int scan_size, enum scan_type type)
1241 {
1242         int predicted_size = 0;
1243
1244         if (type != SCAN_OUT)
1245         {
1246                 /* complete bytes */
1247                 predicted_size += (CEIL(scan_size, 8) > 1) ? (CEIL(scan_size, 8) - 1) : 0;
1248
1249                 /* remaining bits - 1 */
1250                 predicted_size += ((scan_size - 1) % 8) ? 1 : 0;
1251
1252                 /* last bit (from TMS scan) */
1253                 predicted_size += 1;
1254         }
1255
1256         /* LOG_DEBUG("scan_size: %i, predicted_size: %i", scan_size, predicted_size); */
1257
1258         return predicted_size;
1259 }
1260
1261 static void usbjtag_reset(int trst, int srst)
1262 {
1263         enum reset_types jtag_reset_config = jtag_get_reset_config();
1264         if (trst == 1)
1265         {
1266                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1267                         low_direction |= nTRSTnOE;      /* switch to output pin (output is low) */
1268                 else
1269                         low_output &= ~nTRST;           /* switch output low */
1270         }
1271         else if (trst == 0)
1272         {
1273                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1274                         low_direction &= ~nTRSTnOE;     /* switch to input pin (high-Z + internal and external pullup) */
1275                 else
1276                         low_output |= nTRST;            /* switch output high */
1277         }
1278
1279         if (srst == 1)
1280         {
1281                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1282                         low_output &= ~nSRST;           /* switch output low */
1283                 else
1284                         low_direction |= nSRSTnOE;      /* switch to output pin (output is low) */
1285         }
1286         else if (srst == 0)
1287         {
1288                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1289                         low_output |= nSRST;            /* switch output high */
1290                 else
1291                         low_direction &= ~nSRSTnOE;     /* switch to input pin (high-Z) */
1292         }
1293
1294         /* command "set data bits low byte" */
1295         buffer_write(0x80);
1296         buffer_write(low_output);
1297         buffer_write(low_direction);
1298 }
1299
1300 static void jtagkey_reset(int trst, int srst)
1301 {
1302         enum reset_types jtag_reset_config = jtag_get_reset_config();
1303         if (trst == 1)
1304         {
1305                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1306                         high_output &= ~nTRSTnOE;
1307                 else
1308                         high_output &= ~nTRST;
1309         }
1310         else if (trst == 0)
1311         {
1312                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1313                         high_output |= nTRSTnOE;
1314                 else
1315                         high_output |= nTRST;
1316         }
1317
1318         if (srst == 1)
1319         {
1320                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1321                         high_output &= ~nSRST;
1322                 else
1323                         high_output &= ~nSRSTnOE;
1324         }
1325         else if (srst == 0)
1326         {
1327                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1328                         high_output |= nSRST;
1329                 else
1330                         high_output |= nSRSTnOE;
1331         }
1332
1333         /* command "set data bits high byte" */
1334         buffer_write(0x82);
1335         buffer_write(high_output);
1336         buffer_write(high_direction);
1337         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1338                         high_direction);
1339 }
1340
1341 static void olimex_jtag_reset(int trst, int srst)
1342 {
1343         enum reset_types jtag_reset_config = jtag_get_reset_config();
1344         if (trst == 1)
1345         {
1346                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1347                         high_output &= ~nTRSTnOE;
1348                 else
1349                         high_output &= ~nTRST;
1350         }
1351         else if (trst == 0)
1352         {
1353                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1354                         high_output |= nTRSTnOE;
1355                 else
1356                         high_output |= nTRST;
1357         }
1358
1359         if (srst == 1)
1360         {
1361                 high_output |= nSRST;
1362         }
1363         else if (srst == 0)
1364         {
1365                 high_output &= ~nSRST;
1366         }
1367
1368         /* command "set data bits high byte" */
1369         buffer_write(0x82);
1370         buffer_write(high_output);
1371         buffer_write(high_direction);
1372         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1373                         high_direction);
1374 }
1375
1376 static void axm0432_jtag_reset(int trst, int srst)
1377 {
1378         if (trst == 1)
1379         {
1380                 tap_set_state(TAP_RESET);
1381                 high_output &= ~nTRST;
1382         }
1383         else if (trst == 0)
1384         {
1385                 high_output |= nTRST;
1386         }
1387
1388         if (srst == 1)
1389         {
1390                 high_output &= ~nSRST;
1391         }
1392         else if (srst == 0)
1393         {
1394                 high_output |= nSRST;
1395         }
1396
1397         /* command "set data bits low byte" */
1398         buffer_write(0x82);
1399         buffer_write(high_output);
1400         buffer_write(high_direction);
1401         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1402                         high_direction);
1403 }
1404
1405 static void flyswatter_reset(int trst, int srst)
1406 {
1407         if (trst == 1)
1408         {
1409                 low_output &= ~nTRST;
1410         }
1411         else if (trst == 0)
1412         {
1413                 low_output |= nTRST;
1414         }
1415
1416         if (srst == 1)
1417         {
1418                 low_output |= nSRST;
1419         }
1420         else if (srst == 0)
1421         {
1422                 low_output &= ~nSRST;
1423         }
1424
1425         /* command "set data bits low byte" */
1426         buffer_write(0x80);
1427         buffer_write(low_output);
1428         buffer_write(low_direction);
1429         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
1430 }
1431
1432 static void turtle_reset(int trst, int srst)
1433 {
1434         trst = trst;
1435
1436         if (srst == 1)
1437         {
1438                 low_output |= nSRST;
1439         }
1440         else if (srst == 0)
1441         {
1442                 low_output &= ~nSRST;
1443         }
1444
1445         /* command "set data bits low byte" */
1446         buffer_write(0x80);
1447         buffer_write(low_output);
1448         buffer_write(low_direction);
1449         LOG_DEBUG("srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", srst, low_output, low_direction);
1450 }
1451
1452 static void comstick_reset(int trst, int srst)
1453 {
1454         if (trst == 1)
1455         {
1456                 high_output &= ~nTRST;
1457         }
1458         else if (trst == 0)
1459         {
1460                 high_output |= nTRST;
1461         }
1462
1463         if (srst == 1)
1464         {
1465                 high_output &= ~nSRST;
1466         }
1467         else if (srst == 0)
1468         {
1469                 high_output |= nSRST;
1470         }
1471
1472         /* command "set data bits high byte" */
1473         buffer_write(0x82);
1474         buffer_write(high_output);
1475         buffer_write(high_direction);
1476         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1477                         high_direction);
1478 }
1479
1480 static void stm32stick_reset(int trst, int srst)
1481 {
1482         if (trst == 1)
1483         {
1484                 high_output &= ~nTRST;
1485         }
1486         else if (trst == 0)
1487         {
1488                 high_output |= nTRST;
1489         }
1490
1491         if (srst == 1)
1492         {
1493                 low_output &= ~nSRST;
1494         }
1495         else if (srst == 0)
1496         {
1497                 low_output |= nSRST;
1498         }
1499
1500         /* command "set data bits low byte" */
1501         buffer_write(0x80);
1502         buffer_write(low_output);
1503         buffer_write(low_direction);
1504
1505         /* command "set data bits high byte" */
1506         buffer_write(0x82);
1507         buffer_write(high_output);
1508         buffer_write(high_direction);
1509         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1510                         high_direction);
1511 }
1512
1513 static void sheevaplug_reset(int trst, int srst)
1514 {
1515         if (trst == 1)
1516                 high_output &= ~nTRST;
1517         else if (trst == 0)
1518                 high_output |= nTRST;
1519
1520         if (srst == 1)
1521                 high_output &= ~nSRSTnOE;
1522         else if (srst == 0)
1523                 high_output |= nSRSTnOE;
1524
1525         /* command "set data bits high byte" */
1526         buffer_write(0x82);
1527         buffer_write(high_output);
1528         buffer_write(high_direction);
1529         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output, high_direction);
1530 }
1531
1532 static int ft2232_execute_runtest(jtag_command_t *cmd)
1533 {
1534         int retval;
1535         int i;
1536         int predicted_size = 0;
1537         retval = ERROR_OK;
1538
1539         DEBUG_JTAG_IO("runtest %i cycles, end in %s",
1540                         cmd->cmd.runtest->num_cycles,
1541                         tap_state_name(cmd->cmd.runtest->end_state));
1542
1543         /* only send the maximum buffer size that FT2232C can handle */
1544         predicted_size = 0;
1545         if (tap_get_state() != TAP_IDLE)
1546                 predicted_size += 3;
1547         predicted_size += 3 * CEIL(cmd->cmd.runtest->num_cycles, 7);
1548         if (cmd->cmd.runtest->end_state != TAP_IDLE)
1549                 predicted_size += 3;
1550         if (tap_get_end_state() != TAP_IDLE)
1551                 predicted_size += 3;
1552         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1553         {
1554                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1555                         retval = ERROR_JTAG_QUEUE_FAILED;
1556                 require_send = 0;
1557                 first_unsent = cmd;
1558         }
1559         if (tap_get_state() != TAP_IDLE)
1560         {
1561                 move_to_state(TAP_IDLE);
1562                 require_send = 1;
1563         }
1564         i = cmd->cmd.runtest->num_cycles;
1565         while (i > 0)
1566         {
1567                 /* there are no state transitions in this code, so omit state tracking */
1568
1569                 /* command "Clock Data to TMS/CS Pin (no Read)" */
1570                 buffer_write(0x4b);
1571
1572                 /* scan 7 bits */
1573                 buffer_write((i > 7) ? 6 : (i - 1));
1574
1575                 /* TMS data bits */
1576                 buffer_write(0x0);
1577
1578                 i -= (i > 7) ? 7 : i;
1579                 /* LOG_DEBUG("added TMS scan (no read)"); */
1580         }
1581
1582         ft2232_end_state(cmd->cmd.runtest->end_state);
1583
1584         if (tap_get_state() != tap_get_end_state())
1585         {
1586                 move_to_state(tap_get_end_state());
1587         }
1588
1589         require_send = 1;
1590         DEBUG_JTAG_IO("runtest: %i, end in %s",
1591                         cmd->cmd.runtest->num_cycles,
1592                         tap_state_name(tap_get_end_state()));
1593         return retval;
1594 }
1595
1596 static int ft2232_execute_statemove(jtag_command_t *cmd)
1597 {
1598         int     predicted_size = 0;
1599         int     retval = ERROR_OK;
1600
1601         DEBUG_JTAG_IO("statemove end in %s",
1602                         tap_state_name(cmd->cmd.statemove->end_state));
1603
1604         /* only send the maximum buffer size that FT2232C can handle */
1605         predicted_size = 3;
1606         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1607         {
1608                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1609                         retval = ERROR_JTAG_QUEUE_FAILED;
1610                 require_send = 0;
1611                 first_unsent = cmd;
1612         }
1613         ft2232_end_state(cmd->cmd.statemove->end_state);
1614
1615         /* For TAP_RESET, ignore the current recorded state.  It's often
1616          * wrong at server startup, and this transation is critical whenever
1617          * it's requested.
1618          */
1619         if (tap_get_end_state() == TAP_RESET) {
1620                 clock_tms(0x4b,  0xff, 5, 0);
1621                 require_send = 1;
1622
1623         /* shortest-path move to desired end state */
1624         } else if (tap_get_state() != tap_get_end_state())
1625         {
1626                 move_to_state(tap_get_end_state());
1627                 require_send = 1;
1628         }
1629
1630         return retval;
1631 }
1632
1633 static int ft2232_execute_pathmove(jtag_command_t *cmd)
1634 {
1635         int     predicted_size = 0;
1636         int     retval = ERROR_OK;
1637
1638         tap_state_t*     path = cmd->cmd.pathmove->path;
1639         int     num_states    = cmd->cmd.pathmove->num_states;
1640
1641         DEBUG_JTAG_IO("pathmove: %i states, current: %s  end: %s", num_states,
1642                         tap_state_name(tap_get_state()),
1643                         tap_state_name(path[num_states-1]));
1644
1645         /* only send the maximum buffer size that FT2232C can handle */
1646         predicted_size = 3 * CEIL(num_states, 7);
1647         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1648         {
1649                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1650                         retval = ERROR_JTAG_QUEUE_FAILED;
1651
1652                 require_send = 0;
1653                 first_unsent = cmd;
1654         }
1655
1656         ft2232_add_pathmove(path, num_states);
1657         require_send = 1;
1658
1659         return retval;
1660 }
1661
1662 static int ft2232_execute_scan(jtag_command_t *cmd)
1663 {
1664         uint8_t* buffer;
1665         int scan_size;                          /* size of IR or DR scan */
1666         int predicted_size = 0;
1667         int retval = ERROR_OK;
1668
1669         enum scan_type  type = jtag_scan_type(cmd->cmd.scan);
1670
1671         DEBUG_JTAG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN", type);
1672
1673         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
1674
1675         predicted_size = ft2232_predict_scan_out(scan_size, type);
1676         if ((predicted_size + 1) > FT2232_BUFFER_SIZE)
1677         {
1678                 LOG_DEBUG("oversized ft2232 scan (predicted_size > FT2232_BUFFER_SIZE)");
1679                 /* unsent commands before this */
1680                 if (first_unsent != cmd)
1681                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1682                                 retval = ERROR_JTAG_QUEUE_FAILED;
1683
1684                 /* current command */
1685                 ft2232_end_state(cmd->cmd.scan->end_state);
1686                 ft2232_large_scan(cmd->cmd.scan, type, buffer, scan_size);
1687                 require_send = 0;
1688                 first_unsent = cmd->next;
1689                 if (buffer)
1690                         free(buffer);
1691                 return retval;
1692         }
1693         else if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1694         {
1695                 LOG_DEBUG("ft2232 buffer size reached, sending queued commands (first_unsent: %p, cmd: %p)",
1696                                 first_unsent,
1697                                 cmd);
1698                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1699                         retval = ERROR_JTAG_QUEUE_FAILED;
1700                 require_send = 0;
1701                 first_unsent = cmd;
1702         }
1703         ft2232_expect_read += ft2232_predict_scan_in(scan_size, type);
1704         /* LOG_DEBUG("new read size: %i", ft2232_expect_read); */
1705         ft2232_end_state(cmd->cmd.scan->end_state);
1706         ft2232_add_scan(cmd->cmd.scan->ir_scan, type, buffer, scan_size);
1707         require_send = 1;
1708         if (buffer)
1709                 free(buffer);
1710         DEBUG_JTAG_IO("%s scan, %i bits, end in %s",
1711                         (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1712                         tap_state_name(tap_get_end_state()));
1713         return retval;
1714
1715 }
1716
1717 static int ft2232_execute_reset(jtag_command_t *cmd)
1718 {
1719         int retval;
1720         int predicted_size = 0;
1721         retval = ERROR_OK;
1722
1723         DEBUG_JTAG_IO("reset trst: %i srst %i",
1724                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1725
1726         /* only send the maximum buffer size that FT2232C can handle */
1727         predicted_size = 3;
1728         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1729         {
1730                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1731                         retval = ERROR_JTAG_QUEUE_FAILED;
1732                 require_send = 0;
1733                 first_unsent = cmd;
1734         }
1735
1736         if ((cmd->cmd.reset->trst == 1) || (cmd->cmd.reset->srst && (jtag_get_reset_config() & RESET_SRST_PULLS_TRST)))
1737         {
1738                 tap_set_state(TAP_RESET);
1739         }
1740
1741         layout->reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1742         require_send = 1;
1743
1744         DEBUG_JTAG_IO("trst: %i, srst: %i",
1745                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1746         return retval;
1747 }
1748
1749 static int ft2232_execute_sleep(jtag_command_t *cmd)
1750 {
1751         int retval;
1752         retval = ERROR_OK;
1753
1754         DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
1755
1756         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1757                                 retval = ERROR_JTAG_QUEUE_FAILED;
1758         first_unsent = cmd->next;
1759         jtag_sleep(cmd->cmd.sleep->us);
1760         DEBUG_JTAG_IO("sleep %i usec while in %s",
1761                         cmd->cmd.sleep->us,
1762                         tap_state_name(tap_get_state()));
1763         return retval;
1764 }
1765
1766 static int ft2232_execute_stableclocks(jtag_command_t *cmd)
1767 {
1768         int retval;
1769         retval = ERROR_OK;
1770
1771         /* this is only allowed while in a stable state.  A check for a stable
1772          * state was done in jtag_add_clocks()
1773          */
1774         if (ft2232_stableclocks(cmd->cmd.stableclocks->num_cycles, cmd) != ERROR_OK)
1775                 retval = ERROR_JTAG_QUEUE_FAILED;
1776         DEBUG_JTAG_IO("clocks %i while in %s",
1777                         cmd->cmd.stableclocks->num_cycles,
1778                         tap_state_name(tap_get_state()));
1779         return retval;
1780 }
1781
1782 static int ft2232_execute_command(jtag_command_t *cmd)
1783 {
1784         int retval;
1785         retval = ERROR_OK;
1786
1787         switch (cmd->type)
1788         {
1789         case JTAG_RESET:        retval = ft2232_execute_reset(cmd); break;
1790         case JTAG_RUNTEST:      retval = ft2232_execute_runtest(cmd); break;
1791         case JTAG_STATEMOVE: retval = ft2232_execute_statemove(cmd); break;
1792         case JTAG_PATHMOVE:     retval = ft2232_execute_pathmove(cmd); break;
1793         case JTAG_SCAN:         retval = ft2232_execute_scan(cmd); break;
1794         case JTAG_SLEEP:        retval = ft2232_execute_sleep(cmd); break;
1795         case JTAG_STABLECLOCKS: retval = ft2232_execute_stableclocks(cmd); break;
1796         default:
1797                 LOG_ERROR("BUG: unknown JTAG command type encountered");
1798                 exit(-1);
1799         }
1800         return retval;
1801 }
1802
1803 static int ft2232_execute_queue()
1804 {
1805         jtag_command_t* cmd = jtag_command_queue;       /* currently processed command */
1806         int retval;
1807
1808         first_unsent = cmd;             /* next command that has to be sent */
1809         require_send = 0;
1810
1811         /* return ERROR_OK, unless ft2232_send_and_recv reports a failed check
1812          * that wasn't handled by a caller-provided error handler
1813          */
1814         retval = ERROR_OK;
1815
1816         ft2232_buffer_size = 0;
1817         ft2232_expect_read = 0;
1818
1819         /* blink, if the current layout has that feature */
1820         if (layout->blink)
1821                 layout->blink();
1822
1823         while (cmd)
1824         {
1825                 if (ft2232_execute_command(cmd) != ERROR_OK)
1826                         retval = ERROR_JTAG_QUEUE_FAILED;
1827                 /* Start reading input before FT2232 TX buffer fills up */
1828                 cmd = cmd->next;
1829                 if (ft2232_expect_read > 256)
1830                 {
1831                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1832                                 retval = ERROR_JTAG_QUEUE_FAILED;
1833                         first_unsent = cmd;
1834                 }
1835         }
1836
1837         if (require_send > 0)
1838                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1839                         retval = ERROR_JTAG_QUEUE_FAILED;
1840
1841         return retval;
1842 }
1843
1844 #if BUILD_FT2232_FTD2XX == 1
1845 static int ft2232_init_ftd2xx(uint16_t vid, uint16_t pid, int more, int* try_more)
1846 {
1847         FT_STATUS       status;
1848         DWORD           deviceID;
1849         char            SerialNumber[16];
1850         char            Description[64];
1851         DWORD   openex_flags  = 0;
1852         char*   openex_string = NULL;
1853         uint8_t latency_timer;
1854
1855         LOG_DEBUG("'ft2232' interface using FTD2XX with '%s' layout (%4.4x:%4.4x)", ft2232_layout, vid, pid);
1856
1857 #if IS_WIN32 == 0
1858         /* Add non-standard Vid/Pid to the linux driver */
1859         if ((status = FT_SetVIDPID(vid, pid)) != FT_OK)
1860         {
1861                 LOG_WARNING("couldn't add %4.4x:%4.4x", vid, pid);
1862         }
1863 #endif
1864
1865         if (ft2232_device_desc && ft2232_serial)
1866         {
1867                 LOG_WARNING("can't open by device description and serial number, giving precedence to serial");
1868                 ft2232_device_desc = NULL;
1869         }
1870
1871         if (ft2232_device_desc)
1872         {
1873                 openex_string = ft2232_device_desc;
1874                 openex_flags  = FT_OPEN_BY_DESCRIPTION;
1875         }
1876         else if (ft2232_serial)
1877         {
1878                 openex_string = ft2232_serial;
1879                 openex_flags  = FT_OPEN_BY_SERIAL_NUMBER;
1880         }
1881         else
1882         {
1883                 LOG_ERROR("neither device description nor serial number specified");
1884                 LOG_ERROR("please add \"ft2232_device_desc <string>\" or \"ft2232_serial <string>\" to your .cfg file");
1885
1886                 return ERROR_JTAG_INIT_FAILED;
1887         }
1888
1889         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
1890         if (status != FT_OK) {
1891                 /* under Win32, the FTD2XX driver appends an "A" to the end
1892                  * of the description, if we tried by the desc, then
1893                  * try by the alternate "A" description. */
1894                 if (openex_string == ft2232_device_desc) {
1895                         /* Try the alternate method. */
1896                         openex_string = ft2232_device_desc_A;
1897                         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
1898                         if (status == FT_OK) {
1899                                 /* yea, the "alternate" method worked! */
1900                         } else {
1901                                 /* drat, give the user a meaningfull message.
1902                                  * telling the use we tried *BOTH* methods. */
1903                                 LOG_WARNING("Unable to open FTDI Device tried: '%s' and '%s'\n",
1904                                                         ft2232_device_desc,
1905                                                         ft2232_device_desc_A);
1906                         }
1907                 }
1908         }
1909
1910         if (status != FT_OK)
1911         {
1912                 DWORD num_devices;
1913
1914                 if (more)
1915                 {
1916                         LOG_WARNING("unable to open ftdi device (trying more): %lu", status);
1917                         *try_more = 1;
1918                         return ERROR_JTAG_INIT_FAILED;
1919                 }
1920                 LOG_ERROR("unable to open ftdi device: %lu", status);
1921                 status = FT_ListDevices(&num_devices, NULL, FT_LIST_NUMBER_ONLY);
1922                 if (status == FT_OK)
1923                 {
1924                         char** desc_array = malloc(sizeof(char*) * (num_devices + 1));
1925                         uint32_t i;
1926
1927                         for (i = 0; i < num_devices; i++)
1928                                 desc_array[i] = malloc(64);
1929
1930                         desc_array[num_devices] = NULL;
1931
1932                         status = FT_ListDevices(desc_array, &num_devices, FT_LIST_ALL | openex_flags);
1933
1934                         if (status == FT_OK)
1935                         {
1936                                 LOG_ERROR("ListDevices: %lu\n", num_devices);
1937                                 for (i = 0; i < num_devices; i++)
1938                                         LOG_ERROR("%" PRIu32 ": \"%s\"", i, desc_array[i]);
1939                         }
1940
1941                         for (i = 0; i < num_devices; i++)
1942                                 free(desc_array[i]);
1943
1944                         free(desc_array);
1945                 }
1946                 else
1947                 {
1948                         LOG_ERROR("ListDevices: NONE\n");
1949                 }
1950                 return ERROR_JTAG_INIT_FAILED;
1951         }
1952
1953         if ((status = FT_SetLatencyTimer(ftdih, ft2232_latency)) != FT_OK)
1954         {
1955                 LOG_ERROR("unable to set latency timer: %lu", status);
1956                 return ERROR_JTAG_INIT_FAILED;
1957         }
1958
1959         if ((status = FT_GetLatencyTimer(ftdih, &latency_timer)) != FT_OK)
1960         {
1961                 LOG_ERROR("unable to get latency timer: %lu", status);
1962                 return ERROR_JTAG_INIT_FAILED;
1963         }
1964         else
1965         {
1966                 LOG_DEBUG("current latency timer: %i", latency_timer);
1967         }
1968
1969         if ((status = FT_SetTimeouts(ftdih, 5000, 5000)) != FT_OK)
1970         {
1971                 LOG_ERROR("unable to set timeouts: %lu", status);
1972                 return ERROR_JTAG_INIT_FAILED;
1973         }
1974
1975         if ((status = FT_SetBitMode(ftdih, 0x0b, 2)) != FT_OK)
1976         {
1977                 LOG_ERROR("unable to enable bit i/o mode: %lu", status);
1978                 return ERROR_JTAG_INIT_FAILED;
1979         }
1980
1981         if ((status = FT_GetDeviceInfo(ftdih, &ftdi_device, &deviceID, SerialNumber, Description, NULL)) != FT_OK)
1982         {
1983                 LOG_ERROR("unable to get FT_GetDeviceInfo: %lu", status);
1984                 return ERROR_JTAG_INIT_FAILED;
1985         }
1986         else
1987         {
1988                 static const char* type_str[] =
1989                         {"BM", "AM", "100AX", "UNKNOWN", "2232C", "232R", "2232H", "4232H"};
1990                 unsigned no_of_known_types = sizeof(type_str) / sizeof(type_str[0]) - 1;
1991                 unsigned type_index = ((unsigned)ftdi_device <= no_of_known_types)
1992                         ? ftdi_device : FT_DEVICE_UNKNOWN;
1993                 LOG_INFO("device: %lu \"%s\"", ftdi_device, type_str[type_index]);
1994                 LOG_INFO("deviceID: %lu", deviceID);
1995                 LOG_INFO("SerialNumber: %s", SerialNumber);
1996                 LOG_INFO("Description: %s", Description);
1997         }
1998
1999         return ERROR_OK;
2000 }
2001
2002 static int ft2232_purge_ftd2xx(void)
2003 {
2004         FT_STATUS status;
2005
2006         if ((status = FT_Purge(ftdih, FT_PURGE_RX | FT_PURGE_TX)) != FT_OK)
2007         {
2008                 LOG_ERROR("error purging ftd2xx device: %lu", status);
2009                 return ERROR_JTAG_INIT_FAILED;
2010         }
2011
2012         return ERROR_OK;
2013 }
2014
2015 #endif /* BUILD_FT2232_FTD2XX == 1 */
2016
2017 #if BUILD_FT2232_LIBFTDI == 1
2018 static int ft2232_init_libftdi(uint16_t vid, uint16_t pid, int more, int* try_more)
2019 {
2020         uint8_t latency_timer;
2021
2022         LOG_DEBUG("'ft2232' interface using libftdi with '%s' layout (%4.4x:%4.4x)",
2023                         ft2232_layout, vid, pid);
2024
2025         if (ftdi_init(&ftdic) < 0)
2026                 return ERROR_JTAG_INIT_FAILED;
2027
2028         if (ftdi_set_interface(&ftdic, INTERFACE_A) < 0)
2029         {
2030                 LOG_ERROR("unable to select FT2232 channel A: %s", ftdic.error_str);
2031                 return ERROR_JTAG_INIT_FAILED;
2032         }
2033
2034         /* context, vendor id, product id */
2035         if (ftdi_usb_open_desc(&ftdic, vid, pid, ft2232_device_desc,
2036                                 ft2232_serial) < 0)
2037         {
2038                 if (more)
2039                         LOG_WARNING("unable to open ftdi device (trying more): %s",
2040                                         ftdic.error_str);
2041                 else
2042                         LOG_ERROR("unable to open ftdi device: %s", ftdic.error_str);
2043                 *try_more = 1;
2044                 return ERROR_JTAG_INIT_FAILED;
2045         }
2046
2047         /* There is already a reset in ftdi_usb_open_desc, this should be redundant */
2048         if (ftdi_usb_reset(&ftdic) < 0)
2049         {
2050                 LOG_ERROR("unable to reset ftdi device");
2051                 return ERROR_JTAG_INIT_FAILED;
2052         }
2053
2054         if (ftdi_set_latency_timer(&ftdic, ft2232_latency) < 0)
2055         {
2056                 LOG_ERROR("unable to set latency timer");
2057                 return ERROR_JTAG_INIT_FAILED;
2058         }
2059
2060         if (ftdi_get_latency_timer(&ftdic, &latency_timer) < 0)
2061         {
2062                 LOG_ERROR("unable to get latency timer");
2063                 return ERROR_JTAG_INIT_FAILED;
2064         }
2065         else
2066         {
2067                 LOG_DEBUG("current latency timer: %i", latency_timer);
2068         }
2069
2070         ftdi_set_bitmode(&ftdic, 0x0b, 2); /* ctx, JTAG I/O mask */
2071
2072         ftdi_device = ftdic.type;
2073         static const char* type_str[] =
2074                 {"AM", "BM", "2232C", "R", "2232H", "4232H", "Unknown"};
2075         unsigned no_of_known_types = sizeof(type_str) / sizeof(type_str[0]) - 1;
2076         unsigned type_index = ((unsigned)ftdi_device < no_of_known_types)
2077                 ? ftdi_device : no_of_known_types;
2078         LOG_DEBUG("FTDI chip type: %i \"%s\"", (int)ftdi_device, type_str[type_index]);
2079         return ERROR_OK;
2080 }
2081
2082 static int ft2232_purge_libftdi(void)
2083 {
2084         if (ftdi_usb_purge_buffers(&ftdic) < 0)
2085         {
2086                 LOG_ERROR("ftdi_purge_buffers: %s", ftdic.error_str);
2087                 return ERROR_JTAG_INIT_FAILED;
2088         }
2089
2090         return ERROR_OK;
2091 }
2092
2093 #endif /* BUILD_FT2232_LIBFTDI == 1 */
2094
2095 static int ft2232_init(void)
2096 {
2097         uint8_t  buf[1];
2098         int retval;
2099         uint32_t bytes_written;
2100         const ft2232_layout_t* cur_layout = ft2232_layouts;
2101         int i;
2102
2103         if (tap_get_tms_path_len(TAP_IRPAUSE,TAP_IRPAUSE) == 7)
2104         {
2105                 LOG_DEBUG("ft2232 interface using 7 step jtag state transitions");
2106         }
2107         else
2108         {
2109                 LOG_DEBUG("ft2232 interface using shortest path jtag state transitions");
2110
2111         }
2112         if ((ft2232_layout == NULL) || (ft2232_layout[0] == 0))
2113         {
2114                 ft2232_layout = "usbjtag";
2115                 LOG_WARNING("No ft2232 layout specified, using default 'usbjtag'");
2116         }
2117
2118         while (cur_layout->name)
2119         {
2120                 if (strcmp(cur_layout->name, ft2232_layout) == 0)
2121                 {
2122                         layout = cur_layout;
2123                         break;
2124                 }
2125                 cur_layout++;
2126         }
2127
2128         if (!layout)
2129         {
2130                 LOG_ERROR("No matching layout found for %s", ft2232_layout);
2131                 return ERROR_JTAG_INIT_FAILED;
2132         }
2133
2134         for (i = 0; 1; i++)
2135         {
2136                 /*
2137                  * "more indicates that there are more IDs to try, so we should
2138                  * not print an error for an ID mismatch (but for anything
2139                  * else, we should).
2140                  *
2141                  * try_more indicates that the error code returned indicates an
2142                  * ID mismatch (and nothing else) and that we should proceeed
2143                  * with the next ID pair.
2144                  */
2145                 int more     = ft2232_vid[i + 1] || ft2232_pid[i + 1];
2146                 int try_more = 0;
2147
2148 #if BUILD_FT2232_FTD2XX == 1
2149                 retval = ft2232_init_ftd2xx(ft2232_vid[i], ft2232_pid[i],
2150                                 more, &try_more);
2151 #elif BUILD_FT2232_LIBFTDI == 1
2152                 retval = ft2232_init_libftdi(ft2232_vid[i], ft2232_pid[i],
2153                                 more, &try_more);
2154 #endif
2155                 if (retval >= 0)
2156                         break;
2157                 if (!more || !try_more)
2158                         return retval;
2159         }
2160
2161         ft2232_buffer_size = 0;
2162         ft2232_buffer = malloc(FT2232_BUFFER_SIZE);
2163
2164         if (layout->init() != ERROR_OK)
2165                 return ERROR_JTAG_INIT_FAILED;
2166
2167         if (ft2232_device_is_highspeed())
2168         {
2169 #ifndef BUILD_FT2232_HIGHSPEED
2170  #if BUILD_FT2232_FTD2XX == 1
2171                 LOG_WARNING("High Speed device found - You need a newer FTD2XX driver (version 2.04.16 or later)");
2172  #elif BUILD_FT2232_LIBFTDI == 1
2173                 LOG_WARNING("High Speed device found - You need a newer libftdi version (0.16 or later)");
2174  #endif
2175 #endif
2176                 /* make sure the legacy mode is disabled */
2177                 if (ft2232h_ft4232h_clk_divide_by_5(false) != ERROR_OK)
2178                         return ERROR_JTAG_INIT_FAILED;
2179         }
2180
2181         ft2232_speed(jtag_get_speed());
2182
2183         buf[0] = 0x85; /* Disconnect TDI/DO to TDO/DI for Loopback */
2184         if (((retval = ft2232_write(buf, 1, &bytes_written)) != ERROR_OK) || (bytes_written != 1))
2185         {
2186                 LOG_ERROR("couldn't write to FT2232 to disable loopback");
2187                 return ERROR_JTAG_INIT_FAILED;
2188         }
2189
2190 #if BUILD_FT2232_FTD2XX == 1
2191         return ft2232_purge_ftd2xx();
2192 #elif BUILD_FT2232_LIBFTDI == 1
2193         return ft2232_purge_libftdi();
2194 #endif
2195
2196         return ERROR_OK;
2197 }
2198
2199 static int usbjtag_init(void)
2200 {
2201         uint8_t  buf[3];
2202         uint32_t bytes_written;
2203
2204         low_output    = 0x08;
2205         low_direction = 0x0b;
2206
2207         if (strcmp(ft2232_layout, "usbjtag") == 0)
2208         {
2209                 nTRST    = 0x10;
2210                 nTRSTnOE = 0x10;
2211                 nSRST    = 0x40;
2212                 nSRSTnOE = 0x40;
2213         }
2214         else if (strcmp(ft2232_layout, "signalyzer") == 0)
2215         {
2216                 nTRST    = 0x10;
2217                 nTRSTnOE = 0x10;
2218                 nSRST    = 0x20;
2219                 nSRSTnOE = 0x20;
2220         }
2221         else if (strcmp(ft2232_layout, "evb_lm3s811") == 0)
2222         {
2223                 nTRST = 0x0;
2224                 nTRSTnOE = 0x00;
2225                 nSRST = 0x20;
2226                 nSRSTnOE = 0x20;
2227                 low_output    = 0x88;
2228                 low_direction = 0x8b;
2229         }
2230         else if (strcmp(ft2232_layout, "luminary_icdi") == 0)
2231         {
2232                 nTRST = 0x0;
2233                 nTRSTnOE = 0x00;
2234                 nSRST = 0x20;
2235                 nSRSTnOE = 0x20;
2236                 low_output    = 0x88;
2237                 low_direction = 0xcb;
2238         }
2239         else
2240         {
2241                 LOG_ERROR("BUG: usbjtag_init called for unknown layout '%s'", ft2232_layout);
2242                 return ERROR_JTAG_INIT_FAILED;
2243         }
2244
2245         enum reset_types jtag_reset_config = jtag_get_reset_config();
2246         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2247         {
2248                 low_direction &= ~nTRSTnOE; /* nTRST input */
2249                 low_output    &= ~nTRST;    /* nTRST = 0 */
2250         }
2251         else
2252         {
2253                 low_direction |= nTRSTnOE;  /* nTRST output */
2254                 low_output    |= nTRST;     /* nTRST = 1 */
2255         }
2256
2257         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2258         {
2259                 low_direction |= nSRSTnOE;  /* nSRST output */
2260                 low_output    |= nSRST;     /* nSRST = 1 */
2261         }
2262         else
2263         {
2264                 low_direction &= ~nSRSTnOE; /* nSRST input */
2265                 low_output    &= ~nSRST;    /* nSRST = 0 */
2266         }
2267
2268         /* initialize low byte for jtag */
2269         buf[0] = 0x80;          /* command "set data bits low byte" */
2270         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, xRST high) */
2271         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in */
2272         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2273
2274         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2275         {
2276                 LOG_ERROR("couldn't initialize FT2232 with 'USBJTAG' layout");
2277                 return ERROR_JTAG_INIT_FAILED;
2278         }
2279
2280         return ERROR_OK;
2281 }
2282
2283 static int axm0432_jtag_init(void)
2284 {
2285         uint8_t  buf[3];
2286         uint32_t bytes_written;
2287
2288         low_output    = 0x08;
2289         low_direction = 0x2b;
2290
2291         /* initialize low byte for jtag */
2292         buf[0] = 0x80;          /* command "set data bits low byte" */
2293         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2294         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2295         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2296
2297         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2298         {
2299                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2300                 return ERROR_JTAG_INIT_FAILED;
2301         }
2302
2303         if (strcmp(layout->name, "axm0432_jtag") == 0)
2304         {
2305                 nTRST    = 0x08;
2306                 nTRSTnOE = 0x0;     /* No output enable for TRST*/
2307                 nSRST    = 0x04;
2308                 nSRSTnOE = 0x0;     /* No output enable for SRST*/
2309         }
2310         else
2311         {
2312                 LOG_ERROR("BUG: axm0432_jtag_init called for non axm0432 layout");
2313                 exit(-1);
2314         }
2315
2316         high_output    = 0x0;
2317         high_direction = 0x0c;
2318
2319         enum reset_types jtag_reset_config = jtag_get_reset_config();
2320         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2321         {
2322                 LOG_ERROR("can't set nTRSTOE to push-pull on the Dicarlo jtag");
2323         }
2324         else
2325         {
2326                 high_output |= nTRST;
2327         }
2328
2329         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2330         {
2331                 LOG_ERROR("can't set nSRST to push-pull on the Dicarlo jtag");
2332         }
2333         else
2334         {
2335                 high_output |= nSRST;
2336         }
2337
2338         /* initialize high port */
2339         buf[0] = 0x82;              /* command "set data bits high byte" */
2340         buf[1] = high_output;       /* value */
2341         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2342         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2343
2344         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2345         {
2346                 LOG_ERROR("couldn't initialize FT2232 with 'Dicarlo' layout");
2347                 return ERROR_JTAG_INIT_FAILED;
2348         }
2349
2350         return ERROR_OK;
2351 }
2352
2353 static int jtagkey_init(void)
2354 {
2355         uint8_t  buf[3];
2356         uint32_t bytes_written;
2357
2358         low_output    = 0x08;
2359         low_direction = 0x1b;
2360
2361         /* initialize low byte for jtag */
2362         buf[0] = 0x80;          /* command "set data bits low byte" */
2363         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2364         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2365         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2366
2367         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2368         {
2369                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2370                 return ERROR_JTAG_INIT_FAILED;
2371         }
2372
2373         if (strcmp(layout->name, "jtagkey") == 0)
2374         {
2375                 nTRST    = 0x01;
2376                 nTRSTnOE = 0x4;
2377                 nSRST    = 0x02;
2378                 nSRSTnOE = 0x08;
2379         }
2380         else if ((strcmp(layout->name, "jtagkey_prototype_v1") == 0)
2381                          || (strcmp(layout->name, "oocdlink") == 0))
2382         {
2383                 nTRST    = 0x02;
2384                 nTRSTnOE = 0x1;
2385                 nSRST    = 0x08;
2386                 nSRSTnOE = 0x04;
2387         }
2388         else
2389         {
2390                 LOG_ERROR("BUG: jtagkey_init called for non jtagkey layout");
2391                 exit(-1);
2392         }
2393
2394         high_output    = 0x0;
2395         high_direction = 0x0f;
2396
2397         enum reset_types jtag_reset_config = jtag_get_reset_config();
2398         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2399         {
2400                 high_output |= nTRSTnOE;
2401                 high_output &= ~nTRST;
2402         }
2403         else
2404         {
2405                 high_output &= ~nTRSTnOE;
2406                 high_output |= nTRST;
2407         }
2408
2409         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2410         {
2411                 high_output &= ~nSRSTnOE;
2412                 high_output |= nSRST;
2413         }
2414         else
2415         {
2416                 high_output |= nSRSTnOE;
2417                 high_output &= ~nSRST;
2418         }
2419
2420         /* initialize high port */
2421         buf[0] = 0x82;              /* command "set data bits high byte" */
2422         buf[1] = high_output;       /* value */
2423         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2424         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2425
2426         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2427         {
2428                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2429                 return ERROR_JTAG_INIT_FAILED;
2430         }
2431
2432         return ERROR_OK;
2433 }
2434
2435 static int olimex_jtag_init(void)
2436 {
2437         uint8_t  buf[3];
2438         uint32_t bytes_written;
2439
2440         low_output    = 0x08;
2441         low_direction = 0x1b;
2442
2443         /* initialize low byte for jtag */
2444         buf[0] = 0x80;          /* command "set data bits low byte" */
2445         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2446         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2447         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2448
2449         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2450         {
2451                 LOG_ERROR("couldn't initialize FT2232 with 'Olimex' layout");
2452                 return ERROR_JTAG_INIT_FAILED;
2453         }
2454
2455         nTRST    = 0x01;
2456         nTRSTnOE = 0x4;
2457         nSRST    = 0x02;
2458         nSRSTnOE = 0x00; /* no output enable for nSRST */
2459
2460         high_output    = 0x0;
2461         high_direction = 0x0f;
2462
2463         enum reset_types jtag_reset_config = jtag_get_reset_config();
2464         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2465         {
2466                 high_output |= nTRSTnOE;
2467                 high_output &= ~nTRST;
2468         }
2469         else
2470         {
2471                 high_output &= ~nTRSTnOE;
2472                 high_output |= nTRST;
2473         }
2474
2475         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2476         {
2477                 LOG_ERROR("can't set nSRST to push-pull on the Olimex ARM-USB-OCD");
2478         }
2479         else
2480         {
2481                 high_output &= ~nSRST;
2482         }
2483
2484         /* turn red LED on */
2485         high_output |= 0x08;
2486
2487         /* initialize high port */
2488         buf[0] = 0x82;              /* command "set data bits high byte" */
2489         buf[1] = high_output;       /* value */
2490         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
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 'Olimex' layout");
2496                 return ERROR_JTAG_INIT_FAILED;
2497         }
2498
2499         return ERROR_OK;
2500 }
2501
2502 static int flyswatter_init(void)
2503 {
2504         uint8_t  buf[3];
2505         uint32_t bytes_written;
2506
2507         low_output    = 0x18;
2508         low_direction = 0xfb;
2509
2510         /* initialize low byte for jtag */
2511         buf[0] = 0x80;          /* command "set data bits low byte" */
2512         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2513         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE[12]=out, n[ST]srst = out */
2514         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2515
2516         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2517         {
2518                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2519                 return ERROR_JTAG_INIT_FAILED;
2520         }
2521
2522         nTRST    = 0x10;
2523         nTRSTnOE = 0x0;     /* not output enable for nTRST */
2524         nSRST    = 0x20;
2525         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2526
2527         high_output    = 0x00;
2528         high_direction = 0x0c;
2529
2530         /* turn red LED3 on, LED2 off */
2531         high_output |= 0x08;
2532
2533         /* initialize high port */
2534         buf[0] = 0x82;              /* command "set data bits high byte" */
2535         buf[1] = high_output;       /* value */
2536         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2537         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2538
2539         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2540         {
2541                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2542                 return ERROR_JTAG_INIT_FAILED;
2543         }
2544
2545         return ERROR_OK;
2546 }
2547
2548 static int turtle_init(void)
2549 {
2550         uint8_t  buf[3];
2551         uint32_t bytes_written;
2552
2553         low_output    = 0x08;
2554         low_direction = 0x5b;
2555
2556         /* initialize low byte for jtag */
2557         buf[0] = 0x80;          /* command "set data bits low byte" */
2558         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2559         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2560         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2561
2562         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2563         {
2564                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2565                 return ERROR_JTAG_INIT_FAILED;
2566         }
2567
2568         nSRST = 0x40;
2569
2570         high_output    = 0x00;
2571         high_direction = 0x0C;
2572
2573         /* initialize high port */
2574         buf[0] = 0x82; /* command "set data bits high byte" */
2575         buf[1] = high_output;
2576         buf[2] = high_direction;
2577         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2578
2579         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2580         {
2581                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2582                 return ERROR_JTAG_INIT_FAILED;
2583         }
2584
2585         return ERROR_OK;
2586 }
2587
2588 static int comstick_init(void)
2589 {
2590         uint8_t  buf[3];
2591         uint32_t bytes_written;
2592
2593         low_output    = 0x08;
2594         low_direction = 0x0b;
2595
2596         /* initialize low byte for jtag */
2597         buf[0] = 0x80;          /* command "set data bits low byte" */
2598         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2599         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2600         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2601
2602         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2603         {
2604                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2605                 return ERROR_JTAG_INIT_FAILED;
2606         }
2607
2608         nTRST    = 0x01;
2609         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2610         nSRST    = 0x02;
2611         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2612
2613         high_output    = 0x03;
2614         high_direction = 0x03;
2615
2616         /* initialize high port */
2617         buf[0] = 0x82; /* command "set data bits high byte" */
2618         buf[1] = high_output;
2619         buf[2] = high_direction;
2620         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2621
2622         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2623         {
2624                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2625                 return ERROR_JTAG_INIT_FAILED;
2626         }
2627
2628         return ERROR_OK;
2629 }
2630
2631 static int stm32stick_init(void)
2632 {
2633         uint8_t  buf[3];
2634         uint32_t bytes_written;
2635
2636         low_output    = 0x88;
2637         low_direction = 0x8b;
2638
2639         /* initialize low byte for jtag */
2640         buf[0] = 0x80;          /* command "set data bits low byte" */
2641         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2642         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2643         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2644
2645         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2646         {
2647                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2648                 return ERROR_JTAG_INIT_FAILED;
2649         }
2650
2651         nTRST    = 0x01;
2652         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2653         nSRST    = 0x80;
2654         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2655
2656         high_output    = 0x01;
2657         high_direction = 0x03;
2658
2659         /* initialize high port */
2660         buf[0] = 0x82; /* command "set data bits high byte" */
2661         buf[1] = high_output;
2662         buf[2] = high_direction;
2663         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2664
2665         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2666         {
2667                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2668                 return ERROR_JTAG_INIT_FAILED;
2669         }
2670
2671         return ERROR_OK;
2672 }
2673
2674 static int sheevaplug_init(void)
2675 {
2676         uint8_t buf[3];
2677         uint32_t bytes_written;
2678
2679         low_output = 0x08;
2680         low_direction = 0x1b;
2681
2682         /* initialize low byte for jtag */
2683         buf[0] = 0x80; /* command "set data bits low byte" */
2684         buf[1] = low_output; /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2685         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in */
2686         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2687
2688         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2689         {
2690                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2691                 return ERROR_JTAG_INIT_FAILED;
2692         }
2693
2694         nTRSTnOE = 0x1;
2695         nTRST = 0x02;
2696         nSRSTnOE = 0x4;
2697         nSRST = 0x08;
2698
2699         high_output = 0x0;
2700         high_direction = 0x0f;
2701
2702         /* nTRST is always push-pull */
2703         high_output &= ~nTRSTnOE;
2704         high_output |= nTRST;
2705
2706         /* nSRST is always open-drain */
2707         high_output |= nSRSTnOE;
2708         high_output &= ~nSRST;
2709
2710         /* initialize high port */
2711         buf[0] = 0x82; /* command "set data bits high byte" */
2712         buf[1] = high_output; /* value */
2713         buf[2] = high_direction;   /* all outputs - xRST */
2714         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2715
2716         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2717         {
2718                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2719                 return ERROR_JTAG_INIT_FAILED;
2720         }
2721
2722         return ERROR_OK;
2723 }
2724
2725 static int cortino_jtag_init(void)
2726 {
2727         uint8_t  buf[3];
2728         uint32_t bytes_written;
2729
2730         low_output    = 0x08;
2731         low_direction = 0x1b;
2732
2733         /* initialize low byte for jtag */
2734         buf[0] = 0x80;          /* command "set data bits low byte" */
2735         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2736         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2737         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2738
2739         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2740         {
2741                 LOG_ERROR("couldn't initialize FT2232 with 'cortino' layout");
2742                 return ERROR_JTAG_INIT_FAILED;
2743         }
2744
2745         nTRST    = 0x01;
2746         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2747         nSRST    = 0x02;
2748         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2749
2750         high_output    = 0x03;
2751         high_direction = 0x03;
2752
2753         /* initialize high port */
2754         buf[0] = 0x82; /* command "set data bits high byte" */
2755         buf[1] = high_output;
2756         buf[2] = high_direction;
2757         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2758
2759         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2760         {
2761                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2762                 return ERROR_JTAG_INIT_FAILED;
2763         }
2764
2765         return ERROR_OK;
2766 }
2767
2768 static void olimex_jtag_blink(void)
2769 {
2770         /* Olimex ARM-USB-OCD has a LED connected to ACBUS3
2771          * ACBUS3 is bit 3 of the GPIOH port
2772          */
2773         if (high_output & 0x08)
2774         {
2775                 /* set port pin high */
2776                 high_output &= 0x07;
2777         }
2778         else
2779         {
2780                 /* set port pin low */
2781                 high_output |= 0x08;
2782         }
2783
2784         buffer_write(0x82);
2785         buffer_write(high_output);
2786         buffer_write(high_direction);
2787 }
2788
2789 static void flyswatter_jtag_blink(void)
2790 {
2791         /*
2792          * Flyswatter has two LEDs connected to ACBUS2 and ACBUS3
2793          */
2794         high_output ^= 0x0c;
2795
2796         buffer_write(0x82);
2797         buffer_write(high_output);
2798         buffer_write(high_direction);
2799 }
2800
2801 static void turtle_jtag_blink(void)
2802 {
2803         /*
2804          * Turtelizer2 has two LEDs connected to ACBUS2 and ACBUS3
2805          */
2806         if (high_output & 0x08)
2807         {
2808                 high_output = 0x04;
2809         }
2810         else
2811         {
2812                 high_output = 0x08;
2813         }
2814
2815         buffer_write(0x82);
2816         buffer_write(high_output);
2817         buffer_write(high_direction);
2818 }
2819
2820 static int ft2232_quit(void)
2821 {
2822 #if BUILD_FT2232_FTD2XX == 1
2823         FT_STATUS status;
2824
2825         status = FT_Close(ftdih);
2826 #elif BUILD_FT2232_LIBFTDI == 1
2827         ftdi_usb_close(&ftdic);
2828
2829         ftdi_deinit(&ftdic);
2830 #endif
2831
2832         free(ft2232_buffer);
2833         ft2232_buffer = NULL;
2834
2835         return ERROR_OK;
2836 }
2837
2838 static int ft2232_handle_device_desc_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2839 {
2840         char *cp;
2841         char buf[200];
2842         if (argc == 1)
2843         {
2844                 ft2232_device_desc = strdup(args[0]);
2845                 cp = strchr(ft2232_device_desc, 0);
2846                 /* under Win32, the FTD2XX driver appends an "A" to the end
2847                  * of the description, this examines the given desc
2848                  * and creates the 'missing' _A or non_A variable. */
2849                 if ((cp[-1] == 'A') && (cp[-2]==' ')) {
2850                         /* it was, so make this the "A" version. */
2851                         ft2232_device_desc_A = ft2232_device_desc;
2852                         /* and *CREATE* the non-A version. */
2853                         strcpy(buf, ft2232_device_desc);
2854                         cp = strchr(buf, 0);
2855                         cp[-2] = 0;
2856                         ft2232_device_desc =  strdup(buf);
2857                 } else {
2858                         /* <space > A not defined
2859                          * so create it */
2860                         sprintf(buf, "%s A", ft2232_device_desc);
2861                         ft2232_device_desc_A = strdup(buf);
2862                 }
2863         }
2864         else
2865         {
2866                 LOG_ERROR("expected exactly one argument to ft2232_device_desc <description>");
2867         }
2868
2869         return ERROR_OK;
2870 }
2871
2872 static int ft2232_handle_serial_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2873 {
2874         if (argc == 1)
2875         {
2876                 ft2232_serial = strdup(args[0]);
2877         }
2878         else
2879         {
2880                 LOG_ERROR("expected exactly one argument to ft2232_serial <serial-number>");
2881         }
2882
2883         return ERROR_OK;
2884 }
2885
2886 static int ft2232_handle_layout_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2887 {
2888         if (argc == 0)
2889                 return ERROR_OK;
2890
2891         ft2232_layout = malloc(strlen(args[0]) + 1);
2892         strcpy(ft2232_layout, args[0]);
2893
2894         return ERROR_OK;
2895 }
2896
2897 static int ft2232_handle_vid_pid_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2898 {
2899         if (argc > MAX_USB_IDS * 2)
2900         {
2901                 LOG_WARNING("ignoring extra IDs in ft2232_vid_pid "
2902                                         "(maximum is %d pairs)", MAX_USB_IDS);
2903                 argc = MAX_USB_IDS * 2;
2904         }
2905         if (argc < 2 || (argc & 1))
2906         {
2907                 LOG_WARNING("incomplete ft2232_vid_pid configuration directive");
2908                 if (argc < 2)
2909                         return ERROR_COMMAND_SYNTAX_ERROR;
2910                 /* remove the incomplete trailing id */
2911                 argc -= 1;
2912         }
2913
2914         int i;
2915         int retval = ERROR_OK;
2916         for (i = 0; i < argc; i += 2)
2917         {
2918                 retval = parse_u16(args[i], &ft2232_vid[i >> 1]);
2919                 if (ERROR_OK != retval)
2920                         break;
2921                 retval = parse_u16(args[i + 1], &ft2232_pid[i >> 1]);
2922                 if (ERROR_OK != retval)
2923                         break;
2924         }
2925
2926         /*
2927          * Explicitly terminate, in case there are multiples instances of
2928          * ft2232_vid_pid.
2929          */
2930         ft2232_vid[i >> 1] = ft2232_pid[i >> 1] = 0;
2931
2932         return retval;
2933 }
2934
2935 static int ft2232_handle_latency_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2936 {
2937         if (argc == 1)
2938         {
2939                 ft2232_latency = atoi(args[0]);
2940         }
2941         else
2942         {
2943                 LOG_ERROR("expected exactly one argument to ft2232_latency <ms>");
2944         }
2945
2946         return ERROR_OK;
2947 }
2948
2949 static int ft2232_stableclocks(int num_cycles, jtag_command_t* cmd)
2950 {
2951         int retval = 0;
2952
2953         /* 7 bits of either ones or zeros. */
2954         uint8_t  tms = (tap_get_state() == TAP_RESET ? 0x7F : 0x00);
2955
2956         while (num_cycles > 0)
2957         {
2958                 /* the command 0x4b, "Clock Data to TMS/CS Pin (no Read)" handles
2959                  * at most 7 bits per invocation.  Here we invoke it potentially
2960                  * several times.
2961                  */
2962                 int bitcount_per_command = (num_cycles > 7) ? 7 : num_cycles;
2963
2964                 if (ft2232_buffer_size + 3 >= FT2232_BUFFER_SIZE)
2965                 {
2966                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
2967                                 retval = ERROR_JTAG_QUEUE_FAILED;
2968
2969                         first_unsent = cmd;
2970                 }
2971
2972                 /* there are no state transitions in this code, so omit state tracking */
2973
2974                 /* command "Clock Data to TMS/CS Pin (no Read)" */
2975                 buffer_write(0x4b);
2976
2977                 /* scan 7 bit */
2978                 buffer_write(bitcount_per_command - 1);
2979
2980                 /* TMS data bits are either all zeros or ones to stay in the current stable state */
2981                 buffer_write(tms);
2982
2983                 require_send = 1;
2984
2985                 num_cycles -= bitcount_per_command;
2986         }
2987
2988         return retval;
2989 }
2990
2991 /* ---------------------------------------------------------------------
2992  * Support for IceBear JTAG adapter from Section5:
2993  *      http://section5.ch/icebear
2994  *
2995  * Author: Sten, debian@sansys-electronic.com
2996  */
2997
2998 /* Icebear pin layout
2999  *
3000  * ADBUS5 (nEMU) nSRST  | 2   1|        GND (10k->VCC)
3001  * GND GND              | 4   3|        n.c.
3002  * ADBUS3 TMS           | 6   5|        ADBUS6 VCC
3003  * ADBUS0 TCK           | 8   7|        ADBUS7 (GND)
3004  * ADBUS4 nTRST         |10   9|        ACBUS0 (GND)
3005  * ADBUS1 TDI           |12  11|        ACBUS1 (GND)
3006  * ADBUS2 TDO           |14  13|        GND GND
3007  *
3008  * ADBUS0 O L TCK               ACBUS0 GND
3009  * ADBUS1 O L TDI               ACBUS1 GND
3010  * ADBUS2 I   TDO               ACBUS2 n.c.
3011  * ADBUS3 O H TMS               ACBUS3 n.c.
3012  * ADBUS4 O H nTRST
3013  * ADBUS5 O H nSRST
3014  * ADBUS6 -   VCC
3015  * ADBUS7 -   GND
3016  */
3017 static int icebear_jtag_init(void) {
3018         uint8_t  buf[3];
3019         uint32_t bytes_written;
3020
3021         low_direction   = 0x0b; /* output: TCK TDI TMS; input: TDO */
3022         low_output      = 0x08; /* high: TMS; low: TCK TDI */
3023         nTRST           = 0x10;
3024         nSRST           = 0x20;
3025
3026         enum reset_types jtag_reset_config = jtag_get_reset_config();
3027         if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0) {
3028                 low_direction   &= ~nTRST;      /* nTRST high impedance */
3029         }
3030         else {
3031                 low_direction   |= nTRST;
3032                 low_output      |= nTRST;
3033         }
3034
3035         low_direction   |= nSRST;
3036         low_output      |= nSRST;
3037
3038         /* initialize low byte for jtag */
3039         buf[0] = 0x80;          /* command "set data bits low byte" */
3040         buf[1] = low_output;
3041         buf[2] = low_direction;
3042         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
3043
3044         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3)) {
3045                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (low)");
3046                 return ERROR_JTAG_INIT_FAILED;
3047         }
3048
3049         high_output    = 0x0;
3050         high_direction = 0x00;
3051
3052
3053         /* initialize high port */
3054         buf[0] = 0x82;              /* command "set data bits high byte" */
3055         buf[1] = high_output;       /* value */
3056         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
3057         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
3058
3059         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3)) {
3060                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (high)");
3061                 return ERROR_JTAG_INIT_FAILED;
3062         }
3063
3064         return ERROR_OK;
3065 }
3066
3067 static void icebear_jtag_reset(int trst, int srst) {
3068
3069         if (trst == 1) {
3070                 low_direction   |= nTRST;
3071                 low_output      &= ~nTRST;
3072         }
3073         else if (trst == 0) {
3074                 enum reset_types jtag_reset_config = jtag_get_reset_config();
3075                 if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0)
3076                         low_direction   &= ~nTRST;
3077                 else
3078                         low_output      |= nTRST;
3079         }
3080
3081         if (srst == 1) {
3082                 low_output &= ~nSRST;
3083         }
3084         else if (srst == 0) {
3085                 low_output |= nSRST;
3086         }
3087
3088         /* command "set data bits low byte" */
3089         buffer_write(0x80);
3090         buffer_write(low_output);
3091         buffer_write(low_direction);
3092
3093         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
3094 }
3095
3096 /* ---------------------------------------------------------------------
3097  * Support for Signalyzer H2 and Signalyzer H4
3098  * JTAG adapter from Xverve Technologies Inc.
3099  * http://www.signalyzer.com or http://www.xverve.com
3100  *
3101  * Author: Oleg Seiljus, oleg@signalyzer.com
3102  */
3103 static unsigned char signalyzer_h_side;
3104 static unsigned int signalyzer_h_adapter_type;
3105
3106 static int signalyzer_h_ctrl_write(int address, unsigned short value);
3107
3108 #if BUILD_FT2232_FTD2XX == 1
3109 static int signalyzer_h_ctrl_read(int address, unsigned short *value);
3110 #endif
3111
3112 #define SIGNALYZER_COMMAND_ADDR                                 128
3113 #define SIGNALYZER_DATA_BUFFER_ADDR                             129
3114
3115 #define SIGNALYZER_COMMAND_VERSION                              0x41
3116 #define SIGNALYZER_COMMAND_RESET                                0x42
3117 #define SIGNALYZER_COMMAND_POWERCONTROL_GET             0x50
3118 #define SIGNALYZER_COMMAND_POWERCONTROL_SET             0x51
3119 #define SIGNALYZER_COMMAND_PWM_SET                              0x52
3120 #define SIGNALYZER_COMMAND_LED_SET                              0x53
3121 #define SIGNALYZER_COMMAND_ADC                                  0x54
3122 #define SIGNALYZER_COMMAND_GPIO_STATE                   0x55
3123 #define SIGNALYZER_COMMAND_GPIO_MODE                    0x56
3124 #define SIGNALYZER_COMMAND_GPIO_PORT                    0x57
3125 #define SIGNALYZER_COMMAND_I2C                                  0x58
3126
3127 #define SIGNALYZER_CHAN_A                                               1
3128 #define SIGNALYZER_CHAN_B                                               2
3129 /* LEDS use channel C */
3130 #define SIGNALYZER_CHAN_C                                               4
3131
3132 #define SIGNALYZER_LED_GREEN                                    1
3133 #define SIGNALYZER_LED_RED                                              2
3134
3135 #define SIGNALYZER_MODULE_TYPE_EM_LT16_A                0x0301
3136 #define SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG              0x0302
3137 #define SIGNALYZER_MODULE_TYPE_EM_JTAG                  0x0303
3138 #define SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P    0x0304
3139 #define SIGNALYZER_MODULE_TYPE_EM_JTAG_P                0x0305
3140
3141
3142 static int signalyzer_h_ctrl_write(int address, unsigned short value)
3143 {
3144 #if BUILD_FT2232_FTD2XX == 1
3145         return FT_WriteEE(ftdih, address, value);
3146 #elif BUILD_FT2232_LIBFTDI == 1
3147         return 0;
3148 #endif
3149 }
3150
3151 #if BUILD_FT2232_FTD2XX == 1
3152 static int signalyzer_h_ctrl_read(int address, unsigned short *value)
3153 {
3154         return FT_ReadEE(ftdih, address, value);
3155 }
3156 #endif
3157
3158 static int signalyzer_h_led_set(unsigned char channel, unsigned char led,
3159         int on_time_ms, int off_time_ms, unsigned char cycles)
3160 {
3161         unsigned char on_time;
3162         unsigned char off_time;
3163
3164         if (on_time_ms < 0xFFFF)
3165                 on_time = (unsigned char)(on_time_ms / 62);
3166         else
3167                 on_time = 0xFF;
3168
3169         off_time = (unsigned char)(off_time_ms / 62);
3170
3171 #if BUILD_FT2232_FTD2XX == 1
3172         FT_STATUS status;
3173
3174         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3175                         ((uint32_t)(channel << 8) | led))) != FT_OK)
3176         {
3177                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %lu", status);
3178                 return ERROR_JTAG_DEVICE_ERROR;
3179         }
3180
3181         if ((status = signalyzer_h_ctrl_write(
3182                         (SIGNALYZER_DATA_BUFFER_ADDR + 1),
3183                         ((uint32_t)(on_time << 8) | off_time))) != FT_OK)
3184         {
3185                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %lu", status);
3186                 return ERROR_JTAG_DEVICE_ERROR;
3187         }
3188
3189         if ((status = signalyzer_h_ctrl_write(
3190                         (SIGNALYZER_DATA_BUFFER_ADDR + 2),
3191                         ((uint32_t)cycles))) != FT_OK)
3192         {
3193                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %lu", status);
3194                 return ERROR_JTAG_DEVICE_ERROR;
3195         }
3196
3197         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3198                         SIGNALYZER_COMMAND_LED_SET)) != FT_OK)
3199         {
3200                 LOG_ERROR("signalyzer_h_ctrl_write  returned: %lu", status);
3201                 return ERROR_JTAG_DEVICE_ERROR;
3202         }
3203
3204         return ERROR_OK;
3205 #elif BUILD_FT2232_LIBFTDI == 1
3206         int retval;
3207
3208         if ((retval = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3209                         ((uint32_t)(channel << 8) | led))) < 0)
3210         {
3211                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3212                                 ftdi_get_error_string(&ftdic));
3213                 return ERROR_JTAG_DEVICE_ERROR;
3214         }
3215
3216         if ((retval = signalyzer_h_ctrl_write(
3217                         (SIGNALYZER_DATA_BUFFER_ADDR + 1),
3218                         ((uint32_t)(on_time << 8) | off_time))) < 0)
3219         {
3220                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3221                                 ftdi_get_error_string(&ftdic));
3222                 return ERROR_JTAG_DEVICE_ERROR;
3223         }
3224
3225         if ((retval = signalyzer_h_ctrl_write(
3226                         (SIGNALYZER_DATA_BUFFER_ADDR + 2),
3227                         (uint32_t)cycles)) < 0)
3228         {
3229                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3230                                 ftdi_get_error_string(&ftdic));
3231                 return ERROR_JTAG_DEVICE_ERROR;
3232         }
3233
3234         if ((retval = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3235                         SIGNALYZER_COMMAND_LED_SET)) < 0)
3236         {
3237                 LOG_ERROR("signalyzer_h_ctrl_write returned: %s",
3238                                 ftdi_get_error_string(&ftdic));
3239                 return ERROR_JTAG_DEVICE_ERROR;
3240         }
3241
3242         return ERROR_OK;
3243 #endif
3244 }
3245
3246 static int signalyzer_h_init(void)
3247 {
3248 #if BUILD_FT2232_FTD2XX == 1
3249         FT_STATUS status;
3250         int i;
3251 #endif
3252
3253         char *end_of_desc;
3254
3255         uint16_t read_buf[12];
3256         uint8_t  buf[3];
3257         uint32_t bytes_written;
3258
3259         /* turn on center green led */
3260         signalyzer_h_led_set(SIGNALYZER_CHAN_C, SIGNALYZER_LED_GREEN,
3261                         0xFFFF, 0x00, 0x00);
3262
3263         /* determine what channel config wants to open
3264          * TODO: change me... current implementation is made to work
3265          * with openocd description parsing.
3266          */
3267         end_of_desc = strrchr(ft2232_device_desc, 0x00);
3268
3269         if (end_of_desc)
3270         {
3271                 signalyzer_h_side = *(end_of_desc - 1);
3272                 if (signalyzer_h_side == 'B')
3273                         signalyzer_h_side = SIGNALYZER_CHAN_B;
3274                 else
3275                         signalyzer_h_side = SIGNALYZER_CHAN_A;
3276         }
3277         else
3278         {
3279                 LOG_ERROR("No Channel was specified");
3280                 return ERROR_FAIL;
3281         }
3282
3283         signalyzer_h_led_set(signalyzer_h_side, SIGNALYZER_LED_GREEN,
3284                         1000, 1000, 0xFF);
3285
3286 #if BUILD_FT2232_FTD2XX == 1
3287         /* read signalyzer versionining information */
3288         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3289                         SIGNALYZER_COMMAND_VERSION)) != FT_OK)
3290         {
3291                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3292                 return ERROR_JTAG_DEVICE_ERROR;
3293         }
3294
3295         for (i = 0; i < 10; i++)
3296         {
3297                 if ((status = signalyzer_h_ctrl_read(
3298                         (SIGNALYZER_DATA_BUFFER_ADDR + i),
3299                         &read_buf[i])) != FT_OK)
3300                 {
3301                         LOG_ERROR("signalyzer_h_ctrl_read returned: %lu",
3302                                         status);
3303                         return ERROR_JTAG_DEVICE_ERROR;
3304                 }
3305         }
3306
3307         LOG_INFO("Signalyzer: ID info: { %.4x %.4x %.4x %.4x %.4x %.4x %.4x }",
3308                         read_buf[0], read_buf[1], read_buf[2], read_buf[3],
3309                         read_buf[4], read_buf[5], read_buf[6]);
3310
3311         /* set gpio register */
3312         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3313                         (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3314         {
3315                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3316                 return ERROR_JTAG_DEVICE_ERROR;
3317         }
3318
3319         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR + 1,
3320                         0x0404)) != FT_OK)
3321         {
3322                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3323                 return ERROR_JTAG_DEVICE_ERROR;
3324         }
3325
3326         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3327                         SIGNALYZER_COMMAND_GPIO_STATE)) != FT_OK)
3328         {
3329                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3330                 return ERROR_JTAG_DEVICE_ERROR;
3331         }
3332
3333         /* read adapter type information */
3334         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_DATA_BUFFER_ADDR,
3335                         ((uint32_t)(signalyzer_h_side << 8) | 0x01))) != FT_OK)
3336         {
3337                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3338                 return ERROR_JTAG_DEVICE_ERROR;
3339         }
3340
3341         if ((status = signalyzer_h_ctrl_write(
3342                         (SIGNALYZER_DATA_BUFFER_ADDR + 1), 0xA000)) != FT_OK)
3343         {
3344                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3345                 return ERROR_JTAG_DEVICE_ERROR;
3346         }
3347
3348         if ((status = signalyzer_h_ctrl_write(
3349                         (SIGNALYZER_DATA_BUFFER_ADDR + 2), 0x0008)) != FT_OK)
3350         {
3351                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3352                 return ERROR_JTAG_DEVICE_ERROR;
3353         }
3354
3355         if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3356                         SIGNALYZER_COMMAND_I2C)) != FT_OK)
3357         {
3358                 LOG_ERROR("signalyzer_h_ctrl_write returned: %lu", status);
3359                 return ERROR_JTAG_DEVICE_ERROR;
3360         }
3361
3362         usleep(100000);
3363
3364         if ((status = signalyzer_h_ctrl_read(SIGNALYZER_COMMAND_ADDR,
3365                         &read_buf[0])) != FT_OK)
3366         {
3367                 LOG_ERROR("signalyzer_h_ctrl_read returned: %lu", status);
3368                 return ERROR_JTAG_DEVICE_ERROR;
3369         }
3370
3371         if (read_buf[0] != 0x0498)
3372                 signalyzer_h_adapter_type = 0x0000;
3373         else
3374         {
3375                 for (i = 0; i < 4; i++)
3376                 {
3377                         if ((status = signalyzer_h_ctrl_read(
3378                                         (SIGNALYZER_DATA_BUFFER_ADDR + i),
3379                                         &read_buf[i])) != FT_OK)
3380                         {
3381                                 LOG_ERROR("signalyzer_h_ctrl_read returned: %lu",
3382                                         status);
3383                                 return ERROR_JTAG_DEVICE_ERROR;
3384                         }
3385                 }
3386
3387                 signalyzer_h_adapter_type = read_buf[0];
3388         }
3389
3390 #elif BUILD_FT2232_LIBFTDI == 1
3391         /* currently libftdi does not allow reading individual eeprom
3392          * locations, therefore adapter type cannot be detected.
3393          * override with most common type
3394          */
3395         signalyzer_h_adapter_type = SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG;
3396 #endif
3397
3398         enum reset_types jtag_reset_config = jtag_get_reset_config();
3399
3400         /* ADAPTOR: EM_LT16_A */
3401         if (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_LT16_A)
3402         {
3403                 LOG_INFO("Signalyzer: EM-LT (16-channel level translator) "
3404                         "detected. (HW: %2x).", (read_buf[1] >> 8));
3405
3406                 nTRST    = 0x10;
3407                 nTRSTnOE = 0x10;
3408                 nSRST    = 0x20;
3409                 nSRSTnOE = 0x20;
3410
3411                 low_output     = 0x08;
3412                 low_direction  = 0x1b;
3413
3414                 high_output    = 0x0;
3415                 high_direction = 0x0;
3416
3417                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3418                 {
3419                         low_direction &= ~nTRSTnOE; /* nTRST input */
3420                         low_output    &= ~nTRST;    /* nTRST = 0 */
3421                 }
3422                 else
3423                 {
3424                         low_direction |= nTRSTnOE;  /* nTRST output */
3425                         low_output    |= nTRST;     /* nTRST = 1 */
3426                 }
3427
3428                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3429                 {
3430                         low_direction |= nSRSTnOE;  /* nSRST output */
3431                         low_output    |= nSRST;     /* nSRST = 1 */
3432                 }
3433                 else
3434                 {
3435                         low_direction &= ~nSRSTnOE; /* nSRST input */
3436                         low_output    &= ~nSRST;    /* nSRST = 0 */
3437                 }
3438
3439 #if BUILD_FT2232_FTD2XX == 1
3440                 /* enable power to the module */
3441                 if ((status = signalyzer_h_ctrl_write(
3442                                 SIGNALYZER_DATA_BUFFER_ADDR,
3443                                 ((uint32_t)(signalyzer_h_side << 8) | 0x01)))
3444                         != FT_OK)
3445                 {
3446                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3447                                 status);
3448                         return ERROR_JTAG_DEVICE_ERROR;
3449                 }
3450
3451                 if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3452                                 SIGNALYZER_COMMAND_POWERCONTROL_SET)) != FT_OK)
3453                 {
3454                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3455                                         status);
3456                         return ERROR_JTAG_DEVICE_ERROR;
3457                 }
3458
3459                 /* set gpio mode register */
3460                 if ((status = signalyzer_h_ctrl_write(
3461                                 SIGNALYZER_DATA_BUFFER_ADDR,
3462                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3463                 {
3464                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3465                                         status);
3466                         return ERROR_JTAG_DEVICE_ERROR;
3467                 }
3468
3469                 if ((status = signalyzer_h_ctrl_write(
3470                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x0000))
3471                         != FT_OK)
3472                 {
3473                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3474                                         status);
3475                         return ERROR_JTAG_DEVICE_ERROR;
3476                 }
3477
3478                 if ((status = signalyzer_h_ctrl_write(SIGNALYZER_COMMAND_ADDR,
3479                                 SIGNALYZER_COMMAND_GPIO_MODE)) != FT_OK)
3480                 {
3481                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3482                                         status);
3483                         return ERROR_JTAG_DEVICE_ERROR;
3484                 }
3485
3486                 /* set gpio register */
3487                 if ((status = signalyzer_h_ctrl_write(
3488                                 SIGNALYZER_DATA_BUFFER_ADDR,
3489                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3490                 {
3491                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3492                                         status);
3493                         return ERROR_JTAG_DEVICE_ERROR;
3494                 }
3495
3496                 if ((status = signalyzer_h_ctrl_write(
3497                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x4040))
3498                         != FT_OK)
3499                 {
3500                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3501                                         status);
3502                         return ERROR_JTAG_DEVICE_ERROR;
3503                 }
3504
3505                 if ((status = signalyzer_h_ctrl_write(
3506                                 SIGNALYZER_COMMAND_ADDR,
3507                                 SIGNALYZER_COMMAND_GPIO_STATE)) != FT_OK)
3508                 {
3509                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3510                                         status);
3511                         return ERROR_JTAG_DEVICE_ERROR;
3512                 }
3513 #endif
3514         }
3515
3516         /* ADAPTOR: EM_ARM_JTAG, EM_ARM_JTAG_P, EM_JTAG, EM_JTAG_P */
3517         else if ((signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG) ||
3518                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P) ||
3519                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG)  ||
3520                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG_P))
3521         {
3522                 if (signalyzer_h_adapter_type
3523                                 == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG)
3524                         LOG_INFO("Signalyzer: EM-ARM-JTAG (ARM JTAG) "
3525                                 "detected. (HW: %2x).", (read_buf[1] >> 8));
3526                 else if (signalyzer_h_adapter_type
3527                                 == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P)
3528                         LOG_INFO("Signalyzer: EM-ARM-JTAG_P "
3529                                 "(ARM JTAG with PSU) detected. (HW: %2x).",
3530                                 (read_buf[1] >> 8));
3531                 else if (signalyzer_h_adapter_type
3532                                 == SIGNALYZER_MODULE_TYPE_EM_JTAG)
3533                         LOG_INFO("Signalyzer: EM-JTAG (Generic JTAG) "
3534                                 "detected. (HW: %2x).", (read_buf[1] >> 8));
3535                 else if (signalyzer_h_adapter_type
3536                                 == SIGNALYZER_MODULE_TYPE_EM_JTAG_P)
3537                         LOG_INFO("Signalyzer: EM-JTAG-P "
3538                                 "(Generic JTAG with PSU) detected. (HW: %2x).",
3539                                 (read_buf[1] >> 8));
3540
3541                 nTRST          = 0x02;
3542                 nTRSTnOE       = 0x04;
3543                 nSRST          = 0x08;
3544                 nSRSTnOE       = 0x10;
3545
3546                 low_output     = 0x08;
3547                 low_direction  = 0x1b;
3548
3549                 high_output    = 0x0;
3550                 high_direction = 0x1f;
3551
3552                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3553                 {
3554                         high_output |= nTRSTnOE;
3555                         high_output &= ~nTRST;
3556                 }
3557                 else
3558                 {
3559                         high_output &= ~nTRSTnOE;
3560                         high_output |= nTRST;
3561                 }
3562
3563                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3564                 {
3565                         high_output &= ~nSRSTnOE;
3566                         high_output |= nSRST;
3567                 }
3568                 else
3569                 {
3570                         high_output |= nSRSTnOE;
3571                         high_output &= ~nSRST;
3572                 }
3573
3574 #if BUILD_FT2232_FTD2XX == 1
3575                 /* enable power to the module */
3576                 if ((status = signalyzer_h_ctrl_write(
3577                                 SIGNALYZER_DATA_BUFFER_ADDR,
3578                                 ((uint32_t)(signalyzer_h_side << 8) | 0x01)))
3579                         != FT_OK)
3580                 {
3581                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3582                                         status);
3583                         return ERROR_JTAG_DEVICE_ERROR;
3584                 }
3585
3586                 if ((status = signalyzer_h_ctrl_write(
3587                                 SIGNALYZER_COMMAND_ADDR,
3588                                 SIGNALYZER_COMMAND_POWERCONTROL_SET)) != FT_OK)
3589                 {
3590                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3591                                         status);
3592                         return ERROR_JTAG_DEVICE_ERROR;
3593                 }
3594
3595                 /* set gpio mode register (IO_16 and IO_17 set as analog
3596                  * inputs, other is gpio)
3597                  */
3598                 if ((status = signalyzer_h_ctrl_write(
3599                                 SIGNALYZER_DATA_BUFFER_ADDR,
3600                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3601                 {
3602                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3603                                         status);
3604                         return ERROR_JTAG_DEVICE_ERROR;
3605                 }
3606
3607                 if ((status = signalyzer_h_ctrl_write(
3608                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x0060))
3609                         != FT_OK)
3610                 {
3611                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3612                                         status);
3613                         return ERROR_JTAG_DEVICE_ERROR;
3614                 }
3615
3616                 if ((status = signalyzer_h_ctrl_write(
3617                                 SIGNALYZER_COMMAND_ADDR,
3618                                 SIGNALYZER_COMMAND_GPIO_MODE)) != FT_OK)
3619                 {
3620                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3621                                         status);
3622                         return ERROR_JTAG_DEVICE_ERROR;
3623                 }
3624
3625                 /* set gpio register (all inputs, for -P modules,
3626                  * PSU will be turned off)
3627                  */
3628                 if ((status = signalyzer_h_ctrl_write(
3629                                 SIGNALYZER_DATA_BUFFER_ADDR,
3630                                 (uint32_t)(signalyzer_h_side << 8))) != FT_OK)
3631                 {
3632                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3633                                         status);
3634                         return ERROR_JTAG_DEVICE_ERROR;
3635                 }
3636
3637                 if ((status = signalyzer_h_ctrl_write(
3638                                 SIGNALYZER_DATA_BUFFER_ADDR + 1, 0x0000))
3639                         != FT_OK)
3640                 {
3641                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3642                                         status);
3643                         return ERROR_JTAG_DEVICE_ERROR;
3644                 }
3645
3646                 if ((status = signalyzer_h_ctrl_write(
3647                                 SIGNALYZER_COMMAND_ADDR,
3648                                 SIGNALYZER_COMMAND_GPIO_STATE)) != FT_OK)
3649                 {
3650                         LOG_ERROR("signalyzer_h_ctrl_write returned: %lu",
3651                                         status);
3652                         return ERROR_JTAG_DEVICE_ERROR;
3653                 }
3654 #endif
3655         }
3656
3657         else if (signalyzer_h_adapter_type == 0x0000)
3658         {
3659                 LOG_INFO("Signalyzer: No external modules were detected.");
3660
3661                 nTRST    = 0x10;
3662                 nTRSTnOE = 0x10;
3663                 nSRST    = 0x20;
3664                 nSRSTnOE = 0x20;
3665
3666                 low_output     = 0x08;
3667                 low_direction  = 0x1b;
3668
3669                 high_output    = 0x0;
3670                 high_direction = 0x0;
3671
3672                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3673                 {
3674                         low_direction &= ~nTRSTnOE; /* nTRST input */
3675                         low_output    &= ~nTRST;    /* nTRST = 0 */
3676                 }
3677                 else
3678                 {
3679                         low_direction |= nTRSTnOE;  /* nTRST output */
3680                         low_output    |= nTRST;     /* nTRST = 1 */
3681                 }
3682
3683                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3684                 {
3685                         low_direction |= nSRSTnOE;  /* nSRST output */
3686                         low_output    |= nSRST;     /* nSRST = 1 */
3687                 }
3688                 else
3689                 {
3690                         low_direction &= ~nSRSTnOE; /* nSRST input */
3691                         low_output    &= ~nSRST;    /* nSRST = 0 */
3692                 }
3693         }
3694         else
3695         {
3696                 LOG_ERROR("Unknown module type is detected: %.4x",
3697                                 signalyzer_h_adapter_type);
3698                 return ERROR_JTAG_DEVICE_ERROR;
3699         }
3700
3701         /* initialize low byte of controller for jtag operation */
3702         buf[0] = 0x80;
3703         buf[1] = low_output;
3704         buf[2] = low_direction;
3705
3706         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK)
3707                         || (bytes_written != 3))
3708         {
3709                 LOG_ERROR("couldn't initialize Signalyzer-H layout");
3710                 return ERROR_JTAG_INIT_FAILED;
3711         }
3712
3713 #if BUILD_FT2232_FTD2XX == 1
3714         if (ftdi_device == FT_DEVICE_2232H)
3715         {
3716                 /* initialize high byte of controller for jtag operation */
3717                 buf[0] = 0x82;
3718                 buf[1] = high_output;
3719                 buf[2] = high_direction;
3720
3721                 if ((ft2232_write(buf, 3, &bytes_written) != ERROR_OK)
3722                                 || (bytes_written != 3))
3723                 {
3724                         LOG_ERROR("couldn't initialize Signalyzer-H layout");
3725                         return ERROR_JTAG_INIT_FAILED;
3726                 }
3727         }
3728 #elif BUILD_FT2232_LIBFTDI == 1
3729         if (ftdi_device == TYPE_2232H)
3730         {
3731                 /* initialize high byte of controller for jtag operation */
3732                 buf[0] = 0x82;
3733                 buf[1] = high_output;
3734                 buf[2] = high_direction;
3735
3736                 if ((ft2232_write(buf, 3, &bytes_written) != ERROR_OK)
3737                                 || (bytes_written != 3))
3738                 {
3739                         LOG_ERROR("couldn't initialize Signalyzer-H layout");
3740                         return ERROR_JTAG_INIT_FAILED;
3741                 }
3742         }
3743 #endif
3744         return ERROR_OK;
3745 }
3746
3747 static void signalyzer_h_reset(int trst, int srst)
3748 {
3749         enum reset_types jtag_reset_config = jtag_get_reset_config();
3750
3751         /* ADAPTOR: EM_LT16_A */
3752         if (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_LT16_A)
3753         {
3754                 if (trst == 1)
3755                 {
3756                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3757                                 /* switch to output pin (output is low) */
3758                                 low_direction |= nTRSTnOE;
3759                         else
3760                                 /* switch output low */
3761                                 low_output &= ~nTRST;
3762                 }
3763                 else if (trst == 0)
3764                 {
3765                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3766                                 /* switch to input pin (high-Z + internal
3767                                  * and external pullup) */
3768                                 low_direction &= ~nTRSTnOE;
3769                         else
3770                                 /* switch output high */
3771                                 low_output |= nTRST;
3772                 }
3773
3774                 if (srst == 1)
3775                 {
3776                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3777                                 /* switch output low */
3778                                 low_output &= ~nSRST;
3779                         else
3780                                 /* switch to output pin (output is low) */
3781                                 low_direction |= nSRSTnOE;
3782                 }
3783                 else if (srst == 0)
3784                 {
3785                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3786                                 /* switch output high */
3787                                 low_output |= nSRST;
3788                         else
3789                                 /* switch to input pin (high-Z) */
3790                                 low_direction &= ~nSRSTnOE;
3791                 }
3792
3793                 /* command "set data bits low byte" */
3794                 buffer_write(0x80);
3795                 buffer_write(low_output);
3796                 buffer_write(low_direction);
3797                 LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, "
3798                                 "low_direction: 0x%2.2x",
3799                                 trst, srst, low_output, low_direction);
3800         }
3801         /* ADAPTOR: EM_ARM_JTAG,  EM_ARM_JTAG_P, EM_JTAG, EM_JTAG_P */
3802         else if ((signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG) ||
3803                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_ARM_JTAG_P) ||
3804                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG)  ||
3805                                 (signalyzer_h_adapter_type == SIGNALYZER_MODULE_TYPE_EM_JTAG_P))
3806         {
3807                 if (trst == 1)
3808                 {
3809                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3810                                 high_output &= ~nTRSTnOE;
3811                         else
3812                                 high_output &= ~nTRST;
3813                 }
3814                 else if (trst == 0)
3815                 {
3816                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3817                                 high_output |= nTRSTnOE;
3818                         else
3819                                 high_output |= nTRST;
3820                 }
3821
3822                 if (srst == 1)
3823                 {
3824                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3825                                 high_output &= ~nSRST;
3826                         else
3827                                 high_output &= ~nSRSTnOE;
3828                 }
3829                 else if (srst == 0)
3830                 {
3831                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3832                                 high_output |= nSRST;
3833                         else
3834                                 high_output |= nSRSTnOE;
3835                 }
3836
3837                 /* command "set data bits high byte" */
3838                 buffer_write(0x82);
3839                 buffer_write(high_output);
3840                 buffer_write(high_direction);
3841                 LOG_INFO("trst: %i, srst: %i, high_output: 0x%2.2x, "
3842                                 "high_direction: 0x%2.2x",
3843                                 trst, srst, high_output, high_direction);
3844         }
3845         else if (signalyzer_h_adapter_type == 0x0000)
3846         {
3847                 if (trst == 1)
3848                 {
3849                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3850                                 /* switch to output pin (output is low) */
3851                                 low_direction |= nTRSTnOE;
3852                         else
3853                                 /* switch output low */
3854                                 low_output &= ~nTRST;
3855                 }
3856                 else if (trst == 0)
3857                 {
3858                         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
3859                                 /* switch to input pin (high-Z + internal
3860                                  * and external pullup) */
3861                                 low_direction &= ~nTRSTnOE;
3862                         else
3863                                 /* switch output high */
3864                                 low_output |= nTRST;
3865                 }
3866
3867                 if (srst == 1)
3868                 {
3869                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3870                                 /* switch output low */
3871                                 low_output &= ~nSRST;
3872                         else
3873                                 /* switch to output pin (output is low) */
3874                                 low_direction |= nSRSTnOE;
3875                 }
3876                 else if (srst == 0)
3877                 {
3878                         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
3879                                 /* switch output high */
3880                                 low_output |= nSRST;
3881                         else
3882                                 /* switch to input pin (high-Z) */
3883                                 low_direction &= ~nSRSTnOE;
3884                 }
3885
3886                 /* command "set data bits low byte" */
3887                 buffer_write(0x80);
3888                 buffer_write(low_output);
3889                 buffer_write(low_direction);
3890                 LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, "
3891                                 "low_direction: 0x%2.2x",
3892                                 trst, srst, low_output, low_direction);
3893         }
3894 }
3895
3896 static void signalyzer_h_blink(void)
3897 {
3898         signalyzer_h_led_set(signalyzer_h_side, SIGNALYZER_LED_RED, 100, 0, 1);
3899 }