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