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