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