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