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