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