]> git.sur5r.net Git - openocd/blob - src/jtag/ft2232.c
e17d51d6b0530f2fcda5761d983a132b14f3589e
[openocd] / src / jtag / ft2232.c
1 /***************************************************************************
2 *   Copyright (C) 2004, 2006 by Dominic Rath                              *
3 *   Dominic.Rath@gmx.de                                                   *
4 *                                                                         *
5 *   Copyright (C) 2008 by Spencer Oliver                                  *
6 *   spen@spen-soft.co.uk                                                  *
7 *                                                                         *
8 *   Copyright (C) 2009 by SoftPLC Corporation.  http://softplc.com        *
9 *       Dick Hollenbeck <dick@softplc.com>                                    *
10 *                                                                         *
11 *   This program is free software; you can redistribute it and/or modify  *
12 *   it under the terms of the GNU General Public License as published by  *
13 *   the Free Software Foundation; either version 2 of the License, or     *
14 *   (at your option) any later version.                                   *
15 *                                                                         *
16 *   This program is distributed in the hope that it will be useful,       *
17 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19 *   GNU General Public License for more details.                          *
20 *                                                                         *
21 *   You should have received a copy of the GNU General Public License     *
22 *   along with this program; if not, write to the                         *
23 *   Free Software Foundation, Inc.,                                       *
24 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
25 ***************************************************************************/
26
27
28 /* This code uses information contained in the MPSSE specification which was
29  * found here:
30  * http://www.ftdichip.com/Documents/AppNotes/AN2232C-01_MPSSE_Cmnd.pdf
31  * Hereafter this is called the "MPSSE Spec".
32  *
33  * The datasheet for the ftdichip.com's FT2232D part is here:
34  * http://www.ftdichip.com/Documents/DataSheets/DS_FT2232D.pdf
35  */
36
37
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
41
42 /* project specific includes */
43 #include "interface.h"
44 #include "commands.h"
45 #include "time_support.h"
46
47 #if IS_CYGWIN == 1
48 #include <windows.h>
49 #endif
50
51 #include <assert.h>
52
53 #if (BUILD_FT2232_FTD2XX == 1 && BUILD_FT2232_LIBFTDI == 1)
54 #error "BUILD_FT2232_FTD2XX && BUILD_FT2232_LIBFTDI are mutually exclusive"
55 #elif (BUILD_FT2232_FTD2XX != 1 && BUILD_FT2232_LIBFTDI != 1)
56 #error "BUILD_FT2232_FTD2XX || BUILD_FT2232_LIBFTDI must be chosen"
57 #endif
58
59 /* FT2232 access library includes */
60 #if BUILD_FT2232_FTD2XX == 1
61 #include <ftd2xx.h>
62 #elif BUILD_FT2232_LIBFTDI == 1
63 #include <ftdi.h>
64 #endif
65
66 /* max TCK for the high speed devices 30000 kHz */
67 #define FTDI_2232H_4232H_MAX_TCK        30000
68
69 static int ft2232_execute_queue(void);
70
71 static int ft2232_speed(int speed);
72 static int ft2232_speed_div(int speed, int* khz);
73 static int ft2232_khz(int khz, int* jtag_speed);
74 static int ft2232_register_commands(struct command_context_s* cmd_ctx);
75 static int ft2232_init(void);
76 static int ft2232_quit(void);
77
78 static int ft2232_handle_device_desc_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
79 static int ft2232_handle_serial_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
80 static int ft2232_handle_layout_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
81 static int ft2232_handle_vid_pid_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
82 static int ft2232_handle_latency_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
83
84
85 /**
86  * Send out \a num_cycles on the TCK line while the TAP(s) are in a
87  * stable state.  Calling code must ensure that current state is stable,
88  * that verification is not done in here.
89  *
90  * @param num_cycles The number of clocks cycles to send.
91  * @param cmd The command to send.
92  *
93  * @returns ERROR_OK on success, or ERROR_JTAG_QUEUE_FAILED on failure.
94  */
95 static int ft2232_stableclocks(int num_cycles, jtag_command_t* cmd);
96
97 /* max TCK for the high speed devices 30000 kHz */
98 #define FTDI_2232H_4232H_MAX_TCK        30000
99
100 static char *       ft2232_device_desc_A = NULL;
101 static char*        ft2232_device_desc = NULL;
102 static char*        ft2232_serial  = NULL;
103 static char*        ft2232_layout  = NULL;
104 static uint8_t          ft2232_latency = 2;
105 static unsigned         ft2232_max_tck = 6000;
106
107
108 #define MAX_USB_IDS 8
109 /* vid = pid = 0 marks the end of the list */
110 static uint16_t ft2232_vid[MAX_USB_IDS + 1] = { 0x0403, 0 };
111 static uint16_t ft2232_pid[MAX_USB_IDS + 1] = { 0x6010, 0 };
112
113 typedef struct ft2232_layout_s
114 {
115         char* name;
116         int (*init)(void);
117         void (*reset)(int trst, int srst);
118         void (*blink)(void);
119 } ft2232_layout_t;
120
121 /* init procedures for supported layouts */
122 static int usbjtag_init(void);
123 static int jtagkey_init(void);
124 static int olimex_jtag_init(void);
125 static int flyswatter_init(void);
126 static int turtle_init(void);
127 static int comstick_init(void);
128 static int stm32stick_init(void);
129 static int axm0432_jtag_init(void);
130 static int sheevaplug_init(void);
131 static int icebear_jtag_init(void);
132 static int cortino_jtag_init(void);
133
134 /* reset procedures for supported layouts */
135 static void usbjtag_reset(int trst, int srst);
136 static void jtagkey_reset(int trst, int srst);
137 static void olimex_jtag_reset(int trst, int srst);
138 static void flyswatter_reset(int trst, int srst);
139 static void turtle_reset(int trst, int srst);
140 static void comstick_reset(int trst, int srst);
141 static void stm32stick_reset(int trst, int srst);
142 static void axm0432_jtag_reset(int trst, int srst);
143 static void sheevaplug_reset(int trst, int srst);
144 static void icebear_jtag_reset(int trst, int srst);
145
146 /* blink procedures for layouts that support a blinking led */
147 static void olimex_jtag_blink(void);
148 static void flyswatter_jtag_blink(void);
149 static void turtle_jtag_blink(void);
150
151 static const ft2232_layout_t  ft2232_layouts[] =
152 {
153         { "usbjtag",              usbjtag_init,              usbjtag_reset,      NULL                    },
154         { "jtagkey",              jtagkey_init,              jtagkey_reset,      NULL                    },
155         { "jtagkey_prototype_v1", jtagkey_init,              jtagkey_reset,      NULL                    },
156         { "oocdlink",             jtagkey_init,              jtagkey_reset,      NULL                    },
157         { "signalyzer",           usbjtag_init,              usbjtag_reset,      NULL                    },
158         { "evb_lm3s811",          usbjtag_init,              usbjtag_reset,      NULL                    },
159         { "luminary_icdi",        usbjtag_init,              usbjtag_reset,      NULL                    },
160         { "olimex-jtag",          olimex_jtag_init,          olimex_jtag_reset,  olimex_jtag_blink       },
161         { "flyswatter",           flyswatter_init,           flyswatter_reset,   flyswatter_jtag_blink   },
162         { "turtelizer2",          turtle_init,               turtle_reset,       turtle_jtag_blink       },
163         { "comstick",             comstick_init,             comstick_reset,     NULL                    },
164         { "stm32stick",           stm32stick_init,           stm32stick_reset,   NULL                    },
165         { "axm0432_jtag",         axm0432_jtag_init,         axm0432_jtag_reset, NULL                    },
166         { "sheevaplug",           sheevaplug_init,           sheevaplug_reset,   NULL                    },
167         { "icebear",              icebear_jtag_init,         icebear_jtag_reset, NULL                    },
168         { "cortino",              cortino_jtag_init,         comstick_reset, NULL                        },
169         { NULL,                   NULL,                      NULL,               NULL                    },
170 };
171
172 static uint8_t                  nTRST, nTRSTnOE, nSRST, nSRSTnOE;
173
174 static const ft2232_layout_t *layout;
175 static uint8_t                  low_output     = 0x0;
176 static uint8_t                  low_direction  = 0x0;
177 static uint8_t                  high_output    = 0x0;
178 static uint8_t                  high_direction = 0x0;
179
180 #if BUILD_FT2232_FTD2XX == 1
181 static FT_HANDLE        ftdih = NULL;
182 static FT_DEVICE        ftdi_device = 0;
183 #elif BUILD_FT2232_LIBFTDI == 1
184 static struct ftdi_context ftdic;
185 #endif
186
187
188 static jtag_command_t* first_unsent;        /* next command that has to be sent */
189 static int             require_send;
190
191
192 /*      http://urjtag.wiki.sourceforge.net/Cable + FT2232 says:
193
194         "There is a significant difference between libftdi and libftd2xx. The latter
195         one allows to schedule up to 64*64 bytes of result data while libftdi fails
196         with more than 4*64. As a consequence, the FT2232 driver is forced to
197         perform around 16x more USB transactions for long command streams with TDO
198         capture when running with libftdi."
199
200         No idea how we get
201         #define FT2232_BUFFER_SIZE 131072
202         a comment would have been nice.
203 */
204
205 #define FT2232_BUFFER_SIZE 131072
206
207 static uint8_t*             ft2232_buffer = NULL;
208 static int             ft2232_buffer_size  = 0;
209 static int             ft2232_read_pointer = 0;
210 static int             ft2232_expect_read  = 0;
211
212 /**
213  * Function buffer_write
214  * writes a byte into the byte buffer, "ft2232_buffer", which must be sent later.
215  * @param val is the byte to send.
216  */
217 static inline void buffer_write(uint8_t val)
218 {
219         assert(ft2232_buffer);
220         assert((unsigned) ft2232_buffer_size < (unsigned) FT2232_BUFFER_SIZE);
221         ft2232_buffer[ft2232_buffer_size++] = val;
222 }
223
224 /**
225  * Function buffer_read
226  * returns a byte from the byte buffer.
227  */
228 static inline uint8_t buffer_read(void)
229 {
230         assert(ft2232_buffer);
231         assert(ft2232_read_pointer < ft2232_buffer_size);
232         return ft2232_buffer[ft2232_read_pointer++];
233 }
234
235
236 /**
237  * Clocks out \a bit_count bits on the TMS line, starting with the least
238  * significant bit of tms_bits and progressing to more significant bits.
239  * Rigorous state transition logging is done here via tap_set_state().
240  *
241  * @param mpsse_cmd One of the MPSSE TMS oriented commands such as
242  *      0x4b or 0x6b.  See the MPSSE spec referenced above for their
243  *      functionality. The MPSSE command "Clock Data to TMS/CS Pin (no Read)"
244  *      is often used for this, 0x4b.
245  *
246  * @param tms_bits Holds the sequence of bits to send.
247  * @param tms_count Tells how many bits in the sequence.
248  * @param tdi_bit A single bit to pass on to TDI before the first TCK
249  *      cycle and held static for the duration of TMS clocking.
250  *
251  * See the MPSSE spec referenced above.
252  */
253 static void clock_tms(uint8_t mpsse_cmd, int tms_bits, int tms_count, bool tdi_bit)
254 {
255         uint8_t tms_byte;
256         int     i;
257         int     tms_ndx;                                /* bit index into tms_byte */
258
259         assert(tms_count > 0);
260
261 //      LOG_DEBUG("mpsse cmd=%02x, tms_bits = 0x%08x, bit_count=%d", mpsse_cmd, tms_bits, tms_count);
262
263         for (tms_byte = tms_ndx = i = 0;   i < tms_count;   ++i, tms_bits>>=1)
264         {
265                 bool bit = tms_bits & 1;
266
267                 if (bit)
268                         tms_byte |= (1 << tms_ndx);
269
270                 /* always do state transitions in public view */
271                 tap_set_state(tap_state_transition(tap_get_state(), bit));
272
273                 /*      we wrote a bit to tms_byte just above, increment bit index.  if bit was zero
274                         also increment.
275                 */
276                 ++tms_ndx;
277
278                 if (tms_ndx == 7  || i == tms_count-1)
279                 {
280                         buffer_write(mpsse_cmd);
281                         buffer_write(tms_ndx - 1);
282
283                         /*      Bit 7 of the byte is passed on to TDI/DO before the first TCK/SK of
284                                 TMS/CS and is held static for the duration of TMS/CS clocking.
285                         */
286                         buffer_write(tms_byte | (tdi_bit << 7));
287                 }
288         }
289 }
290
291
292 /**
293  * Function get_tms_buffer_requirements
294  * returns what clock_tms() will consume if called with
295  * same \a bit_count.
296  */
297 static inline int get_tms_buffer_requirements(int bit_count)
298 {
299         return ((bit_count + 6)/7) * 3;
300 }
301
302
303 /**
304  * Function move_to_state
305  * moves the TAP controller from the current state to a
306  * \a goal_state through a path given by tap_get_tms_path().  State transition
307  * logging is performed by delegation to clock_tms().
308  *
309  * @param goal_state is the destination state for the move.
310  */
311 static void move_to_state(tap_state_t goal_state)
312 {
313         tap_state_t     start_state = tap_get_state();
314
315         /*      goal_state is 1/2 of a tuple/pair of states which allow convenient
316                 lookup of the required TMS pattern to move to this state from the
317                 start state.
318         */
319
320         /* do the 2 lookups */
321         int tms_bits  = tap_get_tms_path(start_state, goal_state);
322         int tms_count = tap_get_tms_path_len(start_state, goal_state);
323
324         DEBUG_JTAG_IO("start=%s goal=%s", tap_state_name(start_state), tap_state_name(goal_state));
325
326         clock_tms(0x4b,  tms_bits, tms_count, 0);
327 }
328
329
330 jtag_interface_t ft2232_interface =
331 {
332         .name                   = "ft2232",
333         .execute_queue          = ft2232_execute_queue,
334         .speed                  = ft2232_speed,
335         .speed_div              = ft2232_speed_div,
336         .khz                    = ft2232_khz,
337         .register_commands      = ft2232_register_commands,
338         .init                   = ft2232_init,
339         .quit                   = ft2232_quit,
340 };
341
342 static int ft2232_write(uint8_t* buf, int size, uint32_t* bytes_written)
343 {
344 #if BUILD_FT2232_FTD2XX == 1
345         FT_STATUS status;
346         DWORD   dw_bytes_written;
347         if ((status = FT_Write(ftdih, buf, size, &dw_bytes_written)) != FT_OK)
348         {
349                 *bytes_written = dw_bytes_written;
350                 LOG_ERROR("FT_Write returned: %lu", status);
351                 return ERROR_JTAG_DEVICE_ERROR;
352         }
353         else
354         {
355                 *bytes_written = dw_bytes_written;
356                 return ERROR_OK;
357         }
358 #elif BUILD_FT2232_LIBFTDI == 1
359         int retval;
360         if ((retval = ftdi_write_data(&ftdic, buf, size)) < 0)
361         {
362                 *bytes_written = 0;
363                 LOG_ERROR("ftdi_write_data: %s", ftdi_get_error_string(&ftdic));
364                 return ERROR_JTAG_DEVICE_ERROR;
365         }
366         else
367         {
368                 *bytes_written = retval;
369                 return ERROR_OK;
370         }
371 #endif
372 }
373
374
375 static int ft2232_read(uint8_t* buf, uint32_t size, uint32_t* bytes_read)
376 {
377 #if BUILD_FT2232_FTD2XX == 1
378         DWORD     dw_bytes_read;
379         FT_STATUS status;
380         int       timeout = 5;
381         *bytes_read = 0;
382
383         while ((*bytes_read < size) && timeout--)
384         {
385                 if ((status = FT_Read(ftdih, buf + *bytes_read, size -
386                                           *bytes_read, &dw_bytes_read)) != FT_OK)
387                 {
388                         *bytes_read = 0;
389                         LOG_ERROR("FT_Read returned: %lu", status);
390                         return ERROR_JTAG_DEVICE_ERROR;
391                 }
392                 *bytes_read += dw_bytes_read;
393         }
394
395 #elif BUILD_FT2232_LIBFTDI == 1
396         int retval;
397         int timeout = 100;
398         *bytes_read = 0;
399
400         while ((*bytes_read < size) && timeout--)
401         {
402                 if ((retval = ftdi_read_data(&ftdic, buf + *bytes_read, size - *bytes_read)) < 0)
403                 {
404                         *bytes_read = 0;
405                         LOG_ERROR("ftdi_read_data: %s", ftdi_get_error_string(&ftdic));
406                         return ERROR_JTAG_DEVICE_ERROR;
407                 }
408                 *bytes_read += retval;
409         }
410
411 #endif
412
413         if (*bytes_read < size)
414         {
415                 LOG_ERROR("couldn't read the requested number of bytes from FT2232 device (%i < %i)",
416                           (unsigned int)(*bytes_read),
417                           (unsigned int)size);
418                 return ERROR_JTAG_DEVICE_ERROR;
419         }
420
421         return ERROR_OK;
422 }
423
424 #ifdef BUILD_FTD2XX_HIGHSPEED
425 static bool ft2232_device_is_highspeed(void)
426 {
427         return (ftdi_device == FT_DEVICE_2232H) || (ftdi_device == FT_DEVICE_4232H);
428 }
429
430 static int ft2232_adaptive_clocking(int speed)
431 {
432         bool use_adaptive_clocking = FALSE;
433         if (0 == speed)
434         {
435                 if (ft2232_device_is_highspeed())
436                         use_adaptive_clocking = TRUE;
437                 else
438                 {
439                         LOG_ERROR("ft2232 device %lu does not support RTCK", ftdi_device);
440                         return ERROR_OK;
441                 }
442         }
443
444         uint8_t  buf = use_adaptive_clocking ? 0x96 : 0x97;
445         LOG_DEBUG("%2.2x", buf);
446
447         uint32_t bytes_written;
448         int retval = ft2232_write(&buf, 1, &bytes_written);
449         if (ERROR_OK != retval || bytes_written != 1)
450         {
451                 LOG_ERROR("unable to set adative clocking: %d", retval);
452                 return retval;
453         }
454
455         return ERROR_OK;
456 }
457 #else
458 static int ft2232_adaptive_clocking(int speed)
459 {
460         // not implemented on low-speed devices
461         return speed ? ERROR_OK : -1234;
462 }
463 #endif
464
465 static int ft2232_speed(int speed)
466 {
467         uint8_t  buf[3];
468         int retval;
469         uint32_t bytes_written;
470
471         ft2232_adaptive_clocking(speed);
472
473         buf[0] = 0x86;                  /* command "set divisor" */
474         buf[1] = speed & 0xff;          /* valueL (0 = 6MHz, 1 = 3MHz, 2 = 2.0MHz, ...*/
475         buf[2] = (speed >> 8) & 0xff;   /* valueH */
476
477         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
478         if (((retval = ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
479         {
480                 LOG_ERROR("couldn't set FT2232 TCK speed");
481                 return retval;
482         }
483
484         return ERROR_OK;
485 }
486
487
488 static int ft2232_speed_div(int speed, int* khz)
489 {
490         /* Take a look in the FT2232 manual,
491          * AN2232C-01 Command Processor for
492          * MPSSE and MCU Host Bus. Chapter 3.8 */
493
494         *khz = ft2232_max_tck / (1 + speed);
495
496         return ERROR_OK;
497 }
498
499
500 static int ft2232_khz(int khz, int* jtag_speed)
501 {
502         if (khz == 0)
503         {
504 #ifdef BUILD_FTD2XX_HIGHSPEED
505                 *jtag_speed = 0;
506                 return ERROR_OK;
507 #else
508                 LOG_DEBUG("RCLK not supported");
509                 LOG_DEBUG("If you have a high-speed FTDI device, then "
510                         "OpenOCD may be built with --enable-ftd2xx-highspeed.");
511                 return ERROR_FAIL;
512 #endif
513         }
514
515         /* Take a look in the FT2232 manual,
516          * AN2232C-01 Command Processor for
517          * MPSSE and MCU Host Bus. Chapter 3.8
518          *
519          * We will calc here with a multiplier
520          * of 10 for better rounding later. */
521
522         /* Calc speed, (ft2232_max_tck / khz) - 1 */
523         /* Use 65000 for better rounding */
524         *jtag_speed = ((ft2232_max_tck*10) / khz) - 10;
525
526         /* Add 0.9 for rounding */
527         *jtag_speed += 9;
528
529         /* Calc real speed */
530         *jtag_speed = *jtag_speed / 10;
531
532         /* Check if speed is greater than 0 */
533         if (*jtag_speed < 0)
534         {
535                 *jtag_speed = 0;
536         }
537
538         /* Check max value */
539         if (*jtag_speed > 0xFFFF)
540         {
541                 *jtag_speed = 0xFFFF;
542         }
543
544         return ERROR_OK;
545 }
546
547
548 static int ft2232_register_commands(struct command_context_s* cmd_ctx)
549 {
550         register_command(cmd_ctx, NULL, "ft2232_device_desc", ft2232_handle_device_desc_command,
551                         COMMAND_CONFIG, "the USB device description of the FTDI FT2232 device");
552         register_command(cmd_ctx, NULL, "ft2232_serial", ft2232_handle_serial_command,
553                         COMMAND_CONFIG, "the serial number of the FTDI FT2232 device");
554         register_command(cmd_ctx, NULL, "ft2232_layout", ft2232_handle_layout_command,
555                         COMMAND_CONFIG, "the layout of the FT2232 GPIO signals used to control output-enables and reset signals");
556         register_command(cmd_ctx, NULL, "ft2232_vid_pid", ft2232_handle_vid_pid_command,
557                         COMMAND_CONFIG, "the vendor ID and product ID of the FTDI FT2232 device");
558         register_command(cmd_ctx, NULL, "ft2232_latency", ft2232_handle_latency_command,
559                         COMMAND_CONFIG, "set the FT2232 latency timer to a new value");
560         return ERROR_OK;
561 }
562
563
564 static void ft2232_end_state(tap_state_t state)
565 {
566         if (tap_is_state_stable(state))
567                 tap_set_end_state(state);
568         else
569         {
570                 LOG_ERROR("BUG: %s is not a stable end state", tap_state_name(state));
571                 exit(-1);
572         }
573 }
574
575 static void ft2232_read_scan(enum scan_type type, uint8_t* buffer, int scan_size)
576 {
577         int num_bytes = (scan_size + 7) / 8;
578         int bits_left = scan_size;
579         int cur_byte  = 0;
580
581         while (num_bytes-- > 1)
582         {
583                 buffer[cur_byte++] = buffer_read();
584                 bits_left -= 8;
585         }
586
587         buffer[cur_byte] = 0x0;
588
589         /* There is one more partial byte left from the clock data in/out instructions */
590         if (bits_left > 1)
591         {
592                 buffer[cur_byte] = buffer_read() >> 1;
593         }
594         /* 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 */
595         buffer[cur_byte] = (buffer[cur_byte] | (((buffer_read()) << 1) & 0x80)) >> (8 - bits_left);
596 }
597
598
599 static void ft2232_debug_dump_buffer(void)
600 {
601         int   i;
602         char  line[256];
603         char* line_p = line;
604
605         for (i = 0; i < ft2232_buffer_size; i++)
606         {
607                 line_p += snprintf(line_p, 256 - (line_p - line), "%2.2x ", ft2232_buffer[i]);
608                 if (i % 16 == 15)
609                 {
610                         LOG_DEBUG("%s", line);
611                         line_p = line;
612                 }
613         }
614
615         if (line_p != line)
616                 LOG_DEBUG("%s", line);
617 }
618
619
620 static int ft2232_send_and_recv(jtag_command_t* first, jtag_command_t* last)
621 {
622         jtag_command_t* cmd;
623         uint8_t*             buffer;
624         int             scan_size;
625         enum scan_type  type;
626         int             retval;
627         uint32_t             bytes_written = 0;
628         uint32_t             bytes_read = 0;
629
630 #ifdef _DEBUG_USB_IO_
631         struct timeval  start, inter, inter2, end;
632         struct timeval  d_inter, d_inter2, d_end;
633 #endif
634
635 #ifdef _DEBUG_USB_COMMS_
636         LOG_DEBUG("write buffer (size %i):", ft2232_buffer_size);
637         ft2232_debug_dump_buffer();
638 #endif
639
640 #ifdef _DEBUG_USB_IO_
641         gettimeofday(&start, NULL);
642 #endif
643
644         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
645         {
646                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
647                 return retval;
648         }
649
650 #ifdef _DEBUG_USB_IO_
651         gettimeofday(&inter, NULL);
652 #endif
653
654         if (ft2232_expect_read)
655         {
656                 int timeout = 100;
657                 ft2232_buffer_size = 0;
658
659 #ifdef _DEBUG_USB_IO_
660                 gettimeofday(&inter2, NULL);
661 #endif
662
663                 if ((retval = ft2232_read(ft2232_buffer, ft2232_expect_read, &bytes_read)) != ERROR_OK)
664                 {
665                         LOG_ERROR("couldn't read from FT2232");
666                         return retval;
667                 }
668
669 #ifdef _DEBUG_USB_IO_
670                 gettimeofday(&end, NULL);
671
672                 timeval_subtract(&d_inter, &inter, &start);
673                 timeval_subtract(&d_inter2, &inter2, &start);
674                 timeval_subtract(&d_end, &end, &start);
675
676                 LOG_INFO("inter: %u.%06u, inter2: %u.%06u end: %u.%06u",
677                         (unsigned)d_inter.tv_sec, (unsigned)d_inter.tv_usec,
678                         (unsigned)d_inter2.tv_sec, (unsigned)d_inter2.tv_usec,
679                         (unsigned)d_end.tv_sec, (unsigned)d_end.tv_usec);
680 #endif
681
682                 ft2232_buffer_size = bytes_read;
683
684                 if (ft2232_expect_read != ft2232_buffer_size)
685                 {
686                         LOG_ERROR("ft2232_expect_read (%i) != ft2232_buffer_size (%i) (%i retries)", ft2232_expect_read,
687                                         ft2232_buffer_size,
688                                         100 - timeout);
689                         ft2232_debug_dump_buffer();
690
691                         exit(-1);
692                 }
693
694 #ifdef _DEBUG_USB_COMMS_
695                 LOG_DEBUG("read buffer (%i retries): %i bytes", 100 - timeout, ft2232_buffer_size);
696                 ft2232_debug_dump_buffer();
697 #endif
698         }
699
700         ft2232_expect_read  = 0;
701         ft2232_read_pointer = 0;
702
703         /* return ERROR_OK, unless a jtag_read_buffer returns a failed check
704          * that wasn't handled by a caller-provided error handler
705          */
706         retval = ERROR_OK;
707
708         cmd = first;
709         while (cmd != last)
710         {
711                 switch (cmd->type)
712                 {
713                 case JTAG_SCAN:
714                         type = jtag_scan_type(cmd->cmd.scan);
715                         if (type != SCAN_OUT)
716                         {
717                                 scan_size = jtag_scan_size(cmd->cmd.scan);
718                                 buffer    = calloc(CEIL(scan_size, 8), 1);
719                                 ft2232_read_scan(type, buffer, scan_size);
720                                 if (jtag_read_buffer(buffer, cmd->cmd.scan) != ERROR_OK)
721                                         retval = ERROR_JTAG_QUEUE_FAILED;
722                                 free(buffer);
723                         }
724                         break;
725
726                 default:
727                         break;
728                 }
729
730                 cmd = cmd->next;
731         }
732
733         ft2232_buffer_size = 0;
734
735         return retval;
736 }
737
738
739 /**
740  * Function ft2232_add_pathmove
741  * moves the TAP controller from the current state to a new state through the
742  * given path, where path is an array of tap_state_t's.
743  *
744  * @param path is an array of tap_stat_t which gives the states to traverse through
745  *   ending with the last state at path[num_states-1]
746  * @param num_states is the count of state steps to move through
747  */
748 static void ft2232_add_pathmove(tap_state_t* path, int num_states)
749 {
750         int                     tms_bits = 0;
751         int                     state_ndx;
752         tap_state_t     walker = tap_get_state();
753
754         assert((unsigned) num_states <= 32u);           /* tms_bits only holds 32 bits */
755
756         /* this loop verifies that the path is legal and logs each state in the path */
757         for (state_ndx = 0; state_ndx < num_states;  ++state_ndx)
758         {
759                 tap_state_t     desired_next_state = path[state_ndx];
760
761                 if (tap_state_transition(walker, false) == desired_next_state)
762                         ;       /* bit within tms_bits at index state_ndx is already zero */
763                 else if (tap_state_transition(walker, true) == desired_next_state)
764                         tms_bits |= (1 << state_ndx);
765                 else
766                 {
767                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
768                                         tap_state_name(walker), tap_state_name(desired_next_state));
769                         exit(-1);
770                 }
771
772                 walker = desired_next_state;
773         }
774
775         clock_tms(0x4b,  tms_bits, num_states, 0);
776
777         tap_set_end_state(tap_get_state());
778 }
779
780
781 static void ft2232_add_scan(bool ir_scan, enum scan_type type, uint8_t* buffer, int scan_size)
782 {
783         int num_bytes = (scan_size + 7) / 8;
784         int bits_left = scan_size;
785         int cur_byte  = 0;
786         int last_bit;
787
788         if (!ir_scan)
789         {
790                 if (tap_get_state() != TAP_DRSHIFT)
791                 {
792                         move_to_state(TAP_DRSHIFT);
793                 }
794         }
795         else
796         {
797                 if (tap_get_state() != TAP_IRSHIFT)
798                 {
799                         move_to_state(TAP_IRSHIFT);
800                 }
801         }
802
803         /* add command for complete bytes */
804         while (num_bytes > 1)
805         {
806                 int thisrun_bytes;
807                 if (type == SCAN_IO)
808                 {
809                         /* Clock Data Bytes In and Out LSB First */
810                         buffer_write(0x39);
811                         /* LOG_DEBUG("added TDI bytes (io %i)", num_bytes); */
812                 }
813                 else if (type == SCAN_OUT)
814                 {
815                         /* Clock Data Bytes Out on -ve Clock Edge LSB First (no Read) */
816                         buffer_write(0x19);
817                         /* LOG_DEBUG("added TDI bytes (o)"); */
818                 }
819                 else if (type == SCAN_IN)
820                 {
821                         /* Clock Data Bytes In on +ve Clock Edge LSB First (no Write) */
822                         buffer_write(0x28);
823                         /* LOG_DEBUG("added TDI bytes (i %i)", num_bytes); */
824                 }
825
826                 thisrun_bytes = (num_bytes > 65537) ? 65536 : (num_bytes - 1);
827                 num_bytes    -= thisrun_bytes;
828
829                 buffer_write((uint8_t) (thisrun_bytes - 1));
830                 buffer_write((uint8_t) ((thisrun_bytes - 1) >> 8));
831
832                 if (type != SCAN_IN)
833                 {
834                         /* add complete bytes */
835                         while (thisrun_bytes-- > 0)
836                         {
837                                 buffer_write(buffer[cur_byte++]);
838                                 bits_left -= 8;
839                         }
840                 }
841                 else /* (type == SCAN_IN) */
842                 {
843                         bits_left -= 8 * (thisrun_bytes);
844                 }
845         }
846
847         /* the most signifcant bit is scanned during TAP movement */
848         if (type != SCAN_IN)
849                 last_bit = (buffer[cur_byte] >> (bits_left - 1)) & 0x1;
850         else
851                 last_bit = 0;
852
853         /* process remaining bits but the last one */
854         if (bits_left > 1)
855         {
856                 if (type == SCAN_IO)
857                 {
858                         /* Clock Data Bits In and Out LSB First */
859                         buffer_write(0x3b);
860                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
861                 }
862                 else if (type == SCAN_OUT)
863                 {
864                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
865                         buffer_write(0x1b);
866                         /* LOG_DEBUG("added TDI bits (o)"); */
867                 }
868                 else if (type == SCAN_IN)
869                 {
870                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
871                         buffer_write(0x2a);
872                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
873                 }
874
875                 buffer_write(bits_left - 2);
876                 if (type != SCAN_IN)
877                         buffer_write(buffer[cur_byte]);
878         }
879
880         if ((ir_scan && (tap_get_end_state() == TAP_IRSHIFT))
881           || (!ir_scan && (tap_get_end_state() == TAP_DRSHIFT)))
882         {
883                 if (type == SCAN_IO)
884                 {
885                         /* Clock Data Bits In and Out LSB First */
886                         buffer_write(0x3b);
887                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
888                 }
889                 else if (type == SCAN_OUT)
890                 {
891                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
892                         buffer_write(0x1b);
893                         /* LOG_DEBUG("added TDI bits (o)"); */
894                 }
895                 else if (type == SCAN_IN)
896                 {
897                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
898                         buffer_write(0x2a);
899                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
900                 }
901                 buffer_write(0x0);
902                 buffer_write(last_bit);
903         }
904         else
905         {
906                 int tms_bits;
907                 int tms_count;
908                 uint8_t mpsse_cmd;
909
910                 /* move from Shift-IR/DR to end state */
911                 if (type != SCAN_OUT)
912                 {
913                         /* We always go to the PAUSE state in two step at the end of an IN or IO scan */
914                         /* This must be coordinated with the bit shifts in ft2232_read_scan    */
915                         tms_bits  = 0x01;
916                         tms_count = 2;
917                         /* Clock Data to TMS/CS Pin with Read */
918                         mpsse_cmd = 0x6b;
919                         /* LOG_DEBUG("added TMS scan (read)"); */
920                 }
921                 else
922                 {
923                         tms_bits  = tap_get_tms_path(tap_get_state(), tap_get_end_state());
924                         tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
925                         /* Clock Data to TMS/CS Pin (no Read) */
926                         mpsse_cmd = 0x4b;
927                         /* LOG_DEBUG("added TMS scan (no read)"); */
928                 }
929
930                 clock_tms(mpsse_cmd, tms_bits, tms_count, last_bit);
931         }
932
933         if (tap_get_state() != tap_get_end_state())
934         {
935                 move_to_state(tap_get_end_state());
936         }
937 }
938
939
940 static int ft2232_large_scan(scan_command_t* cmd, enum scan_type type, uint8_t* buffer, int scan_size)
941 {
942         int num_bytes = (scan_size + 7) / 8;
943         int bits_left = scan_size;
944         int cur_byte  = 0;
945         int last_bit;
946         uint8_t* receive_buffer  = malloc(CEIL(scan_size, 8));
947         uint8_t* receive_pointer = receive_buffer;
948         uint32_t bytes_written;
949         uint32_t bytes_read;
950         int retval;
951         int thisrun_read = 0;
952
953         if (cmd->ir_scan)
954         {
955                 LOG_ERROR("BUG: large IR scans are not supported");
956                 exit(-1);
957         }
958
959         if (tap_get_state() != TAP_DRSHIFT)
960         {
961                 move_to_state(TAP_DRSHIFT);
962         }
963
964         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
965         {
966                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
967                 exit(-1);
968         }
969         LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
970                   ft2232_buffer_size, (int)bytes_written);
971         ft2232_buffer_size = 0;
972
973         /* add command for complete bytes */
974         while (num_bytes > 1)
975         {
976                 int thisrun_bytes;
977
978                 if (type == SCAN_IO)
979                 {
980                         /* Clock Data Bytes In and Out LSB First */
981                         buffer_write(0x39);
982                         /* LOG_DEBUG("added TDI bytes (io %i)", num_bytes); */
983                 }
984                 else if (type == SCAN_OUT)
985                 {
986                         /* Clock Data Bytes Out on -ve Clock Edge LSB First (no Read) */
987                         buffer_write(0x19);
988                         /* LOG_DEBUG("added TDI bytes (o)"); */
989                 }
990                 else if (type == SCAN_IN)
991                 {
992                         /* Clock Data Bytes In on +ve Clock Edge LSB First (no Write) */
993                         buffer_write(0x28);
994                         /* LOG_DEBUG("added TDI bytes (i %i)", num_bytes); */
995                 }
996
997                 thisrun_bytes = (num_bytes > 65537) ? 65536 : (num_bytes - 1);
998                 thisrun_read  = thisrun_bytes;
999                 num_bytes    -= thisrun_bytes;
1000                 buffer_write((uint8_t) (thisrun_bytes - 1));
1001                 buffer_write((uint8_t) ((thisrun_bytes - 1) >> 8));
1002
1003                 if (type != SCAN_IN)
1004                 {
1005                         /* add complete bytes */
1006                         while (thisrun_bytes-- > 0)
1007                         {
1008                                 buffer_write(buffer[cur_byte]);
1009                                 cur_byte++;
1010                                 bits_left -= 8;
1011                         }
1012                 }
1013                 else /* (type == SCAN_IN) */
1014                 {
1015                         bits_left -= 8 * (thisrun_bytes);
1016                 }
1017
1018                 if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1019                 {
1020                         LOG_ERROR("couldn't write MPSSE commands to FT2232");
1021                         exit(-1);
1022                 }
1023                 LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1024                           ft2232_buffer_size,
1025                           (int)bytes_written);
1026                 ft2232_buffer_size = 0;
1027
1028                 if (type != SCAN_OUT)
1029                 {
1030                         if ((retval = ft2232_read(receive_pointer, thisrun_read, &bytes_read)) != ERROR_OK)
1031                         {
1032                                 LOG_ERROR("couldn't read from FT2232");
1033                                 exit(-1);
1034                         }
1035                         LOG_DEBUG("thisrun_read: %i, bytes_read: %i",
1036                                   thisrun_read,
1037                                   (int)bytes_read);
1038                         receive_pointer += bytes_read;
1039                 }
1040         }
1041
1042         thisrun_read = 0;
1043
1044         /* the most signifcant bit is scanned during TAP movement */
1045         if (type != SCAN_IN)
1046                 last_bit = (buffer[cur_byte] >> (bits_left - 1)) & 0x1;
1047         else
1048                 last_bit = 0;
1049
1050         /* process remaining bits but the last one */
1051         if (bits_left > 1)
1052         {
1053                 if (type == SCAN_IO)
1054                 {
1055                         /* Clock Data Bits In and Out LSB First */
1056                         buffer_write(0x3b);
1057                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
1058                 }
1059                 else if (type == SCAN_OUT)
1060                 {
1061                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
1062                         buffer_write(0x1b);
1063                         /* LOG_DEBUG("added TDI bits (o)"); */
1064                 }
1065                 else if (type == SCAN_IN)
1066                 {
1067                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
1068                         buffer_write(0x2a);
1069                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
1070                 }
1071                 buffer_write(bits_left - 2);
1072                 if (type != SCAN_IN)
1073                         buffer_write(buffer[cur_byte]);
1074
1075                 if (type != SCAN_OUT)
1076                         thisrun_read += 2;
1077         }
1078
1079         if (tap_get_end_state() == TAP_DRSHIFT)
1080         {
1081                 if (type == SCAN_IO)
1082                 {
1083                         /* Clock Data Bits In and Out LSB First */
1084                         buffer_write(0x3b);
1085                         /* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
1086                 }
1087                 else if (type == SCAN_OUT)
1088                 {
1089                         /* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
1090                         buffer_write(0x1b);
1091                         /* LOG_DEBUG("added TDI bits (o)"); */
1092                 }
1093                 else if (type == SCAN_IN)
1094                 {
1095                         /* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
1096                         buffer_write(0x2a);
1097                         /* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
1098                 }
1099                 buffer_write(0x0);
1100                 buffer_write(last_bit);
1101         }
1102         else
1103         {
1104                 int tms_bits  = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1105                 int tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1106                 uint8_t mpsse_cmd;
1107
1108                 /* move from Shift-IR/DR to end state */
1109                 if (type != SCAN_OUT)
1110                 {
1111                         /* Clock Data to TMS/CS Pin with Read */
1112                         mpsse_cmd = 0x6b;
1113                         /* LOG_DEBUG("added TMS scan (read)"); */
1114                 }
1115                 else
1116                 {
1117                         /* Clock Data to TMS/CS Pin (no Read) */
1118                         mpsse_cmd = 0x4b;
1119                         /* LOG_DEBUG("added TMS scan (no read)"); */
1120                 }
1121
1122                 clock_tms(mpsse_cmd, tms_bits, tms_count, last_bit);
1123         }
1124
1125         if (type != SCAN_OUT)
1126                 thisrun_read += 1;
1127
1128         if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
1129         {
1130                 LOG_ERROR("couldn't write MPSSE commands to FT2232");
1131                 exit(-1);
1132         }
1133         LOG_DEBUG("ft2232_buffer_size: %i, bytes_written: %i",
1134                   ft2232_buffer_size,
1135                   (int)bytes_written);
1136         ft2232_buffer_size = 0;
1137
1138         if (type != SCAN_OUT)
1139         {
1140                 if ((retval = ft2232_read(receive_pointer, thisrun_read, &bytes_read)) != ERROR_OK)
1141                 {
1142                         LOG_ERROR("couldn't read from FT2232");
1143                         exit(-1);
1144                 }
1145                 LOG_DEBUG("thisrun_read: %i, bytes_read: %i",
1146                           thisrun_read,
1147                           (int)bytes_read);
1148                 receive_pointer += bytes_read;
1149         }
1150
1151         return ERROR_OK;
1152 }
1153
1154
1155 static int ft2232_predict_scan_out(int scan_size, enum scan_type type)
1156 {
1157         int predicted_size = 3;
1158         int num_bytes = (scan_size - 1) / 8;
1159
1160         if (tap_get_state() != TAP_DRSHIFT)
1161                 predicted_size += get_tms_buffer_requirements(tap_get_tms_path_len(tap_get_state(), TAP_DRSHIFT));
1162
1163         if (type == SCAN_IN)    /* only from device to host */
1164         {
1165                 /* complete bytes */
1166                 predicted_size += CEIL(num_bytes, 65536) * 3;
1167
1168                 /* remaining bits - 1 (up to 7) */
1169                 predicted_size += ((scan_size - 1) % 8) ? 2 : 0;
1170         }
1171         else                    /* host to device, or bidirectional */
1172         {
1173                 /* complete bytes */
1174                 predicted_size += num_bytes + CEIL(num_bytes, 65536) * 3;
1175
1176                 /* remaining bits -1 (up to 7) */
1177                 predicted_size += ((scan_size - 1) % 8) ? 3 : 0;
1178         }
1179
1180         return predicted_size;
1181 }
1182
1183
1184 static int ft2232_predict_scan_in(int scan_size, enum scan_type type)
1185 {
1186         int predicted_size = 0;
1187
1188         if (type != SCAN_OUT)
1189         {
1190                 /* complete bytes */
1191                 predicted_size += (CEIL(scan_size, 8) > 1) ? (CEIL(scan_size, 8) - 1) : 0;
1192
1193                 /* remaining bits - 1 */
1194                 predicted_size += ((scan_size - 1) % 8) ? 1 : 0;
1195
1196                 /* last bit (from TMS scan) */
1197                 predicted_size += 1;
1198         }
1199
1200         /* LOG_DEBUG("scan_size: %i, predicted_size: %i", scan_size, predicted_size); */
1201
1202         return predicted_size;
1203 }
1204
1205
1206 static void usbjtag_reset(int trst, int srst)
1207 {
1208         enum reset_types jtag_reset_config = jtag_get_reset_config();
1209         if (trst == 1)
1210         {
1211                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1212                         low_direction |= nTRSTnOE;  /* switch to output pin (output is low) */
1213                 else
1214                         low_output &= ~nTRST;       /* switch output low */
1215         }
1216         else if (trst == 0)
1217         {
1218                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1219                         low_direction &= ~nTRSTnOE; /* switch to input pin (high-Z + internal and external pullup) */
1220                 else
1221                         low_output |= nTRST;        /* switch output high */
1222         }
1223
1224         if (srst == 1)
1225         {
1226                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1227                         low_output &= ~nSRST;       /* switch output low */
1228                 else
1229                         low_direction |= nSRSTnOE;  /* switch to output pin (output is low) */
1230         }
1231         else if (srst == 0)
1232         {
1233                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1234                         low_output |= nSRST;        /* switch output high */
1235                 else
1236                         low_direction &= ~nSRSTnOE; /* switch to input pin (high-Z) */
1237         }
1238
1239         /* command "set data bits low byte" */
1240         buffer_write(0x80);
1241         buffer_write(low_output);
1242         buffer_write(low_direction);
1243 }
1244
1245
1246 static void jtagkey_reset(int trst, int srst)
1247 {
1248         enum reset_types jtag_reset_config = jtag_get_reset_config();
1249         if (trst == 1)
1250         {
1251                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1252                         high_output &= ~nTRSTnOE;
1253                 else
1254                         high_output &= ~nTRST;
1255         }
1256         else if (trst == 0)
1257         {
1258                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1259                         high_output |= nTRSTnOE;
1260                 else
1261                         high_output |= nTRST;
1262         }
1263
1264         if (srst == 1)
1265         {
1266                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1267                         high_output &= ~nSRST;
1268                 else
1269                         high_output &= ~nSRSTnOE;
1270         }
1271         else if (srst == 0)
1272         {
1273                 if (jtag_reset_config & RESET_SRST_PUSH_PULL)
1274                         high_output |= nSRST;
1275                 else
1276                         high_output |= nSRSTnOE;
1277         }
1278
1279         /* command "set data bits high byte" */
1280         buffer_write(0x82);
1281         buffer_write(high_output);
1282         buffer_write(high_direction);
1283         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1284                         high_direction);
1285 }
1286
1287
1288 static void olimex_jtag_reset(int trst, int srst)
1289 {
1290         enum reset_types jtag_reset_config = jtag_get_reset_config();
1291         if (trst == 1)
1292         {
1293                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1294                         high_output &= ~nTRSTnOE;
1295                 else
1296                         high_output &= ~nTRST;
1297         }
1298         else if (trst == 0)
1299         {
1300                 if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
1301                         high_output |= nTRSTnOE;
1302                 else
1303                         high_output |= nTRST;
1304         }
1305
1306         if (srst == 1)
1307         {
1308                 high_output |= nSRST;
1309         }
1310         else if (srst == 0)
1311         {
1312                 high_output &= ~nSRST;
1313         }
1314
1315         /* command "set data bits high byte" */
1316         buffer_write(0x82);
1317         buffer_write(high_output);
1318         buffer_write(high_direction);
1319         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1320                         high_direction);
1321 }
1322
1323
1324 static void axm0432_jtag_reset(int trst, int srst)
1325 {
1326         if (trst == 1)
1327         {
1328                 tap_set_state(TAP_RESET);
1329                 high_output &= ~nTRST;
1330         }
1331         else if (trst == 0)
1332         {
1333                 high_output |= nTRST;
1334         }
1335
1336         if (srst == 1)
1337         {
1338                 high_output &= ~nSRST;
1339         }
1340         else if (srst == 0)
1341         {
1342                 high_output |= nSRST;
1343         }
1344
1345         /* command "set data bits low byte" */
1346         buffer_write(0x82);
1347         buffer_write(high_output);
1348         buffer_write(high_direction);
1349         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1350                         high_direction);
1351 }
1352
1353
1354 static void flyswatter_reset(int trst, int srst)
1355 {
1356         if (trst == 1)
1357         {
1358                 low_output &= ~nTRST;
1359         }
1360         else if (trst == 0)
1361         {
1362                 low_output |= nTRST;
1363         }
1364
1365         if (srst == 1)
1366         {
1367                 low_output |= nSRST;
1368         }
1369         else if (srst == 0)
1370         {
1371                 low_output &= ~nSRST;
1372         }
1373
1374         /* command "set data bits low byte" */
1375         buffer_write(0x80);
1376         buffer_write(low_output);
1377         buffer_write(low_direction);
1378         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
1379 }
1380
1381
1382 static void turtle_reset(int trst, int srst)
1383 {
1384         trst = trst;
1385
1386         if (srst == 1)
1387         {
1388                 low_output |= nSRST;
1389         }
1390         else if (srst == 0)
1391         {
1392                 low_output &= ~nSRST;
1393         }
1394
1395         /* command "set data bits low byte" */
1396         buffer_write(0x80);
1397         buffer_write(low_output);
1398         buffer_write(low_direction);
1399         LOG_DEBUG("srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", srst, low_output, low_direction);
1400 }
1401
1402
1403 static void comstick_reset(int trst, int srst)
1404 {
1405         if (trst == 1)
1406         {
1407                 high_output &= ~nTRST;
1408         }
1409         else if (trst == 0)
1410         {
1411                 high_output |= nTRST;
1412         }
1413
1414         if (srst == 1)
1415         {
1416                 high_output &= ~nSRST;
1417         }
1418         else if (srst == 0)
1419         {
1420                 high_output |= nSRST;
1421         }
1422
1423         /* command "set data bits high byte" */
1424         buffer_write(0x82);
1425         buffer_write(high_output);
1426         buffer_write(high_direction);
1427         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1428                         high_direction);
1429 }
1430
1431
1432 static void stm32stick_reset(int trst, int srst)
1433 {
1434         if (trst == 1)
1435         {
1436                 high_output &= ~nTRST;
1437         }
1438         else if (trst == 0)
1439         {
1440                 high_output |= nTRST;
1441         }
1442
1443         if (srst == 1)
1444         {
1445                 low_output &= ~nSRST;
1446         }
1447         else if (srst == 0)
1448         {
1449                 low_output |= nSRST;
1450         }
1451
1452         /* command "set data bits low byte" */
1453         buffer_write(0x80);
1454         buffer_write(low_output);
1455         buffer_write(low_direction);
1456
1457         /* command "set data bits high byte" */
1458         buffer_write(0x82);
1459         buffer_write(high_output);
1460         buffer_write(high_direction);
1461         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output,
1462                         high_direction);
1463 }
1464
1465
1466
1467 static void sheevaplug_reset(int trst, int srst)
1468 {
1469         if (trst == 1)
1470                 high_output &= ~nTRST;
1471         else if (trst == 0)
1472                 high_output |= nTRST;
1473
1474         if (srst == 1)
1475                 high_output &= ~nSRSTnOE;
1476         else if (srst == 0)
1477                 high_output |= nSRSTnOE;
1478
1479         /* command "set data bits high byte" */
1480         buffer_write(0x82);
1481         buffer_write(high_output);
1482         buffer_write(high_direction);
1483         LOG_DEBUG("trst: %i, srst: %i, high_output: 0x%2.2x, high_direction: 0x%2.2x", trst, srst, high_output, high_direction);
1484 }
1485
1486 static int ft2232_execute_runtest(jtag_command_t *cmd)
1487 {
1488         int  retval;
1489         int             i;
1490         int predicted_size = 0;
1491         retval = ERROR_OK;
1492
1493         DEBUG_JTAG_IO("runtest %i cycles, end in %s",
1494                         cmd->cmd.runtest->num_cycles,
1495                         tap_state_name(cmd->cmd.runtest->end_state));
1496
1497         /* only send the maximum buffer size that FT2232C can handle */
1498         predicted_size = 0;
1499         if (tap_get_state() != TAP_IDLE)
1500                 predicted_size += 3;
1501         predicted_size += 3 * CEIL(cmd->cmd.runtest->num_cycles, 7);
1502         if (cmd->cmd.runtest->end_state != TAP_IDLE)
1503                 predicted_size += 3;
1504         if (tap_get_end_state() != TAP_IDLE)
1505                 predicted_size += 3;
1506         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1507         {
1508                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1509                         retval = ERROR_JTAG_QUEUE_FAILED;
1510                 require_send = 0;
1511                 first_unsent = cmd;
1512         }
1513         if (tap_get_state() != TAP_IDLE)
1514         {
1515                 move_to_state(TAP_IDLE);
1516                 require_send = 1;
1517         }
1518         i = cmd->cmd.runtest->num_cycles;
1519         while (i > 0)
1520         {
1521                 /* there are no state transitions in this code, so omit state tracking */
1522
1523                 /* command "Clock Data to TMS/CS Pin (no Read)" */
1524                 buffer_write(0x4b);
1525
1526                 /* scan 7 bits */
1527                 buffer_write((i > 7) ? 6 : (i - 1));
1528
1529                 /* TMS data bits */
1530                 buffer_write(0x0);
1531                 tap_set_state(TAP_IDLE);
1532
1533                 i -= (i > 7) ? 7 : i;
1534                 /* LOG_DEBUG("added TMS scan (no read)"); */
1535         }
1536
1537         ft2232_end_state(cmd->cmd.runtest->end_state);
1538
1539         if (tap_get_state() != tap_get_end_state())
1540         {
1541                 move_to_state(tap_get_end_state());
1542         }
1543
1544         require_send = 1;
1545 #ifdef _DEBUG_JTAG_IO_
1546         LOG_DEBUG("runtest: %i, end in %s", cmd->cmd.runtest->num_cycles, tap_state_name(tap_get_end_state()));
1547 #endif
1548
1549         return retval;
1550 }
1551
1552
1553 static int ft2232_execute_statemove(jtag_command_t *cmd)
1554 {
1555         int     predicted_size = 0;
1556         int     retval = ERROR_OK;
1557
1558         DEBUG_JTAG_IO("statemove end in %i", cmd->cmd.statemove->end_state);
1559
1560         /* only send the maximum buffer size that FT2232C can handle */
1561         predicted_size = 3;
1562         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1563         {
1564                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1565                         retval = ERROR_JTAG_QUEUE_FAILED;
1566                 require_send = 0;
1567                 first_unsent = cmd;
1568         }
1569         ft2232_end_state(cmd->cmd.statemove->end_state);
1570
1571         /* move to end state */
1572         if (tap_get_state() != tap_get_end_state())
1573         {
1574                 move_to_state(tap_get_end_state());
1575                 require_send = 1;
1576         }
1577
1578         return retval;
1579 }
1580
1581 static int ft2232_execute_pathmove(jtag_command_t *cmd)
1582 {
1583         int     predicted_size = 0;
1584         int     retval = ERROR_OK;
1585
1586         tap_state_t*     path = cmd->cmd.pathmove->path;
1587         int     num_states    = cmd->cmd.pathmove->num_states;
1588
1589         DEBUG_JTAG_IO("pathmove: %i states, current: %s  end: %s", num_states,
1590                         tap_state_name(tap_get_state()),
1591                         tap_state_name(path[num_states-1])
1592 );
1593
1594         /* only send the maximum buffer size that FT2232C can handle */
1595         predicted_size = 3 * CEIL(num_states, 7);
1596         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1597         {
1598                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1599                         retval = ERROR_JTAG_QUEUE_FAILED;
1600
1601                 require_send = 0;
1602                 first_unsent = cmd;
1603         }
1604
1605         ft2232_add_pathmove(path, num_states);
1606         require_send = 1;
1607
1608         return retval;
1609 }
1610
1611
1612 static int ft2232_execute_scan(jtag_command_t *cmd)
1613 {
1614         uint8_t*             buffer;
1615         int             scan_size;                  /* size of IR or DR scan */
1616         int             predicted_size = 0;
1617         int                             retval = ERROR_OK;
1618
1619         enum scan_type  type = jtag_scan_type(cmd->cmd.scan);
1620
1621         DEBUG_JTAG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN", type);
1622
1623         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
1624
1625         predicted_size = ft2232_predict_scan_out(scan_size, type);
1626         if ((predicted_size + 1) > FT2232_BUFFER_SIZE)
1627         {
1628                 LOG_DEBUG("oversized ft2232 scan (predicted_size > FT2232_BUFFER_SIZE)");
1629                 /* unsent commands before this */
1630                 if (first_unsent != cmd)
1631                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1632                                 retval = ERROR_JTAG_QUEUE_FAILED;
1633
1634                 /* current command */
1635                 ft2232_end_state(cmd->cmd.scan->end_state);
1636                 ft2232_large_scan(cmd->cmd.scan, type, buffer, scan_size);
1637                 require_send = 0;
1638                 first_unsent = cmd->next;
1639                 if (buffer)
1640                         free(buffer);
1641                 return retval;
1642         }
1643         else if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1644         {
1645                 LOG_DEBUG("ft2232 buffer size reached, sending queued commands (first_unsent: %p, cmd: %p)",
1646                                 first_unsent,
1647                                 cmd);
1648                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1649                         retval = ERROR_JTAG_QUEUE_FAILED;
1650                 require_send = 0;
1651                 first_unsent = cmd;
1652         }
1653         ft2232_expect_read += ft2232_predict_scan_in(scan_size, type);
1654         /* LOG_DEBUG("new read size: %i", ft2232_expect_read); */
1655         ft2232_end_state(cmd->cmd.scan->end_state);
1656         ft2232_add_scan(cmd->cmd.scan->ir_scan, type, buffer, scan_size);
1657         require_send = 1;
1658         if (buffer)
1659                 free(buffer);
1660 #ifdef _DEBUG_JTAG_IO_
1661         LOG_DEBUG("%s scan, %i bits, end in %s", (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
1662                         tap_state_name(tap_get_end_state()));
1663 #endif
1664         return retval;
1665
1666 }
1667
1668 static int ft2232_execute_reset(jtag_command_t *cmd)
1669 {
1670         int             retval;
1671         int             predicted_size = 0;
1672         retval = ERROR_OK;
1673
1674         DEBUG_JTAG_IO("reset trst: %i srst %i",
1675                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1676
1677         /* only send the maximum buffer size that FT2232C can handle */
1678         predicted_size = 3;
1679         if (ft2232_buffer_size + predicted_size + 1 > FT2232_BUFFER_SIZE)
1680         {
1681                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1682                         retval = ERROR_JTAG_QUEUE_FAILED;
1683                 require_send = 0;
1684                 first_unsent = cmd;
1685         }
1686
1687         layout->reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1688         require_send = 1;
1689
1690 #ifdef _DEBUG_JTAG_IO_
1691         LOG_DEBUG("trst: %i, srst: %i", cmd->cmd.reset->trst, cmd->cmd.reset->srst);
1692 #endif
1693         return retval;
1694 }
1695
1696 static int ft2232_execute_sleep(jtag_command_t *cmd)
1697 {
1698         int             retval;
1699         retval = ERROR_OK;
1700
1701         DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
1702
1703         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1704                                 retval = ERROR_JTAG_QUEUE_FAILED;
1705         first_unsent = cmd->next;
1706         jtag_sleep(cmd->cmd.sleep->us);
1707 #ifdef _DEBUG_JTAG_IO_
1708                         LOG_DEBUG("sleep %i usec while in %s", cmd->cmd.sleep->us, tap_state_name(tap_get_state()));
1709 #endif
1710
1711         return retval;
1712 }
1713
1714 static int ft2232_execute_stableclocks(jtag_command_t *cmd)
1715 {
1716         int             retval;
1717         retval = ERROR_OK;
1718
1719         /* this is only allowed while in a stable state.  A check for a stable
1720          * state was done in jtag_add_clocks()
1721          */
1722         if (ft2232_stableclocks(cmd->cmd.stableclocks->num_cycles, cmd) != ERROR_OK)
1723                 retval = ERROR_JTAG_QUEUE_FAILED;
1724 #ifdef _DEBUG_JTAG_IO_
1725         LOG_DEBUG("clocks %i while in %s", cmd->cmd.stableclocks->num_cycles, tap_state_name(tap_get_state()));
1726 #endif
1727
1728         return retval;
1729 }
1730
1731 static int ft2232_execute_command(jtag_command_t *cmd)
1732 {
1733         int             retval;
1734         retval = ERROR_OK;
1735
1736         switch (cmd->type)
1737         {
1738         case JTAG_RESET:        retval = ft2232_execute_reset(cmd); break;
1739         case JTAG_RUNTEST:      retval = ft2232_execute_runtest(cmd); break;
1740         case JTAG_STATEMOVE: retval = ft2232_execute_statemove(cmd); break;
1741         case JTAG_PATHMOVE:     retval = ft2232_execute_pathmove(cmd); break;
1742         case JTAG_SCAN:         retval = ft2232_execute_scan(cmd); break;
1743         case JTAG_SLEEP:        retval = ft2232_execute_sleep(cmd); break;
1744         case JTAG_STABLECLOCKS: retval = ft2232_execute_stableclocks(cmd); break;
1745         default:
1746                 LOG_ERROR("BUG: unknown JTAG command type encountered");
1747                 exit(-1);
1748         }
1749         return retval;
1750 }
1751
1752 static int ft2232_execute_queue()
1753 {
1754         jtag_command_t* cmd = jtag_command_queue;   /* currently processed command */
1755         int             retval;
1756
1757         first_unsent = cmd;         /* next command that has to be sent */
1758         require_send = 0;
1759
1760         /* return ERROR_OK, unless ft2232_send_and_recv reports a failed check
1761          * that wasn't handled by a caller-provided error handler
1762          */
1763         retval = ERROR_OK;
1764
1765         ft2232_buffer_size = 0;
1766         ft2232_expect_read = 0;
1767
1768         /* blink, if the current layout has that feature */
1769         if (layout->blink)
1770                 layout->blink();
1771
1772         while (cmd)
1773         {
1774                 if (ft2232_execute_command(cmd) != ERROR_OK)
1775                         retval = ERROR_JTAG_QUEUE_FAILED;
1776                 /* Start reading input before FT2232 TX buffer fills up */
1777                 cmd = cmd->next;
1778                 if (ft2232_expect_read > 256)
1779                 {
1780                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1781                                 retval = ERROR_JTAG_QUEUE_FAILED;
1782                         first_unsent = cmd;
1783                 }
1784         }
1785
1786         if (require_send > 0)
1787                 if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
1788                         retval = ERROR_JTAG_QUEUE_FAILED;
1789
1790         return retval;
1791 }
1792
1793
1794 #if BUILD_FT2232_FTD2XX == 1
1795 static int ft2232_init_ftd2xx(uint16_t vid, uint16_t pid, int more, int* try_more)
1796 {
1797         FT_STATUS       status;
1798         DWORD           deviceID;
1799         char            SerialNumber[16];
1800         char            Description[64];
1801         DWORD   openex_flags  = 0;
1802         char*   openex_string = NULL;
1803         uint8_t latency_timer;
1804
1805         LOG_DEBUG("'ft2232' interface using FTD2XX with '%s' layout (%4.4x:%4.4x)", ft2232_layout, vid, pid);
1806
1807 #if IS_WIN32 == 0
1808         /* Add non-standard Vid/Pid to the linux driver */
1809         if ((status = FT_SetVIDPID(vid, pid)) != FT_OK)
1810         {
1811                 LOG_WARNING("couldn't add %4.4x:%4.4x", vid, pid);
1812         }
1813 #endif
1814
1815         if (ft2232_device_desc && ft2232_serial)
1816         {
1817                 LOG_WARNING("can't open by device description and serial number, giving precedence to serial");
1818                 ft2232_device_desc = NULL;
1819         }
1820
1821         if (ft2232_device_desc)
1822         {
1823                 openex_string = ft2232_device_desc;
1824                 openex_flags  = FT_OPEN_BY_DESCRIPTION;
1825         }
1826         else if (ft2232_serial)
1827         {
1828                 openex_string = ft2232_serial;
1829                 openex_flags  = FT_OPEN_BY_SERIAL_NUMBER;
1830         }
1831         else
1832         {
1833                 LOG_ERROR("neither device description nor serial number specified");
1834                 LOG_ERROR("please add \"ft2232_device_desc <string>\" or \"ft2232_serial <string>\" to your .cfg file");
1835
1836                 return ERROR_JTAG_INIT_FAILED;
1837         }
1838
1839         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
1840         if (status != FT_OK) {
1841                 // under Win32, the FTD2XX driver appends an "A" to the end
1842                 // of the description, if we tried by the desc, then
1843                 // try by the alternate "A" description.
1844                 if (openex_string == ft2232_device_desc) {
1845                         // Try the alternate method.
1846                         openex_string = ft2232_device_desc_A;
1847                         status = FT_OpenEx(openex_string, openex_flags, &ftdih);
1848                         if (status == FT_OK) {
1849                                 // yea, the "alternate" method worked!
1850                         } else {
1851                                 // drat, give the user a meaningfull message.
1852                                 // telling the use we tried *BOTH* methods.
1853                                 LOG_WARNING("Unable to open FTDI Device tried: '%s' and '%s'\n",
1854                                                         ft2232_device_desc,
1855                                                         ft2232_device_desc_A);
1856                         }
1857                 }
1858         }
1859
1860         if (status != FT_OK)
1861         {
1862                 DWORD num_devices;
1863
1864                 if (more)
1865                 {
1866                         LOG_WARNING("unable to open ftdi device (trying more): %lu", status);
1867                         *try_more = 1;
1868                         return ERROR_JTAG_INIT_FAILED;
1869                 }
1870                 LOG_ERROR("unable to open ftdi device: %lu", status);
1871                 status = FT_ListDevices(&num_devices, NULL, FT_LIST_NUMBER_ONLY);
1872                 if (status == FT_OK)
1873                 {
1874                         char** desc_array = malloc(sizeof(char*) * (num_devices + 1));
1875                         uint32_t i;
1876
1877                         for (i = 0; i < num_devices; i++)
1878                                 desc_array[i] = malloc(64);
1879
1880                         desc_array[num_devices] = NULL;
1881
1882                         status = FT_ListDevices(desc_array, &num_devices, FT_LIST_ALL | openex_flags);
1883
1884                         if (status == FT_OK)
1885                         {
1886                                 LOG_ERROR("ListDevices: %lu\n", num_devices);
1887                                 for (i = 0; i < num_devices; i++)
1888                                         LOG_ERROR("%" PRIu32 ": \"%s\"", i, desc_array[i]);
1889                         }
1890
1891                         for (i = 0; i < num_devices; i++)
1892                                 free(desc_array[i]);
1893
1894                         free(desc_array);
1895                 }
1896                 else
1897                 {
1898                         LOG_ERROR("ListDevices: NONE\n");
1899                 }
1900                 return ERROR_JTAG_INIT_FAILED;
1901         }
1902
1903         if ((status = FT_SetLatencyTimer(ftdih, ft2232_latency)) != FT_OK)
1904         {
1905                 LOG_ERROR("unable to set latency timer: %lu", status);
1906                 return ERROR_JTAG_INIT_FAILED;
1907         }
1908
1909         if ((status = FT_GetLatencyTimer(ftdih, &latency_timer)) != FT_OK)
1910         {
1911                 LOG_ERROR("unable to get latency timer: %lu", status);
1912                 return ERROR_JTAG_INIT_FAILED;
1913         }
1914         else
1915         {
1916                 LOG_DEBUG("current latency timer: %i", latency_timer);
1917         }
1918
1919         if ((status = FT_SetTimeouts(ftdih, 5000, 5000)) != FT_OK)
1920         {
1921                 LOG_ERROR("unable to set timeouts: %lu", status);
1922                 return ERROR_JTAG_INIT_FAILED;
1923         }
1924
1925         if ((status = FT_SetBitMode(ftdih, 0x0b, 2)) != FT_OK)
1926         {
1927                 LOG_ERROR("unable to enable bit i/o mode: %lu", status);
1928                 return ERROR_JTAG_INIT_FAILED;
1929         }
1930
1931         if ((status = FT_GetDeviceInfo(ftdih, &ftdi_device, &deviceID, SerialNumber, Description, NULL)) != FT_OK)
1932         {
1933                 LOG_ERROR("unable to get FT_GetDeviceInfo: %lu", status);
1934                 return ERROR_JTAG_INIT_FAILED;
1935         }
1936         else
1937         {
1938                 LOG_INFO("device: %lu", ftdi_device);
1939                 LOG_INFO("deviceID: %lu", deviceID);
1940                 LOG_INFO("SerialNumber: %s", SerialNumber);
1941                 LOG_INFO("Description: %s", Description);
1942
1943 #ifdef BUILD_FTD2XX_HIGHSPEED
1944                 if (ft2232_device_is_highspeed())
1945                 {
1946                         ft2232_max_tck = FTDI_2232H_4232H_MAX_TCK;
1947                         LOG_INFO("max TCK change to: %u kHz", ft2232_max_tck);
1948                 }
1949 #endif
1950         }
1951
1952         return ERROR_OK;
1953 }
1954
1955
1956 static int ft2232_purge_ftd2xx(void)
1957 {
1958         FT_STATUS status;
1959
1960         if ((status = FT_Purge(ftdih, FT_PURGE_RX | FT_PURGE_TX)) != FT_OK)
1961         {
1962                 LOG_ERROR("error purging ftd2xx device: %lu", status);
1963                 return ERROR_JTAG_INIT_FAILED;
1964         }
1965
1966         return ERROR_OK;
1967 }
1968
1969
1970 #endif /* BUILD_FT2232_FTD2XX == 1 */
1971
1972 #if BUILD_FT2232_LIBFTDI == 1
1973 static int ft2232_init_libftdi(uint16_t vid, uint16_t pid, int more, int* try_more)
1974 {
1975         uint8_t latency_timer;
1976
1977         LOG_DEBUG("'ft2232' interface using libftdi with '%s' layout (%4.4x:%4.4x)",
1978                         ft2232_layout, vid, pid);
1979
1980         if (ftdi_init(&ftdic) < 0)
1981                 return ERROR_JTAG_INIT_FAILED;
1982
1983         if (ftdi_set_interface(&ftdic, INTERFACE_A) < 0)
1984         {
1985                 LOG_ERROR("unable to select FT2232 channel A: %s", ftdic.error_str);
1986                 return ERROR_JTAG_INIT_FAILED;
1987         }
1988
1989         /* context, vendor id, product id */
1990         if (ftdi_usb_open_desc(&ftdic, vid, pid, ft2232_device_desc,
1991                                 ft2232_serial) < 0)
1992         {
1993                 if (more)
1994                         LOG_WARNING("unable to open ftdi device (trying more): %s",
1995                                         ftdic.error_str);
1996                 else
1997                         LOG_ERROR("unable to open ftdi device: %s", ftdic.error_str);
1998                 *try_more = 1;
1999                 return ERROR_JTAG_INIT_FAILED;
2000         }
2001
2002         /* There is already a reset in ftdi_usb_open_desc, this should be redundant */
2003         if (ftdi_usb_reset(&ftdic) < 0)
2004         {
2005                 LOG_ERROR("unable to reset ftdi device");
2006                 return ERROR_JTAG_INIT_FAILED;
2007         }
2008
2009         if (ftdi_set_latency_timer(&ftdic, ft2232_latency) < 0)
2010         {
2011                 LOG_ERROR("unable to set latency timer");
2012                 return ERROR_JTAG_INIT_FAILED;
2013         }
2014
2015         if (ftdi_get_latency_timer(&ftdic, &latency_timer) < 0)
2016         {
2017                 LOG_ERROR("unable to get latency timer");
2018                 return ERROR_JTAG_INIT_FAILED;
2019         }
2020         else
2021         {
2022                 LOG_DEBUG("current latency timer: %i", latency_timer);
2023         }
2024
2025         ftdi_set_bitmode(&ftdic, 0x0b, 2); /* ctx, JTAG I/O mask */
2026
2027         return ERROR_OK;
2028 }
2029
2030
2031 static int ft2232_purge_libftdi(void)
2032 {
2033         if (ftdi_usb_purge_buffers(&ftdic) < 0)
2034         {
2035                 LOG_ERROR("ftdi_purge_buffers: %s", ftdic.error_str);
2036                 return ERROR_JTAG_INIT_FAILED;
2037         }
2038
2039         return ERROR_OK;
2040 }
2041
2042
2043 #endif /* BUILD_FT2232_LIBFTDI == 1 */
2044
2045 static int ft2232_init(void)
2046 {
2047         uint8_t  buf[1];
2048         int retval;
2049         uint32_t bytes_written;
2050         const ft2232_layout_t* cur_layout = ft2232_layouts;
2051         int i;
2052
2053         if (tap_get_tms_path_len(TAP_IRPAUSE,TAP_IRPAUSE) == 7)
2054         {
2055                 LOG_DEBUG("ft2232 interface using 7 step jtag state transitions");
2056         }
2057         else
2058         {
2059                 LOG_DEBUG("ft2232 interface using shortest path jtag state transitions");
2060
2061         }
2062         if ((ft2232_layout == NULL) || (ft2232_layout[0] == 0))
2063         {
2064                 ft2232_layout = "usbjtag";
2065                 LOG_WARNING("No ft2232 layout specified, using default 'usbjtag'");
2066         }
2067
2068         while (cur_layout->name)
2069         {
2070                 if (strcmp(cur_layout->name, ft2232_layout) == 0)
2071                 {
2072                         layout = cur_layout;
2073                         break;
2074                 }
2075                 cur_layout++;
2076         }
2077
2078         if (!layout)
2079         {
2080                 LOG_ERROR("No matching layout found for %s", ft2232_layout);
2081                 return ERROR_JTAG_INIT_FAILED;
2082         }
2083
2084         for (i = 0; 1; i++)
2085         {
2086                 /*
2087                  * "more indicates that there are more IDs to try, so we should
2088                  * not print an error for an ID mismatch (but for anything
2089                  * else, we should).
2090                  *
2091                  * try_more indicates that the error code returned indicates an
2092                  * ID mismatch (and nothing else) and that we should proceeed
2093                  * with the next ID pair.
2094                  */
2095                 int more     = ft2232_vid[i + 1] || ft2232_pid[i + 1];
2096                 int try_more = 0;
2097
2098 #if BUILD_FT2232_FTD2XX == 1
2099                 retval = ft2232_init_ftd2xx(ft2232_vid[i], ft2232_pid[i],
2100                                 more, &try_more);
2101 #elif BUILD_FT2232_LIBFTDI == 1
2102                 retval = ft2232_init_libftdi(ft2232_vid[i], ft2232_pid[i],
2103                                 more, &try_more);
2104 #endif
2105                 if (retval >= 0)
2106                         break;
2107                 if (!more || !try_more)
2108                         return retval;
2109         }
2110
2111         ft2232_buffer_size = 0;
2112         ft2232_buffer = malloc(FT2232_BUFFER_SIZE);
2113
2114         if (layout->init() != ERROR_OK)
2115                 return ERROR_JTAG_INIT_FAILED;
2116
2117         ft2232_speed(jtag_get_speed());
2118
2119         buf[0] = 0x85; /* Disconnect TDI/DO to TDO/DI for Loopback */
2120         if (((retval = ft2232_write(buf, 1, &bytes_written)) != ERROR_OK) || (bytes_written != 1))
2121         {
2122                 LOG_ERROR("couldn't write to FT2232 to disable loopback");
2123                 return ERROR_JTAG_INIT_FAILED;
2124         }
2125
2126 #if BUILD_FT2232_FTD2XX == 1
2127         return ft2232_purge_ftd2xx();
2128 #elif BUILD_FT2232_LIBFTDI == 1
2129         return ft2232_purge_libftdi();
2130 #endif
2131
2132         return ERROR_OK;
2133 }
2134
2135
2136 static int usbjtag_init(void)
2137 {
2138         uint8_t  buf[3];
2139         uint32_t bytes_written;
2140
2141         low_output    = 0x08;
2142         low_direction = 0x0b;
2143
2144         if (strcmp(ft2232_layout, "usbjtag") == 0)
2145         {
2146                 nTRST    = 0x10;
2147                 nTRSTnOE = 0x10;
2148                 nSRST    = 0x40;
2149                 nSRSTnOE = 0x40;
2150         }
2151         else if (strcmp(ft2232_layout, "signalyzer") == 0)
2152         {
2153                 nTRST    = 0x10;
2154                 nTRSTnOE = 0x10;
2155                 nSRST    = 0x20;
2156                 nSRSTnOE = 0x20;
2157         }
2158         else if (strcmp(ft2232_layout, "evb_lm3s811") == 0)
2159         {
2160                 nTRST = 0x0;
2161                 nTRSTnOE = 0x00;
2162                 nSRST = 0x20;
2163                 nSRSTnOE = 0x20;
2164                 low_output    = 0x88;
2165                 low_direction = 0x8b;
2166         }
2167         else if (strcmp(ft2232_layout, "luminary_icdi") == 0)
2168         {
2169                 nTRST = 0x0;
2170                 nTRSTnOE = 0x00;
2171                 nSRST = 0x20;
2172                 nSRSTnOE = 0x20;
2173                 low_output    = 0x88;
2174                 low_direction = 0xcb;
2175         }
2176         else
2177         {
2178                 LOG_ERROR("BUG: usbjtag_init called for unknown layout '%s'", ft2232_layout);
2179                 return ERROR_JTAG_INIT_FAILED;
2180         }
2181
2182         enum reset_types jtag_reset_config = jtag_get_reset_config();
2183         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2184         {
2185                 low_direction &= ~nTRSTnOE; /* nTRST input */
2186                 low_output    &= ~nTRST;    /* nTRST = 0 */
2187         }
2188         else
2189         {
2190                 low_direction |= nTRSTnOE;  /* nTRST output */
2191                 low_output    |= nTRST;     /* nTRST = 1 */
2192         }
2193
2194         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2195         {
2196                 low_direction |= nSRSTnOE;  /* nSRST output */
2197                 low_output    |= nSRST;     /* nSRST = 1 */
2198         }
2199         else
2200         {
2201                 low_direction &= ~nSRSTnOE; /* nSRST input */
2202                 low_output    &= ~nSRST;    /* nSRST = 0 */
2203         }
2204
2205         /* initialize low byte for jtag */
2206         buf[0] = 0x80;          /* command "set data bits low byte" */
2207         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, xRST high) */
2208         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in */
2209         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2210
2211         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2212         {
2213                 LOG_ERROR("couldn't initialize FT2232 with 'USBJTAG' layout");
2214                 return ERROR_JTAG_INIT_FAILED;
2215         }
2216
2217         return ERROR_OK;
2218 }
2219
2220
2221 static int axm0432_jtag_init(void)
2222 {
2223         uint8_t  buf[3];
2224         uint32_t bytes_written;
2225
2226         low_output    = 0x08;
2227         low_direction = 0x2b;
2228
2229         /* initialize low byte for jtag */
2230         buf[0] = 0x80;          /* command "set data bits low byte" */
2231         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2232         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2233         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2234
2235         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2236         {
2237                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2238                 return ERROR_JTAG_INIT_FAILED;
2239         }
2240
2241         if (strcmp(layout->name, "axm0432_jtag") == 0)
2242         {
2243                 nTRST    = 0x08;
2244                 nTRSTnOE = 0x0;     /* No output enable for TRST*/
2245                 nSRST    = 0x04;
2246                 nSRSTnOE = 0x0;     /* No output enable for SRST*/
2247         }
2248         else
2249         {
2250                 LOG_ERROR("BUG: axm0432_jtag_init called for non axm0432 layout");
2251                 exit(-1);
2252         }
2253
2254         high_output    = 0x0;
2255         high_direction = 0x0c;
2256
2257         enum reset_types jtag_reset_config = jtag_get_reset_config();
2258         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2259         {
2260                 LOG_ERROR("can't set nTRSTOE to push-pull on the Dicarlo jtag");
2261         }
2262         else
2263         {
2264                 high_output |= nTRST;
2265         }
2266
2267         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2268         {
2269                 LOG_ERROR("can't set nSRST to push-pull on the Dicarlo jtag");
2270         }
2271         else
2272         {
2273                 high_output |= nSRST;
2274         }
2275
2276         /* initialize high port */
2277         buf[0] = 0x82;              /* command "set data bits high byte" */
2278         buf[1] = high_output;       /* value */
2279         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2280         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2281
2282         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2283         {
2284                 LOG_ERROR("couldn't initialize FT2232 with 'Dicarlo' layout");
2285                 return ERROR_JTAG_INIT_FAILED;
2286         }
2287
2288         return ERROR_OK;
2289 }
2290
2291
2292 static int jtagkey_init(void)
2293 {
2294         uint8_t  buf[3];
2295         uint32_t bytes_written;
2296
2297         low_output    = 0x08;
2298         low_direction = 0x1b;
2299
2300         /* initialize low byte for jtag */
2301         buf[0] = 0x80;          /* command "set data bits low byte" */
2302         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2303         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2304         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2305
2306         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2307         {
2308                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2309                 return ERROR_JTAG_INIT_FAILED;
2310         }
2311
2312         if (strcmp(layout->name, "jtagkey") == 0)
2313         {
2314                 nTRST    = 0x01;
2315                 nTRSTnOE = 0x4;
2316                 nSRST    = 0x02;
2317                 nSRSTnOE = 0x08;
2318         }
2319         else if ((strcmp(layout->name, "jtagkey_prototype_v1") == 0)
2320                          || (strcmp(layout->name, "oocdlink") == 0))
2321         {
2322                 nTRST    = 0x02;
2323                 nTRSTnOE = 0x1;
2324                 nSRST    = 0x08;
2325                 nSRSTnOE = 0x04;
2326         }
2327         else
2328         {
2329                 LOG_ERROR("BUG: jtagkey_init called for non jtagkey layout");
2330                 exit(-1);
2331         }
2332
2333         high_output    = 0x0;
2334         high_direction = 0x0f;
2335
2336         enum reset_types jtag_reset_config = jtag_get_reset_config();
2337         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2338         {
2339                 high_output |= nTRSTnOE;
2340                 high_output &= ~nTRST;
2341         }
2342         else
2343         {
2344                 high_output &= ~nTRSTnOE;
2345                 high_output |= nTRST;
2346         }
2347
2348         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2349         {
2350                 high_output &= ~nSRSTnOE;
2351                 high_output |= nSRST;
2352         }
2353         else
2354         {
2355                 high_output |= nSRSTnOE;
2356                 high_output &= ~nSRST;
2357         }
2358
2359         /* initialize high port */
2360         buf[0] = 0x82;              /* command "set data bits high byte" */
2361         buf[1] = high_output;       /* value */
2362         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2363         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2364
2365         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2366         {
2367                 LOG_ERROR("couldn't initialize FT2232 with 'JTAGkey' layout");
2368                 return ERROR_JTAG_INIT_FAILED;
2369         }
2370
2371         return ERROR_OK;
2372 }
2373
2374
2375 static int olimex_jtag_init(void)
2376 {
2377         uint8_t  buf[3];
2378         uint32_t bytes_written;
2379
2380         low_output    = 0x08;
2381         low_direction = 0x1b;
2382
2383         /* initialize low byte for jtag */
2384         buf[0] = 0x80;          /* command "set data bits low byte" */
2385         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2386         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2387         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2388
2389         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2390         {
2391                 LOG_ERROR("couldn't initialize FT2232 with 'Olimex' layout");
2392                 return ERROR_JTAG_INIT_FAILED;
2393         }
2394
2395         nTRST    = 0x01;
2396         nTRSTnOE = 0x4;
2397         nSRST    = 0x02;
2398         nSRSTnOE = 0x00; /* no output enable for nSRST */
2399
2400         high_output    = 0x0;
2401         high_direction = 0x0f;
2402
2403         enum reset_types jtag_reset_config = jtag_get_reset_config();
2404         if (jtag_reset_config & RESET_TRST_OPEN_DRAIN)
2405         {
2406                 high_output |= nTRSTnOE;
2407                 high_output &= ~nTRST;
2408         }
2409         else
2410         {
2411                 high_output &= ~nTRSTnOE;
2412                 high_output |= nTRST;
2413         }
2414
2415         if (jtag_reset_config & RESET_SRST_PUSH_PULL)
2416         {
2417                 LOG_ERROR("can't set nSRST to push-pull on the Olimex ARM-USB-OCD");
2418         }
2419         else
2420         {
2421                 high_output &= ~nSRST;
2422         }
2423
2424         /* turn red LED on */
2425         high_output |= 0x08;
2426
2427         /* initialize high port */
2428         buf[0] = 0x82;              /* command "set data bits high byte" */
2429         buf[1] = high_output;       /* value */
2430         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2431         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2432
2433         if ((ft2232_write(buf, 3, &bytes_written) != ERROR_OK) || (bytes_written != 3))
2434         {
2435                 LOG_ERROR("couldn't initialize FT2232 with 'Olimex' layout");
2436                 return ERROR_JTAG_INIT_FAILED;
2437         }
2438
2439         return ERROR_OK;
2440 }
2441
2442
2443 static int flyswatter_init(void)
2444 {
2445         uint8_t  buf[3];
2446         uint32_t bytes_written;
2447
2448         low_output    = 0x18;
2449         low_direction = 0xfb;
2450
2451         /* initialize low byte for jtag */
2452         buf[0] = 0x80;          /* command "set data bits low byte" */
2453         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2454         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE[12]=out, n[ST]srst = out */
2455         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2456
2457         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2458         {
2459                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2460                 return ERROR_JTAG_INIT_FAILED;
2461         }
2462
2463         nTRST    = 0x10;
2464         nTRSTnOE = 0x0;     /* not output enable for nTRST */
2465         nSRST    = 0x20;
2466         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2467
2468         high_output    = 0x00;
2469         high_direction = 0x0c;
2470
2471         /* turn red LED3 on, LED2 off */
2472         high_output |= 0x08;
2473
2474         /* initialize high port */
2475         buf[0] = 0x82;              /* command "set data bits high byte" */
2476         buf[1] = high_output;       /* value */
2477         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
2478         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2479
2480         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2481         {
2482                 LOG_ERROR("couldn't initialize FT2232 with 'flyswatter' layout");
2483                 return ERROR_JTAG_INIT_FAILED;
2484         }
2485
2486         return ERROR_OK;
2487 }
2488
2489
2490 static int turtle_init(void)
2491 {
2492         uint8_t  buf[3];
2493         uint32_t bytes_written;
2494
2495         low_output    = 0x08;
2496         low_direction = 0x5b;
2497
2498         /* initialize low byte for jtag */
2499         buf[0] = 0x80;          /* command "set data bits low byte" */
2500         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2501         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2502         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2503
2504         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2505         {
2506                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2507                 return ERROR_JTAG_INIT_FAILED;
2508         }
2509
2510         nSRST = 0x40;
2511
2512         high_output    = 0x00;
2513         high_direction = 0x0C;
2514
2515         /* initialize high port */
2516         buf[0] = 0x82; /* command "set data bits high byte" */
2517         buf[1] = high_output;
2518         buf[2] = high_direction;
2519         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2520
2521         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2522         {
2523                 LOG_ERROR("couldn't initialize FT2232 with 'turtelizer2' layout");
2524                 return ERROR_JTAG_INIT_FAILED;
2525         }
2526
2527         return ERROR_OK;
2528 }
2529
2530
2531 static int comstick_init(void)
2532 {
2533         uint8_t  buf[3];
2534         uint32_t bytes_written;
2535
2536         low_output    = 0x08;
2537         low_direction = 0x0b;
2538
2539         /* initialize low byte for jtag */
2540         buf[0] = 0x80;          /* command "set data bits low byte" */
2541         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2542         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2543         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2544
2545         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2546         {
2547                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2548                 return ERROR_JTAG_INIT_FAILED;
2549         }
2550
2551         nTRST    = 0x01;
2552         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2553         nSRST    = 0x02;
2554         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2555
2556         high_output    = 0x03;
2557         high_direction = 0x03;
2558
2559         /* initialize high port */
2560         buf[0] = 0x82; /* command "set data bits high byte" */
2561         buf[1] = high_output;
2562         buf[2] = high_direction;
2563         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2564
2565         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2566         {
2567                 LOG_ERROR("couldn't initialize FT2232 with 'comstick' layout");
2568                 return ERROR_JTAG_INIT_FAILED;
2569         }
2570
2571         return ERROR_OK;
2572 }
2573
2574
2575 static int stm32stick_init(void)
2576 {
2577         uint8_t  buf[3];
2578         uint32_t bytes_written;
2579
2580         low_output    = 0x88;
2581         low_direction = 0x8b;
2582
2583         /* initialize low byte for jtag */
2584         buf[0] = 0x80;          /* command "set data bits low byte" */
2585         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2586         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2587         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2588
2589         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2590         {
2591                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2592                 return ERROR_JTAG_INIT_FAILED;
2593         }
2594
2595         nTRST    = 0x01;
2596         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2597         nSRST    = 0x80;
2598         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2599
2600         high_output    = 0x01;
2601         high_direction = 0x03;
2602
2603         /* initialize high port */
2604         buf[0] = 0x82; /* command "set data bits high byte" */
2605         buf[1] = high_output;
2606         buf[2] = high_direction;
2607         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2608
2609         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2610         {
2611                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2612                 return ERROR_JTAG_INIT_FAILED;
2613         }
2614
2615         return ERROR_OK;
2616 }
2617
2618
2619 static int sheevaplug_init(void)
2620 {
2621         uint8_t buf[3];
2622         uint32_t bytes_written;
2623
2624         low_output = 0x08;
2625         low_direction = 0x1b;
2626
2627         /* initialize low byte for jtag */
2628         buf[0] = 0x80; /* command "set data bits low byte" */
2629         buf[1] = low_output; /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2630         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in */
2631         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2632
2633         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2634         {
2635                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2636                 return ERROR_JTAG_INIT_FAILED;
2637         }
2638
2639         nTRSTnOE = 0x1;
2640         nTRST = 0x02;
2641         nSRSTnOE = 0x4;
2642         nSRST = 0x08;
2643
2644         high_output = 0x0;
2645         high_direction = 0x0f;
2646
2647         /* nTRST is always push-pull */
2648         high_output &= ~nTRSTnOE;
2649         high_output |= nTRST;
2650
2651         /* nSRST is always open-drain */
2652         high_output |= nSRSTnOE;
2653         high_output &= ~nSRST;
2654
2655         /* initialize high port */
2656         buf[0] = 0x82; /* command "set data bits high byte" */
2657         buf[1] = high_output; /* value */
2658         buf[2] = high_direction;   /* all outputs - xRST */
2659         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2660
2661         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2662         {
2663                 LOG_ERROR("couldn't initialize FT2232 with 'sheevaplug' layout");
2664                 return ERROR_JTAG_INIT_FAILED;
2665         }
2666
2667         return ERROR_OK;
2668 }
2669
2670 static int cortino_jtag_init(void)
2671 {
2672         uint8_t  buf[3];
2673         uint32_t bytes_written;
2674
2675         low_output    = 0x08;
2676         low_direction = 0x1b;
2677
2678         /* initialize low byte for jtag */
2679         buf[0] = 0x80;          /* command "set data bits low byte" */
2680         buf[1] = low_output;    /* value (TMS = 1,TCK = 0, TDI = 0, nOE = 0) */
2681         buf[2] = low_direction; /* dir (output = 1), TCK/TDI/TMS = out, TDO = in, nOE = out */
2682         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2683
2684         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2685         {
2686                 LOG_ERROR("couldn't initialize FT2232 with 'cortino' layout");
2687                 return ERROR_JTAG_INIT_FAILED;
2688         }
2689
2690         nTRST    = 0x01;
2691         nTRSTnOE = 0x00;    /* no output enable for nTRST */
2692         nSRST    = 0x02;
2693         nSRSTnOE = 0x00;    /* no output enable for nSRST */
2694
2695         high_output    = 0x03;
2696         high_direction = 0x03;
2697
2698         /* initialize high port */
2699         buf[0] = 0x82; /* command "set data bits high byte" */
2700         buf[1] = high_output;
2701         buf[2] = high_direction;
2702         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2703
2704         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
2705         {
2706                 LOG_ERROR("couldn't initialize FT2232 with 'stm32stick' layout");
2707                 return ERROR_JTAG_INIT_FAILED;
2708         }
2709
2710         return ERROR_OK;
2711 }
2712
2713 static void olimex_jtag_blink(void)
2714 {
2715         /* Olimex ARM-USB-OCD has a LED connected to ACBUS3
2716          * ACBUS3 is bit 3 of the GPIOH port
2717          */
2718         if (high_output & 0x08)
2719         {
2720                 /* set port pin high */
2721                 high_output &= 0x07;
2722         }
2723         else
2724         {
2725                 /* set port pin low */
2726                 high_output |= 0x08;
2727         }
2728
2729         buffer_write(0x82);
2730         buffer_write(high_output);
2731         buffer_write(high_direction);
2732 }
2733
2734
2735 static void flyswatter_jtag_blink(void)
2736 {
2737         /*
2738          * Flyswatter has two LEDs connected to ACBUS2 and ACBUS3
2739          */
2740         high_output ^= 0x0c;
2741
2742         buffer_write(0x82);
2743         buffer_write(high_output);
2744         buffer_write(high_direction);
2745 }
2746
2747
2748 static void turtle_jtag_blink(void)
2749 {
2750         /*
2751          * Turtelizer2 has two LEDs connected to ACBUS2 and ACBUS3
2752          */
2753         if (high_output & 0x08)
2754         {
2755                 high_output = 0x04;
2756         }
2757         else
2758         {
2759                 high_output = 0x08;
2760         }
2761
2762         buffer_write(0x82);
2763         buffer_write(high_output);
2764         buffer_write(high_direction);
2765 }
2766
2767
2768 static int ft2232_quit(void)
2769 {
2770 #if BUILD_FT2232_FTD2XX == 1
2771         FT_STATUS status;
2772
2773         status = FT_Close(ftdih);
2774 #elif BUILD_FT2232_LIBFTDI == 1
2775         ftdi_usb_close(&ftdic);
2776
2777         ftdi_deinit(&ftdic);
2778 #endif
2779
2780         free(ft2232_buffer);
2781         ft2232_buffer = NULL;
2782
2783         return ERROR_OK;
2784 }
2785
2786
2787 static int ft2232_handle_device_desc_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2788 {
2789         char *cp;
2790         char buf[200];
2791         if (argc == 1)
2792         {
2793                 ft2232_device_desc = strdup(args[0]);
2794                 cp = strchr(ft2232_device_desc, 0);
2795                 // under Win32, the FTD2XX driver appends an "A" to the end
2796                 // of the description, this examines the given desc
2797                 // and creates the 'missing' _A or non_A variable.
2798                 if ((cp[-1] == 'A') && (cp[-2]==' ')) {
2799                         // it was, so make this the "A" version.
2800                         ft2232_device_desc_A = ft2232_device_desc;
2801                         // and *CREATE* the non-A version.
2802                         strcpy(buf, ft2232_device_desc);
2803                         cp = strchr(buf, 0);
2804                         cp[-2] = 0;
2805                         ft2232_device_desc =  strdup(buf);
2806                 } else {
2807                         // <space > A not defined
2808                         // so create it
2809                         sprintf(buf, "%s A", ft2232_device_desc);
2810                         ft2232_device_desc_A = strdup(buf);
2811                 }
2812         }
2813         else
2814         {
2815                 LOG_ERROR("expected exactly one argument to ft2232_device_desc <description>");
2816         }
2817
2818         return ERROR_OK;
2819 }
2820
2821
2822 static int ft2232_handle_serial_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2823 {
2824         if (argc == 1)
2825         {
2826                 ft2232_serial = strdup(args[0]);
2827         }
2828         else
2829         {
2830                 LOG_ERROR("expected exactly one argument to ft2232_serial <serial-number>");
2831         }
2832
2833         return ERROR_OK;
2834 }
2835
2836
2837 static int ft2232_handle_layout_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2838 {
2839         if (argc == 0)
2840                 return ERROR_OK;
2841
2842         ft2232_layout = malloc(strlen(args[0]) + 1);
2843         strcpy(ft2232_layout, args[0]);
2844
2845         return ERROR_OK;
2846 }
2847
2848
2849 static int ft2232_handle_vid_pid_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2850 {
2851         if (argc > MAX_USB_IDS * 2)
2852         {
2853                 LOG_WARNING("ignoring extra IDs in ft2232_vid_pid "
2854                                         "(maximum is %d pairs)", MAX_USB_IDS);
2855                 argc = MAX_USB_IDS * 2;
2856         }
2857         if (argc < 2 || (argc & 1))
2858         {
2859                 LOG_WARNING("incomplete ft2232_vid_pid configuration directive");
2860                 if (argc < 2)
2861                         return ERROR_COMMAND_SYNTAX_ERROR;
2862                 // remove the incomplete trailing id
2863                 argc -= 1;
2864         }
2865
2866         int i;
2867         int retval = ERROR_OK;
2868         for (i = 0; i < argc; i += 2)
2869         {
2870                 retval = parse_u16(args[i], &ft2232_vid[i >> 1]);
2871                 if (ERROR_OK != retval)
2872                         break;
2873                 retval = parse_u16(args[i + 1], &ft2232_pid[i >> 1]);
2874                 if (ERROR_OK != retval)
2875                         break;
2876         }
2877
2878         /*
2879          * Explicitly terminate, in case there are multiples instances of
2880          * ft2232_vid_pid.
2881          */
2882         ft2232_vid[i >> 1] = ft2232_pid[i >> 1] = 0;
2883
2884         return retval;
2885 }
2886
2887
2888 static int ft2232_handle_latency_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc)
2889 {
2890         if (argc == 1)
2891         {
2892                 ft2232_latency = atoi(args[0]);
2893         }
2894         else
2895         {
2896                 LOG_ERROR("expected exactly one argument to ft2232_latency <ms>");
2897         }
2898
2899         return ERROR_OK;
2900 }
2901
2902
2903 static int ft2232_stableclocks(int num_cycles, jtag_command_t* cmd)
2904 {
2905         int retval = 0;
2906
2907         /* 7 bits of either ones or zeros. */
2908         uint8_t  tms = (tap_get_state() == TAP_RESET ? 0x7F : 0x00);
2909
2910         while (num_cycles > 0)
2911         {
2912                 /* the command 0x4b, "Clock Data to TMS/CS Pin (no Read)" handles
2913                  * at most 7 bits per invocation.  Here we invoke it potentially
2914                  * several times.
2915                  */
2916                 int bitcount_per_command = (num_cycles > 7) ? 7 : num_cycles;
2917
2918                 if (ft2232_buffer_size + 3 >= FT2232_BUFFER_SIZE)
2919                 {
2920                         if (ft2232_send_and_recv(first_unsent, cmd) != ERROR_OK)
2921                                 retval = ERROR_JTAG_QUEUE_FAILED;
2922
2923                         first_unsent = cmd;
2924                 }
2925
2926                 /* there are no state transitions in this code, so omit state tracking */
2927
2928                 /* command "Clock Data to TMS/CS Pin (no Read)" */
2929                 buffer_write(0x4b);
2930
2931                 /* scan 7 bit */
2932                 buffer_write(bitcount_per_command - 1);
2933
2934                 /* TMS data bits are either all zeros or ones to stay in the current stable state */
2935                 buffer_write(tms);
2936
2937                 require_send = 1;
2938
2939                 num_cycles -= bitcount_per_command;
2940         }
2941
2942         return retval;
2943 }
2944
2945
2946 /* ---------------------------------------------------------------------
2947  * Support for IceBear JTAG adapter from Section5:
2948  *      http://section5.ch/icebear
2949  *
2950  * Author: Sten, debian@sansys-electronic.com
2951  */
2952
2953 /* Icebear pin layout
2954  *
2955  * ADBUS5 (nEMU) nSRST  | 2   1|        GND (10k->VCC)
2956  * GND GND              | 4   3|        n.c.
2957  * ADBUS3 TMS           | 6   5|        ADBUS6 VCC
2958  * ADBUS0 TCK           | 8   7|        ADBUS7 (GND)
2959  * ADBUS4 nTRST         |10   9|        ACBUS0 (GND)
2960  * ADBUS1 TDI           |12  11|        ACBUS1 (GND)
2961  * ADBUS2 TDO           |14  13|        GND GND
2962  *
2963  * ADBUS0 O L TCK               ACBUS0 GND
2964  * ADBUS1 O L TDI               ACBUS1 GND
2965  * ADBUS2 I   TDO               ACBUS2 n.c.
2966  * ADBUS3 O H TMS               ACBUS3 n.c.
2967  * ADBUS4 O H nTRST
2968  * ADBUS5 O H nSRST
2969  * ADBUS6 -   VCC
2970  * ADBUS7 -   GND
2971  */
2972 static int icebear_jtag_init(void) {
2973         uint8_t  buf[3];
2974         uint32_t bytes_written;
2975
2976         low_direction   = 0x0b; /* output: TCK TDI TMS; input: TDO */
2977         low_output      = 0x08; /* high: TMS; low: TCK TDI */
2978         nTRST           = 0x10;
2979         nSRST           = 0x20;
2980
2981         enum reset_types jtag_reset_config = jtag_get_reset_config();
2982         if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0) {
2983                 low_direction   &= ~nTRST;      /* nTRST high impedance */
2984         }
2985         else {
2986                 low_direction   |= nTRST;
2987                 low_output      |= nTRST;
2988         }
2989
2990         low_direction   |= nSRST;
2991         low_output      |= nSRST;
2992
2993         /* initialize low byte for jtag */
2994         buf[0] = 0x80;          /* command "set data bits low byte" */
2995         buf[1] = low_output;
2996         buf[2] = low_direction;
2997         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
2998
2999         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3)) {
3000                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (low)");
3001                 return ERROR_JTAG_INIT_FAILED;
3002         }
3003
3004         high_output    = 0x0;
3005         high_direction = 0x00;
3006
3007
3008         /* initialize high port */
3009         buf[0] = 0x82;              /* command "set data bits high byte" */
3010         buf[1] = high_output;       /* value */
3011         buf[2] = high_direction;    /* all outputs (xRST and xRSTnOE) */
3012         LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
3013
3014         if (((ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3)) {
3015                 LOG_ERROR("couldn't initialize FT2232 with 'IceBear' layout (high)");
3016                 return ERROR_JTAG_INIT_FAILED;
3017         }
3018
3019         return ERROR_OK;
3020 }
3021
3022 static void icebear_jtag_reset(int trst, int srst) {
3023
3024         if (trst == 1) {
3025                 low_direction   |= nTRST;
3026                 low_output      &= ~nTRST;
3027         }
3028         else if (trst == 0) {
3029                 enum reset_types jtag_reset_config = jtag_get_reset_config();
3030                 if ((jtag_reset_config & RESET_TRST_OPEN_DRAIN) != 0)
3031                         low_direction   &= ~nTRST;
3032                 else
3033                         low_output      |= nTRST;
3034         }
3035
3036         if (srst == 1) {
3037                 low_output &= ~nSRST;
3038         }
3039         else if (srst == 0) {
3040                 low_output |= nSRST;
3041         }
3042
3043         /* command "set data bits low byte" */
3044         buffer_write(0x80);
3045         buffer_write(low_output);
3046         buffer_write(low_direction);
3047
3048         LOG_DEBUG("trst: %i, srst: %i, low_output: 0x%2.2x, low_direction: 0x%2.2x", trst, srst, low_output, low_direction);
3049 }