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