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