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