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