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