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