ft2232.c 76.3 KB
Newer Older
1
/***************************************************************************
2
3
4
5
6
7
*   Copyright (C) 2004, 2006 by Dominic Rath                              *
*   Dominic.Rath@gmx.de                                                   *
*                                                                         *
*   Copyright (C) 2008 by Spencer Oliver                                  *
*   spen@spen-soft.co.uk                                                  *
*                                                                         *
8
9
10
*   Copyright (C) 2009 by SoftPLC Corporation.  http://softplc.com        *
*	Dick Hollenbeck <dick@softplc.com>                                    *
*                                                                         *
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU General Public License     *
*   along with this program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/


/* This code uses information contained in the MPSSE specification which was
 * found here:
 * http://www.ftdichip.com/Documents/AppNotes/AN2232C-01_MPSSE_Cmnd.pdf
 * Hereafter this is called the "MPSSE Spec".
32
33
34
 *
 * The datasheet for the ftdichip.com's FT2232D part is here:
 * http://www.ftdichip.com/Documents/DataSheets/DS_FT2232D.pdf
35
36
37
 */


38
39
40
41
42
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

/* project specific includes */
43
#include "interface.h"
44
#include "commands.h"
45
46
#include "time_support.h"

47
48
49
50
#if IS_CYGWIN == 1
#include <windows.h>
#endif

51
52
53
54
#include <assert.h>

#if (BUILD_FT2232_FTD2XX==1 && BUILD_FT2232_LIBFTDI==1)
#error "BUILD_FT2232_FTD2XX && BUILD_FT2232_LIBFTDI are mutually exclusive"
zwelch's avatar
zwelch committed
55
#elif (BUILD_FT2232_FTD2XX != 1 && BUILD_FT2232_LIBFTDI != 1)
56
57
#error "BUILD_FT2232_FTD2XX || BUILD_FT2232_LIBFTDI must be chosen"
#endif
58
59
60
61
62
63
64
65

/* FT2232 access library includes */
#if BUILD_FT2232_FTD2XX == 1
#include <ftd2xx.h>
#elif BUILD_FT2232_LIBFTDI == 1
#include <ftdi.h>
#endif

66
67
68
/* max TCK for the high speed devices 30000 kHz */
#define	FTDI_2232H_4232H_MAX_TCK	30000

69
static int ft2232_execute_queue(void);
70

71
72
73
74
75
76
static int ft2232_speed(int speed);
static int ft2232_speed_div(int speed, int* khz);
static int ft2232_khz(int khz, int* jtag_speed);
static int ft2232_register_commands(struct command_context_s* cmd_ctx);
static int ft2232_init(void);
static int ft2232_quit(void);
77

78
79
80
81
82
static int ft2232_handle_device_desc_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
static int ft2232_handle_serial_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
static int ft2232_handle_layout_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
static int ft2232_handle_vid_pid_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
static int ft2232_handle_latency_command(struct command_context_s* cmd_ctx, char* cmd, char** args, int argc);
83

84
85

/**
86
87
88
89
90
91
92
93
 * Send out \a num_cycles on the TCK line while the TAP(s) are in a
 * stable state.  Calling code must ensure that current state is stable,
 * that verification is not done in here.
 *
 * @param num_cycles The number of clocks cycles to send.
 * @param cmd The command to send.
 *
 * @returns ERROR_OK on success, or ERROR_JTAG_QUEUE_FAILED on failure.
94
 */
95
static int ft2232_stableclocks(int num_cycles, jtag_command_t* cmd);
96

97
98
/* max TCK for the high speed devices 30000 kHz */
#define	FTDI_2232H_4232H_MAX_TCK	30000
99

100
101
102
103
static char *       ft2232_device_desc_A = NULL;
static char*        ft2232_device_desc = NULL;
static char*        ft2232_serial  = NULL;
static char*        ft2232_layout  = NULL;
zwelch's avatar
zwelch committed
104
static uint8_t		ft2232_latency = 2;
zwelch's avatar
zwelch committed
105
static unsigned		ft2232_max_tck = 6000;
106

107

108
#define MAX_USB_IDS 8
109
/* vid = pid = 0 marks the end of the list */
zwelch's avatar
zwelch committed
110
111
static uint16_t ft2232_vid[MAX_USB_IDS + 1] = { 0x0403, 0 };
static uint16_t ft2232_pid[MAX_USB_IDS + 1] = { 0x6010, 0 };
112
113
114
115

typedef struct ft2232_layout_s
{
	char* name;
116
117
118
	int (*init)(void);
	void (*reset)(int trst, int srst);
	void (*blink)(void);
119
120
121
} ft2232_layout_t;

/* init procedures for supported layouts */
zwelch's avatar
zwelch committed
122
123
124
125
126
127
128
129
130
131
132
static int usbjtag_init(void);
static int jtagkey_init(void);
static int olimex_jtag_init(void);
static int flyswatter_init(void);
static int turtle_init(void);
static int comstick_init(void);
static int stm32stick_init(void);
static int axm0432_jtag_init(void);
static int sheevaplug_init(void);
static int icebear_jtag_init(void);
static int cortino_jtag_init(void);
133
134

/* reset procedures for supported layouts */
135
136
137
138
139
140
141
142
143
static void usbjtag_reset(int trst, int srst);
static void jtagkey_reset(int trst, int srst);
static void olimex_jtag_reset(int trst, int srst);
static void flyswatter_reset(int trst, int srst);
static void turtle_reset(int trst, int srst);
static void comstick_reset(int trst, int srst);
static void stm32stick_reset(int trst, int srst);
static void axm0432_jtag_reset(int trst, int srst);
static void sheevaplug_reset(int trst, int srst);
144
static void icebear_jtag_reset(int trst, int srst);
145

146
/* blink procedures for layouts that support a blinking led */
147
148
149
static void olimex_jtag_blink(void);
static void flyswatter_jtag_blink(void);
static void turtle_jtag_blink(void);
150

zwelch's avatar
zwelch committed
151
static const ft2232_layout_t  ft2232_layouts[] =
152
{
153
154
155
156
157
158
159
	{ "usbjtag",              usbjtag_init,              usbjtag_reset,      NULL                    },
	{ "jtagkey",              jtagkey_init,              jtagkey_reset,      NULL                    },
	{ "jtagkey_prototype_v1", jtagkey_init,              jtagkey_reset,      NULL                    },
	{ "oocdlink",             jtagkey_init,              jtagkey_reset,      NULL                    },
	{ "signalyzer",           usbjtag_init,              usbjtag_reset,      NULL                    },
	{ "evb_lm3s811",          usbjtag_init,              usbjtag_reset,      NULL                    },
	{ "olimex-jtag",          olimex_jtag_init,          olimex_jtag_reset,  olimex_jtag_blink       },
160
	{ "flyswatter",           flyswatter_init,           flyswatter_reset,   flyswatter_jtag_blink   },
161
162
163
164
	{ "turtelizer2",          turtle_init,               turtle_reset,       turtle_jtag_blink       },
	{ "comstick",             comstick_init,             comstick_reset,     NULL                    },
	{ "stm32stick",           stm32stick_init,           stm32stick_reset,   NULL                    },
	{ "axm0432_jtag",         axm0432_jtag_init,         axm0432_jtag_reset, NULL                    },
165
	{ "sheevaplug",           sheevaplug_init,           sheevaplug_reset,   NULL                    },
166
	{ "icebear",              icebear_jtag_init,         icebear_jtag_reset, NULL                    },
167
	{ "cortino",              cortino_jtag_init,         comstick_reset, NULL                        },
168
	{ NULL,                   NULL,                      NULL,               NULL                    },
169
170
};

zwelch's avatar
zwelch committed
171
static uint8_t                  nTRST, nTRSTnOE, nSRST, nSRSTnOE;
172

zwelch's avatar
zwelch committed
173
static const ft2232_layout_t *layout;
zwelch's avatar
zwelch committed
174
175
176
177
static uint8_t                  low_output     = 0x0;
static uint8_t                  low_direction  = 0x0;
static uint8_t                  high_output    = 0x0;
static uint8_t                  high_direction = 0x0;
178
179

#if BUILD_FT2232_FTD2XX == 1
zwelch's avatar
zwelch committed
180
181
static FT_HANDLE	ftdih = NULL;
static FT_DEVICE	ftdi_device = 0;
182
183
184
185
#elif BUILD_FT2232_LIBFTDI == 1
static struct ftdi_context ftdic;
#endif

186

187
188
static jtag_command_t* first_unsent;        /* next command that has to be sent */
static int             require_send;
189

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205

/*	http://urjtag.wiki.sourceforge.net/Cable+FT2232 says:

	"There is a significant difference between libftdi and libftd2xx. The latter
	one allows to schedule up to 64*64 bytes of result data while libftdi fails
	with more than 4*64. As a consequence, the FT2232 driver is forced to
	perform around 16x more USB transactions for long command streams with TDO
	capture when running with libftdi."

	No idea how we get
	#define FT2232_BUFFER_SIZE 131072
	a comment would have been nice.
*/

#define FT2232_BUFFER_SIZE 131072

zwelch's avatar
zwelch committed
206
static uint8_t*             ft2232_buffer = NULL;
207
208
209
static int             ft2232_buffer_size  = 0;
static int             ft2232_read_pointer = 0;
static int             ft2232_expect_read  = 0;
210

211
212
213
214
215
/**
 * Function buffer_write
 * writes a byte into the byte buffer, "ft2232_buffer", which must be sent later.
 * @param val is the byte to send.
 */
zwelch's avatar
zwelch committed
216
static inline void buffer_write(uint8_t val)
217
{
zwelch's avatar
zwelch committed
218
219
	assert(ft2232_buffer);
	assert((unsigned) ft2232_buffer_size < (unsigned) FT2232_BUFFER_SIZE);
220
221
222
223
224
225
226
	ft2232_buffer[ft2232_buffer_size++] = val;
}

/**
 * Function buffer_read
 * returns a byte from the byte buffer.
 */
zwelch's avatar
zwelch committed
227
static inline uint8_t buffer_read(void)
228
{
zwelch's avatar
zwelch committed
229
230
	assert(ft2232_buffer);
	assert(ft2232_read_pointer < ft2232_buffer_size);
231
232
233
234
235
	return ft2232_buffer[ft2232_read_pointer++];
}


/**
236
 * Clocks out \a bit_count bits on the TMS line, starting with the least
237
238
239
 * significant bit of tms_bits and progressing to more significant bits.
 * Rigorous state transition logging is done here via tap_set_state().
 *
240
 * @param mpsse_cmd One of the MPSSE TMS oriented commands such as
zwelch's avatar
zwelch committed
241
242
243
 *	0x4b or 0x6b.  See the MPSSE spec referenced above for their
 *	functionality. The MPSSE command "Clock Data to TMS/CS Pin (no Read)"
 *	is often used for this, 0x4b.
244
245
246
247
 *
 * @param tms_bits Holds the sequence of bits to send.
 * @param tms_count Tells how many bits in the sequence.
 * @param tdi_bit A single bit to pass on to TDI before the first TCK
zwelch's avatar
zwelch committed
248
 *	cycle and held static for the duration of TMS clocking.
249
 *
250
 * See the MPSSE spec referenced above.
251
 */
zwelch's avatar
zwelch committed
252
static void clock_tms(uint8_t mpsse_cmd, int tms_bits, int tms_count, bool tdi_bit)
253
{
zwelch's avatar
zwelch committed
254
	uint8_t	tms_byte;
255
256
257
	int	i;
	int	tms_ndx;				/* bit index into tms_byte */

zwelch's avatar
zwelch committed
258
	assert(tms_count > 0);
259

zwelch's avatar
zwelch committed
260
//	LOG_DEBUG("mpsse cmd=%02x, tms_bits=0x%08x, bit_count=%d", mpsse_cmd, tms_bits, tms_count);
261
262
263
264
265

	for (tms_byte = tms_ndx = i = 0;   i < tms_count;   ++i, tms_bits>>=1)
	{
		bool bit = tms_bits & 1;

zwelch's avatar
zwelch committed
266
		if (bit)
267
268
269
			tms_byte |= (1<<tms_ndx);

		/* always do state transitions in public view */
zwelch's avatar
zwelch committed
270
		tap_set_state(tap_state_transition(tap_get_state(), bit));
271

zwelch's avatar
zwelch committed
272
		/*	we wrote a bit to tms_byte just above, increment bit index.  if bit was zero
273
274
275
276
			also increment.
		*/
		++tms_ndx;

zwelch's avatar
zwelch committed
277
		if (tms_ndx==7  || i==tms_count-1)
278
		{
zwelch's avatar
zwelch committed
279
280
			buffer_write(mpsse_cmd);
			buffer_write(tms_ndx - 1);
281

zwelch's avatar
zwelch committed
282
			/*	Bit 7 of the byte is passed on to TDI/DO before the first TCK/SK of
283
284
				TMS/CS and is held static for the duration of TMS/CS clocking.
			*/
zwelch's avatar
zwelch committed
285
			buffer_write(tms_byte | (tdi_bit << 7));
286
287
288
289
290
291
292
293
294
295
		}
	}
}


/**
 * Function get_tms_buffer_requirements
 * returns what clock_tms() will consume if called with
 * same \a bit_count.
 */
zwelch's avatar
zwelch committed
296
static inline int get_tms_buffer_requirements(int bit_count)
297
298
299
300
301
302
303
304
305
306
307
308
309
{
	return ((bit_count + 6)/7) * 3;
}


/**
 * Function move_to_state
 * moves the TAP controller from the current state to a
 * \a goal_state through a path given by tap_get_tms_path().  State transition
 * logging is performed by delegation to clock_tms().
 *
 * @param goal_state is the destination state for the move.
 */
zwelch's avatar
zwelch committed
310
static void move_to_state(tap_state_t goal_state)
311
{
zwelch's avatar
zwelch committed
312
	tap_state_t	start_state = tap_get_state();
313

zwelch's avatar
zwelch committed
314
	/*	goal_state is 1/2 of a tuple/pair of states which allow convenient
315
316
317
318
319
320
321
322
		lookup of the required TMS pattern to move to this state from the
		start state.
	*/

	/* do the 2 lookups */
	int tms_bits  = tap_get_tms_path(start_state, goal_state);
	int tms_count = tap_get_tms_path_len(start_state, goal_state);

zwelch's avatar
zwelch committed
323
	DEBUG_JTAG_IO("start=%s goal=%s", tap_state_name(start_state), tap_state_name(goal_state));
324

zwelch's avatar
zwelch committed
325
	clock_tms(0x4b,  tms_bits, tms_count, 0);
326
327
}

328

329
jtag_interface_t ft2232_interface =
330
{
zwelch's avatar
zwelch committed
331
332
333
334
335
336
337
338
	.name			= "ft2232",
	.execute_queue		= ft2232_execute_queue,
	.speed			= ft2232_speed,
	.speed_div		= ft2232_speed_div,
	.khz			= ft2232_khz,
	.register_commands	= ft2232_register_commands,
	.init			= ft2232_init,
	.quit			= ft2232_quit,
339
340
};

341
static int ft2232_write(uint8_t* buf, int size, uint32_t* bytes_written)
342
343
344
{
#if BUILD_FT2232_FTD2XX == 1
	FT_STATUS status;
zwelch's avatar
zwelch committed
345
346
	DWORD	dw_bytes_written;
	if ((status = FT_Write(ftdih, buf, size, &dw_bytes_written)) != FT_OK)
347
348
	{
		*bytes_written = dw_bytes_written;
349
		LOG_ERROR("FT_Write returned: %lu", status);
350
351
352
353
354
		return ERROR_JTAG_DEVICE_ERROR;
	}
	else
	{
		*bytes_written = dw_bytes_written;
355
		return ERROR_OK;
356
357
358
	}
#elif BUILD_FT2232_LIBFTDI == 1
	int retval;
zwelch's avatar
zwelch committed
359
	if ((retval = ftdi_write_data(&ftdic, buf, size)) < 0)
360
361
	{
		*bytes_written = 0;
zwelch's avatar
zwelch committed
362
		LOG_ERROR("ftdi_write_data: %s", ftdi_get_error_string(&ftdic));
363
364
365
366
367
		return ERROR_JTAG_DEVICE_ERROR;
	}
	else
	{
		*bytes_written = retval;
368
		return ERROR_OK;
369
370
371
372
	}
#endif
}

373

374
static int ft2232_read(uint8_t* buf, uint32_t size, uint32_t* bytes_read)
375
376
{
#if BUILD_FT2232_FTD2XX == 1
377
	DWORD     dw_bytes_read;
378
	FT_STATUS status;
379
	int       timeout = 5;
380
381
	*bytes_read = 0;

zwelch's avatar
zwelch committed
382
	while ((*bytes_read < size) && timeout--)
383
	{
zwelch's avatar
zwelch committed
384
385
		if ((status = FT_Read(ftdih, buf + *bytes_read, size -
					  *bytes_read, &dw_bytes_read)) != FT_OK)
386
		{
387
			*bytes_read = 0;
388
			LOG_ERROR("FT_Read returned: %lu", status);
389
390
			return ERROR_JTAG_DEVICE_ERROR;
		}
391
		*bytes_read += dw_bytes_read;
392
	}
393

394
395
396
397
#elif BUILD_FT2232_LIBFTDI == 1
	int retval;
	int timeout = 100;
	*bytes_read = 0;
398

zwelch's avatar
zwelch committed
399
	while ((*bytes_read < size) && timeout--)
400
	{
zwelch's avatar
zwelch committed
401
		if ((retval = ftdi_read_data(&ftdic, buf + *bytes_read, size - *bytes_read)) < 0)
402
403
		{
			*bytes_read = 0;
zwelch's avatar
zwelch committed
404
			LOG_ERROR("ftdi_read_data: %s", ftdi_get_error_string(&ftdic));
405
406
407
408
			return ERROR_JTAG_DEVICE_ERROR;
		}
		*bytes_read += retval;
	}
409

410
411
412
413
#endif

	if (*bytes_read < size)
	{
414
415
416
		LOG_ERROR("couldn't read the requested number of bytes from FT2232 device (%i < %i)", 
			  (unsigned int)(*bytes_read), 
			  (unsigned int)size);
417
418
		return ERROR_JTAG_DEVICE_ERROR;
	}
419

420
421
422
	return ERROR_OK;
}

423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#ifdef BUILD_FTD2XX_HIGHSPEED
static bool ft2232_device_is_highspeed(void)
{
	return (ftdi_device == FT_DEVICE_2232H) || (ftdi_device == FT_DEVICE_4232H);
}

static int ft2232_adaptive_clocking(int speed)
{
	bool use_adaptive_clocking = FALSE;
	if (0 == speed)
	{
		if (ft2232_device_is_highspeed())
			use_adaptive_clocking = TRUE;
		else
		{
			LOG_ERROR("ft2232 device %lu does not support RTCK", ftdi_device);
			return ERROR_OK;
		}
	}

zwelch's avatar
zwelch committed
443
	uint8_t  buf = use_adaptive_clocking ? 0x96 : 0x97;
444
445
	LOG_DEBUG("%2.2x", buf);

446
	uint32_t bytes_written;
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
	int retval = ft2232_write(&buf, 1, &bytes_written);
	if (ERROR_OK != retval || bytes_written != 1)
	{
		LOG_ERROR("unable to set adative clocking: %d", retval);
		return retval;
	}

	return ERROR_OK;
}
#else
static int ft2232_adaptive_clocking(int speed)
{
	// not implemented on low-speed devices
	return speed ? ERROR_OK : -1234;
}
#endif
463

464
static int ft2232_speed(int speed)
465
{
zwelch's avatar
zwelch committed
466
	uint8_t  buf[3];
467
	int retval;
468
	uint32_t bytes_written;
469

470
471
	ft2232_adaptive_clocking(speed);

zwelch's avatar
zwelch committed
472
	buf[0] = 0x86;			/* command "set divisor" */
473
474
	buf[1] = speed & 0xff;          /* valueL (0=6MHz, 1=3MHz, 2=2.0MHz, ...*/
	buf[2] = (speed >> 8) & 0xff;   /* valueH */
475

476
	LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
zwelch's avatar
zwelch committed
477
	if (((retval = ft2232_write(buf, 3, &bytes_written)) != ERROR_OK) || (bytes_written != 3))
478
	{
479
		LOG_ERROR("couldn't set FT2232 TCK speed");
480
481
482
483
484
485
		return retval;
	}

	return ERROR_OK;
}

486

487
static int ft2232_speed_div(int speed, int* khz)
mifi's avatar
mifi committed
488
{
489
	/* Take a look in the FT2232 manual,
ntfreak's avatar
ntfreak committed
490
491
	 * AN2232C-01 Command Processor for
	 * MPSSE and MCU Host Bus. Chapter 3.8 */
492

493
	*khz = ft2232_max_tck / (1 + speed);
494

mifi's avatar
mifi committed
495
496
497
	return ERROR_OK;
}

498

499
static int ft2232_khz(int khz, int* jtag_speed)
mifi's avatar
mifi committed
500
{
501
502
	if (khz==0)
	{
503
504
505
506
507
508
509
#ifdef BUILD_FTD2XX_HIGHSPEED
		*jtag_speed = 0;
		return ERROR_OK;
#else
		LOG_DEBUG("RCLK not supported");
		LOG_DEBUG("If you have a high-speed FTDI device, then "
			"OpenOCD may be built with --enable-ftd2xx-highspeed.");
510
		return ERROR_FAIL;
511
#endif
512
	}
513

514
	/* Take a look in the FT2232 manual,
ntfreak's avatar
ntfreak committed
515
516
	 * AN2232C-01 Command Processor for
	 * MPSSE and MCU Host Bus. Chapter 3.8
517
	 *
ntfreak's avatar
ntfreak committed
518
519
	 * We will calc here with a multiplier
	 * of 10 for better rounding later. */
520

521
	/* Calc speed, (ft2232_max_tck / khz) - 1 */
ntfreak's avatar
ntfreak committed
522
	/* Use 65000 for better rounding */
523
	*jtag_speed = ((ft2232_max_tck*10) / khz) - 10;
524

ntfreak's avatar
ntfreak committed
525
526
	/* Add 0.9 for rounding */
	*jtag_speed += 9;
527

ntfreak's avatar
ntfreak committed
528
529
	/* Calc real speed */
	*jtag_speed = *jtag_speed / 10;
530

ntfreak's avatar
ntfreak committed
531
532
533
534
535
	/* Check if speed is greater than 0 */
	if (*jtag_speed < 0)
	{
		*jtag_speed = 0;
	}
536

537
538
539
540
541
	/* Check max value */
	if (*jtag_speed > 0xFFFF)
	{
		*jtag_speed = 0xFFFF;
	}
542

mifi's avatar
mifi committed
543
544
545
	return ERROR_OK;
}

546

547
static int ft2232_register_commands(struct command_context_s* cmd_ctx)
548
549
{
	register_command(cmd_ctx, NULL, "ft2232_device_desc", ft2232_handle_device_desc_command,
550
			COMMAND_CONFIG, "the USB device description of the FTDI FT2232 device");
551
	register_command(cmd_ctx, NULL, "ft2232_serial", ft2232_handle_serial_command,
552
			COMMAND_CONFIG, "the serial number of the FTDI FT2232 device");
553
	register_command(cmd_ctx, NULL, "ft2232_layout", ft2232_handle_layout_command,
554
			COMMAND_CONFIG, "the layout of the FT2232 GPIO signals used to control output-enables and reset signals");
555
	register_command(cmd_ctx, NULL, "ft2232_vid_pid", ft2232_handle_vid_pid_command,
556
			COMMAND_CONFIG, "the vendor ID and product ID of the FTDI FT2232 device");
557
	register_command(cmd_ctx, NULL, "ft2232_latency", ft2232_handle_latency_command,
558
			COMMAND_CONFIG, "set the FT2232 latency timer to a new value");
559
560
561
	return ERROR_OK;
}

562

zwelch's avatar
zwelch committed
563
static void ft2232_end_state(tap_state_t state)
564
{
565
566
	if (tap_is_state_stable(state))
		tap_set_end_state(state);
567
568
	else
	{
569
		LOG_ERROR("BUG: %s is not a stable end state", tap_state_name(state));
570
571
572
573
		exit(-1);
	}
}

zwelch's avatar
zwelch committed
574
static void ft2232_read_scan(enum scan_type type, uint8_t* buffer, int scan_size)
575
{
576
	int num_bytes = (scan_size + 7) / 8;
577
	int bits_left = scan_size;
578
	int cur_byte  = 0;
579

580
	while (num_bytes-- > 1)
581
	{
582
		buffer[cur_byte++] = buffer_read();
583
584
585
586
587
		bits_left -= 8;
	}

	buffer[cur_byte] = 0x0;

zwelch's avatar
zwelch committed
588
	/* There is one more partial byte left from the clock data in/out instructions */
589
590
	if (bits_left > 1)
	{
591
		buffer[cur_byte] = buffer_read() >> 1;
592
	}
593
	/* This shift depends on the length of the clock data to tms instruction, insterted at end of the scan, now fixed to a two step transition in ft2232_add_scan */
zwelch's avatar
zwelch committed
594
	buffer[cur_byte] = (buffer[cur_byte] | (((buffer_read()) << 1) & 0x80)) >> (8 - bits_left);
595
596
}

597

598
static void ft2232_debug_dump_buffer(void)
599
{
600
601
602
	int   i;
	char  line[256];
	char* line_p = line;
603

604
605
606
607
608
	for (i = 0; i < ft2232_buffer_size; i++)
	{
		line_p += snprintf(line_p, 256 - (line_p - line), "%2.2x ", ft2232_buffer[i]);
		if (i % 16 == 15)
		{
609
			LOG_DEBUG("%s", line);
610
611
612
			line_p = line;
		}
	}
613

614
	if (line_p != line)
615
		LOG_DEBUG("%s", line);
616
617
}

618

619
static int ft2232_send_and_recv(jtag_command_t* first, jtag_command_t* last)
620
{
621
	jtag_command_t* cmd;
zwelch's avatar
zwelch committed
622
	uint8_t*             buffer;
623
624
625
	int             scan_size;
	enum scan_type  type;
	int             retval;
626
627
	uint32_t             bytes_written=0;
	uint32_t             bytes_read=0;
628

629
#ifdef _DEBUG_USB_IO_
630
631
	struct timeval  start, inter, inter2, end;
	struct timeval  d_inter, d_inter2, d_end;
632
633
634
#endif

#ifdef _DEBUG_USB_COMMS_
635
	LOG_DEBUG("write buffer (size %i):", ft2232_buffer_size);
636
637
638
639
	ft2232_debug_dump_buffer();
#endif

#ifdef _DEBUG_USB_IO_
640
	gettimeofday(&start, NULL);
641
642
#endif

zwelch's avatar
zwelch committed
643
	if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
644
	{
645
		LOG_ERROR("couldn't write MPSSE commands to FT2232");
646
		return retval;
647
	}
648

649
#ifdef _DEBUG_USB_IO_
650
	gettimeofday(&inter, NULL);
651
#endif
652

653
654
655
656
	if (ft2232_expect_read)
	{
		int timeout = 100;
		ft2232_buffer_size = 0;
657

658
#ifdef _DEBUG_USB_IO_
659
		gettimeofday(&inter2, NULL);
660
#endif
661

zwelch's avatar
zwelch committed
662
		if ((retval = ft2232_read(ft2232_buffer, ft2232_expect_read, &bytes_read)) != ERROR_OK)
663
		{
664
			LOG_ERROR("couldn't read from FT2232");
665
			return retval;
666
		}
667

668
#ifdef _DEBUG_USB_IO_
669
		gettimeofday(&end, NULL);
670
671
672
673
674

		timeval_subtract(&d_inter, &inter, &start);
		timeval_subtract(&d_inter2, &inter2, &start);
		timeval_subtract(&d_end, &end, &start);

675
676
677
678
		LOG_INFO("inter: %u.%06u, inter2: %u.%06u end: %u.%06u",
			(unsigned)d_inter.tv_sec, (unsigned)d_inter.tv_usec,
			(unsigned)d_inter2.tv_sec, (unsigned)d_inter2.tv_usec,
			(unsigned)d_end.tv_sec, (unsigned)d_end.tv_usec);
679
#endif
680

681
		ft2232_buffer_size = bytes_read;
682

683
684
		if (ft2232_expect_read != ft2232_buffer_size)
		{
685
686
687
			LOG_ERROR("ft2232_expect_read (%i) != ft2232_buffer_size (%i) (%i retries)", ft2232_expect_read,
					ft2232_buffer_size,
					100 - timeout);
688
			ft2232_debug_dump_buffer();
689
690
691
692
693

			exit(-1);
		}

#ifdef _DEBUG_USB_COMMS_
694
		LOG_DEBUG("read buffer (%i retries): %i bytes", 100 - timeout, ft2232_buffer_size);
695
696
697
698
		ft2232_debug_dump_buffer();
#endif
	}

699
	ft2232_expect_read  = 0;
700
	ft2232_read_pointer = 0;
701

702
703
	/* return ERROR_OK, unless a jtag_read_buffer returns a failed check
	 * that wasn't handled by a caller-provided error handler
704
	 */
705
	retval = ERROR_OK;
706

707
708
709
710
711
	cmd = first;
	while (cmd != last)
	{
		switch (cmd->type)
		{
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
		case JTAG_SCAN:
			type = jtag_scan_type(cmd->cmd.scan);
			if (type != SCAN_OUT)
			{
				scan_size = jtag_scan_size(cmd->cmd.scan);
				buffer    = calloc(CEIL(scan_size, 8), 1);
				ft2232_read_scan(type, buffer, scan_size);
				if (jtag_read_buffer(buffer, cmd->cmd.scan) != ERROR_OK)
					retval = ERROR_JTAG_QUEUE_FAILED;
				free(buffer);
			}
			break;

		default:
			break;
727
		}
728

729
730
		cmd = cmd->next;
	}
731

732
733
734
735
736
	ft2232_buffer_size = 0;

	return retval;
}

737

738
739
740
741
742
743
744
745
746
/**
 * Function ft2232_add_pathmove
 * moves the TAP controller from the current state to a new state through the
 * given path, where path is an array of tap_state_t's.
 *
 * @param path is an array of tap_stat_t which gives the states to traverse through
 *   ending with the last state at path[num_states-1]
 * @param num_states is the count of state steps to move through
 */
zwelch's avatar
zwelch committed
747
static void ft2232_add_pathmove(tap_state_t* path, int num_states)
748
{
749
750
751
	int			tms_bits = 0;
	int			state_ndx;
	tap_state_t	walker = tap_get_state();
752

zwelch's avatar
zwelch committed
753
	assert((unsigned) num_states <= 32u);		/* tms_bits only holds 32 bits */
754

755
	/* this loop verifies that the path is legal and logs each state in the path */
zwelch's avatar
zwelch committed
756
	for (state_ndx = 0; state_ndx < num_states;  ++state_ndx)
757
758
	{
		tap_state_t	desired_next_state = path[state_ndx];
759

zwelch's avatar
zwelch committed
760
		if (tap_state_transition(walker, false) == desired_next_state)
761
			;	/* bit within tms_bits at index state_ndx is already zero */
zwelch's avatar
zwelch committed
762
		else if (tap_state_transition(walker, true) == desired_next_state)
763
764
			tms_bits |= (1<<state_ndx);
		else
765
		{
zwelch's avatar
zwelch committed
766
767
			LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
					tap_state_name(walker), tap_state_name(desired_next_state));
768
			exit(-1);
769
		}
770

771
		walker = desired_next_state;
772
	}
773

zwelch's avatar
zwelch committed
774
	clock_tms(0x4b,  tms_bits, num_states, 0);
775

776
	tap_set_end_state(tap_get_state());
777
778
}

779

zwelch's avatar
zwelch committed
780
static void ft2232_add_scan(bool ir_scan, enum scan_type type, uint8_t* buffer, int scan_size)
781
782
783
{
	int num_bytes = (scan_size + 7) / 8;
	int bits_left = scan_size;
784
	int cur_byte  = 0;
785
786
	int last_bit;

zwelch's avatar
zwelch committed
787
	if (!ir_scan)
788
	{
789
		if (tap_get_state() != TAP_DRSHIFT)
790
		{
zwelch's avatar
zwelch committed
791
			move_to_state(TAP_DRSHIFT);
792
		}
793
794
795
796
	}
	else
	{
		if (tap_get_state() != TAP_IRSHIFT)
797
		{
zwelch's avatar
zwelch committed
798
			move_to_state(TAP_IRSHIFT);
799
800
		}
	}
801

802
803
804
805
806
807
808
	/* add command for complete bytes */
	while (num_bytes > 1)
	{
		int thisrun_bytes;
		if (type == SCAN_IO)
		{
			/* Clock Data Bytes In and Out LSB First */
zwelch's avatar
zwelch committed
809
			buffer_write(0x39);
810
			/* LOG_DEBUG("added TDI bytes (io %i)", num_bytes); */
811
812
813
814
		}
		else if (type == SCAN_OUT)
		{
			/* Clock Data Bytes Out on -ve Clock Edge LSB First (no Read) */
zwelch's avatar
zwelch committed
815
			buffer_write(0x19);
816
			/* LOG_DEBUG("added TDI bytes (o)"); */
817
818
819
820
		}
		else if (type == SCAN_IN)
		{
			/* Clock Data Bytes In on +ve Clock Edge LSB First (no Write) */
zwelch's avatar
zwelch committed
821
			buffer_write(0x28);
822
			/* LOG_DEBUG("added TDI bytes (i %i)", num_bytes); */
823
		}
824

825
		thisrun_bytes = (num_bytes > 65537) ? 65536 : (num_bytes - 1);
826
		num_bytes    -= thisrun_bytes;
827

zwelch's avatar
zwelch committed
828
829
		buffer_write((uint8_t) (thisrun_bytes - 1));
		buffer_write((uint8_t) ((thisrun_bytes - 1) >> 8));
830

831
832
833
		if (type != SCAN_IN)
		{
			/* add complete bytes */
834
			while (thisrun_bytes-- > 0)
835
			{
zwelch's avatar
zwelch committed
836
				buffer_write(buffer[cur_byte++]);
837
838
839
840
841
842
843
844
				bits_left -= 8;
			}
		}
		else /* (type == SCAN_IN) */
		{
			bits_left -= 8 * (thisrun_bytes);
		}
	}
845

846
847
	/* the most signifcant bit is scanned during TAP movement */
	if (type != SCAN_IN)
zwelch's avatar
zwelch committed
848
		last_bit = (buffer[cur_byte] >> (bits_left - 1)) & 0x1;
849
850
851
852
853
854
855
856
857
	else
		last_bit = 0;

	/* process remaining bits but the last one */
	if (bits_left > 1)
	{
		if (type == SCAN_IO)
		{
			/* Clock Data Bits In and Out LSB First */
zwelch's avatar
zwelch committed
858
			buffer_write(0x3b);
859
			/* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
860
861
862
863
		}
		else if (type == SCAN_OUT)
		{
			/* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
zwelch's avatar
zwelch committed
864
			buffer_write(0x1b);
865
			/* LOG_DEBUG("added TDI bits (o)"); */
866
867
868
869
		}
		else if (type == SCAN_IN)
		{
			/* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
zwelch's avatar
zwelch committed
870
			buffer_write(0x2a);
871
			/* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
872
		}
873

zwelch's avatar
zwelch committed
874
		buffer_write(bits_left - 2);
875
		if (type != SCAN_IN)
zwelch's avatar
zwelch committed
876
			buffer_write(buffer[cur_byte]);
877
878
	}

zwelch's avatar
zwelch committed
879
880
	if (( ir_scan && (tap_get_end_state() == TAP_IRSHIFT))
	  || (!ir_scan && (tap_get_end_state() == TAP_DRSHIFT)))
881
882
883
884
	{
		if (type == SCAN_IO)
		{
			/* Clock Data Bits In and Out LSB First */
zwelch's avatar
zwelch committed
885
			buffer_write(0x3b);
886
			/* LOG_DEBUG("added TDI bits (io) %i", bits_left - 1); */
887
888
889
890
		}
		else if (type == SCAN_OUT)
		{
			/* Clock Data Bits Out on -ve Clock Edge LSB First (no Read) */
zwelch's avatar
zwelch committed
891
			buffer_write(0x1b);
892
			/* LOG_DEBUG("added TDI bits (o)"); */
893
894
895
896
		}
		else if (type == SCAN_IN)
		{
			/* Clock Data Bits In on +ve Clock Edge LSB First (no Write) */
zwelch's avatar
zwelch committed
897
			buffer_write(0x2a);
898
			/* LOG_DEBUG("added TDI bits (i %i)", bits_left - 1); */
899
		}
zwelch's avatar
zwelch committed
900
901
		buffer_write(0x0);
		buffer_write(last_bit);
902
903
904
	}
	else
	{
905
906
		int tms_bits;
		int tms_count;
zwelch's avatar
zwelch committed
907
		uint8_t	mpsse_cmd;
908

909
910
911
		/* move from Shift-IR/DR to end state */
		if (type != SCAN_OUT)
		{
912
913
914
915
			/* We always go to the PAUSE state in two step at the end of an IN or IO scan */
			/* This must be coordinated with the bit shifts in ft2232_read_scan    */
			tms_bits  = 0x01;
			tms_count = 2;
916
			/* Clock Data to TMS/CS Pin with Read */
917
			mpsse_cmd = 0x6b;