ft2232.c 113 KB
Newer Older
1
/***************************************************************************
2
3
4
5
6
7
*   Copyright (C) 2009 by Øyvind Harboe                                   *
*	Øyvind Harboe <oyvind.harboe@zylin.com>                               *
*                                                                         *
*   Copyright (C) 2009 by SoftPLC Corporation.  http://softplc.com        *
*	Dick Hollenbeck <dick@softplc.com>                                    *
*                                                                         *
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
*   Copyright (C) 2004, 2006 by Dominic Rath                              *
*   Dominic.Rath@gmx.de                                                   *
*                                                                         *
*   Copyright (C) 2008 by Spencer Oliver                                  *
*   spen@spen-soft.co.uk                                                  *
*                                                                         *
*   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.             *
***************************************************************************/

David Brownell's avatar
David Brownell committed
30
31
32
33
34
/**
 * @file
 * JTAG adapters based on the FT2232 full and high speed USB parts are
 * popular low cost JTAG debug solutions.  Many FT2232 based JTAG adapters
 * are discrete, but development boards may integrate them as alternatives
David Brownell's avatar
David Brownell committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
 * to more capable (and expensive) third party JTAG pods.
 *
 * JTAG uses only one of the two communications channels ("MPSSE engines")
 * on these devices.  Adapters based on FT4232 parts have four ports/channels
 * (A/B/C/D), instead of just two (A/B).
 *
 * Especially on development boards integrating one of these chips (as
 * opposed to discrete pods/dongles), the additional channels can be used
 * for a variety of purposes, but OpenOCD only uses one channel at a time.
 *
 *  - As a USB-to-serial adapter for the target's console UART ...
 *    which may be able to support ROM boot loaders that load initial
 *    firmware images to flash (or SRAM).
 *
 *  - On systems which support ARM's SWD in addition to JTAG, or instead
 *    of it, that second port can be used for reading SWV/SWO trace data.
 *
 *  - Additional JTAG links, e.g. to a CPLD or * FPGA.
David Brownell's avatar
David Brownell committed
53
54
55
56
57
58
59
60
61
62
63
64
65
 *
 * FT2232 based JTAG adapters are "dumb" not "smart", because most JTAG
 * request/response interactions involve round trips over the USB link.
 * A "smart" JTAG adapter has intelligence close to the scan chain, so it
 * can for example poll quickly for a status change (usually taking on the
 * order of microseconds not milliseconds) before beginning a queued
 * transaction which require the previous one to have completed.
 *
 * There are dozens of adapters of this type, differing in details which
 * this driver needs to understand.  Those "layout" details are required
 * as part of FT2232 driver configuration.
 *
 * This code uses information contained in the MPSSE specification which was
66
67
68
 * found here:
 * http://www.ftdichip.com/Documents/AppNotes/AN2232C-01_MPSSE_Cmnd.pdf
 * Hereafter this is called the "MPSSE Spec".
69
70
71
 *
 * The datasheet for the ftdichip.com's FT2232D part is here:
 * http://www.ftdichip.com/Documents/DataSheets/DS_FT2232D.pdf
David Brownell's avatar
David Brownell committed
72
73
74
75
 *
 * Also note the issue with code 0x4b (clock data to TMS) noted in
 * http://developer.intra2net.com/mailarchive/html/libftdi/2009/msg00292.html
 * which can affect longer JTAG state paths.
76
77
 */

78
79
80
81
82
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

/* project specific includes */
83
#include <jtag/interface.h>
David Brownell's avatar
David Brownell committed
84
#include <jtag/transport.h>
85
#include <helper/time_support.h>
86

87
88
89
90
#if IS_CYGWIN == 1
#include <windows.h>
#endif

91
92
#include <assert.h>

zwelch's avatar
zwelch committed
93
#if (BUILD_FT2232_FTD2XX == 1 && BUILD_FT2232_LIBFTDI == 1)
94
#error "BUILD_FT2232_FTD2XX && BUILD_FT2232_LIBFTDI are mutually exclusive"
zwelch's avatar
zwelch committed
95
#elif (BUILD_FT2232_FTD2XX != 1 && BUILD_FT2232_LIBFTDI != 1)
96
97
#error "BUILD_FT2232_FTD2XX || BUILD_FT2232_LIBFTDI must be chosen"
#endif
98
99
100
101

/* FT2232 access library includes */
#if BUILD_FT2232_FTD2XX == 1
#include <ftd2xx.h>
102
103
104
105
106
107
108
109
110
111

enum ftdi_interface
{
    INTERFACE_ANY = 0,
    INTERFACE_A   = 1,
    INTERFACE_B   = 2,
    INTERFACE_C   = 3,
    INTERFACE_D   = 4
};

112
113
114
115
#elif BUILD_FT2232_LIBFTDI == 1
#include <ftdi.h>
#endif

116
117
/* max TCK for the high speed devices 30000 kHz */
#define	FTDI_2232H_4232H_MAX_TCK	30000
118
119
120
121
/* max TCK for the full speed devices 6000 kHz */
#define	FTDI_2232C_MAX_TCK 6000
/* this speed value tells that RTCK is requested */
#define RTCK_SPEED -1
122

123
124
125
126
127
128
129
130
131
132
133
/*
 * On my Athlon XP 1900+ EHCI host with FT2232H JTAG dongle I get read timeout
 * errors with a retry count of 100. Increasing it solves the problem for me.
 *	- Dimitar
 *
 * FIXME There's likely an issue with the usb_read_timeout from libftdi.
 * Fix that (libusb? kernel? libftdi? here?) and restore the retry count
 * to something sane.
 */
#define LIBFTDI_READ_RETRY_COUNT		2000

134
135
136
137
138
139
140
#ifndef BUILD_FT2232_HIGHSPEED
 #if BUILD_FT2232_FTD2XX == 1
	enum { FT_DEVICE_2232H = 6, FT_DEVICE_4232H };
 #elif BUILD_FT2232_LIBFTDI == 1
	enum { TYPE_2232H = 4, TYPE_4232H = 5 };
 #endif
#endif
141

142
/**
143
144
145
146
147
148
149
150
 * 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.
151
 */
152
static int ft2232_stableclocks(int num_cycles, struct jtag_command* cmd);
153

154
155
156
static char *       ft2232_device_desc_A = NULL;
static char*        ft2232_device_desc = NULL;
static char*        ft2232_serial  = NULL;
zwelch's avatar
zwelch committed
157
static uint8_t		ft2232_latency = 2;
158
static unsigned		ft2232_max_tck = FTDI_2232C_MAX_TCK;
159

160
#define MAX_USB_IDS 8
161
/* vid = pid = 0 marks the end of the list */
zwelch's avatar
zwelch committed
162
163
static uint16_t ft2232_vid[MAX_USB_IDS + 1] = { 0x0403, 0 };
static uint16_t ft2232_pid[MAX_USB_IDS + 1] = { 0x6010, 0 };
164

165
struct ft2232_layout {
166
	char* name;
167
168
169
	int (*init)(void);
	void (*reset)(int trst, int srst);
	void (*blink)(void);
170
	int channel;
171
};
172
173

/* init procedures for supported layouts */
zwelch's avatar
zwelch committed
174
175
static int usbjtag_init(void);
static int jtagkey_init(void);
David Brownell's avatar
David Brownell committed
176
177
static int lm3s811_jtag_init(void);
static int icdi_jtag_init(void);
zwelch's avatar
zwelch committed
178
179
180
181
182
183
184
185
186
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);
David Brownell's avatar
David Brownell committed
187
static int signalyzer_init(void);
Oleg Seiljus's avatar
Oleg Seiljus committed
188
static int signalyzer_h_init(void);
189
static int ktlink_init(void);
190
static int redbee_init(void);
191
static int lisa_l_init(void);
192
static int flossjtag_init(void);
193
194

/* reset procedures for supported layouts */
David Brownell's avatar
David Brownell committed
195
static void ftx23_reset(int trst, int srst);
196
197
198
199
200
201
202
203
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);
204
static void icebear_jtag_reset(int trst, int srst);
Oleg Seiljus's avatar
Oleg Seiljus committed
205
static void signalyzer_h_reset(int trst, int srst);
206
static void ktlink_reset(int trst, int srst);
207
static void redbee_reset(int trst, int srst);
208

209
/* blink procedures for layouts that support a blinking led */
210
211
212
static void olimex_jtag_blink(void);
static void flyswatter_jtag_blink(void);
static void turtle_jtag_blink(void);
Oleg Seiljus's avatar
Oleg Seiljus committed
213
static void signalyzer_h_blink(void);
214
static void ktlink_blink(void);
215
static void lisa_l_blink(void);
216
static void flossjtag_blink(void);
217

David Brownell's avatar
David Brownell committed
218
219
220
221
/* common transport support options */

//static const char *jtag_and_swd[] = { "jtag", "swd", NULL };

222
static const struct ft2232_layout  ft2232_layouts[] =
223
{
David Brownell's avatar
David Brownell committed
224
225
	{ .name = "usbjtag",
		.init = usbjtag_init,
David Brownell's avatar
David Brownell committed
226
		.reset = ftx23_reset,
David Brownell's avatar
David Brownell committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
	},
	{ .name = "jtagkey",
		.init = jtagkey_init,
		.reset = jtagkey_reset,
	},
	{ .name = "jtagkey_prototype_v1",
		.init = jtagkey_init,
		.reset = jtagkey_reset,
	},
	{ .name = "oocdlink",
		.init = jtagkey_init,
		.reset = jtagkey_reset,
	},
	{ .name = "signalyzer",
David Brownell's avatar
David Brownell committed
241
242
		.init = signalyzer_init,
		.reset = ftx23_reset,
David Brownell's avatar
David Brownell committed
243
244
	},
	{ .name = "evb_lm3s811",
David Brownell's avatar
David Brownell committed
245
246
		.init = lm3s811_jtag_init,
		.reset = ftx23_reset,
David Brownell's avatar
David Brownell committed
247
248
	},
	{ .name = "luminary_icdi",
David Brownell's avatar
David Brownell committed
249
250
		.init = icdi_jtag_init,
		.reset = ftx23_reset,
David Brownell's avatar
David Brownell committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
	},
	{ .name = "olimex-jtag",
		.init = olimex_jtag_init,
		.reset = olimex_jtag_reset,
		.blink = olimex_jtag_blink
	},
	{ .name = "flyswatter",
		.init = flyswatter_init,
		.reset = flyswatter_reset,
		.blink = flyswatter_jtag_blink
	},
	{ .name = "turtelizer2",
		.init = turtle_init,
		.reset = turtle_reset,
		.blink = turtle_jtag_blink
	},
	{ .name = "comstick",
		.init = comstick_init,
		.reset = comstick_reset,
	},
	{ .name = "stm32stick",
		.init = stm32stick_init,
		.reset = stm32stick_reset,
	},
	{ .name = "axm0432_jtag",
		.init = axm0432_jtag_init,
		.reset = axm0432_jtag_reset,
	},
	{ .name = "sheevaplug",
		.init = sheevaplug_init,
		.reset = sheevaplug_reset,
	},
	{ .name = "icebear",
		.init = icebear_jtag_init,
		.reset = icebear_jtag_reset,
	},
	{ .name = "cortino",
		.init = cortino_jtag_init,
		.reset = comstick_reset,
	},
	{ .name = "signalyzer-h",
		.init = signalyzer_h_init,
		.reset = signalyzer_h_reset,
		.blink = signalyzer_h_blink
	},
	{ .name = "ktlink",
		.init = ktlink_init,
		.reset = ktlink_reset,
		.blink = ktlink_blink
	},
301
302
303
304
	{ .name = "redbee-econotag",
		.init = redbee_init,
		.reset = redbee_reset,
	},
Mariano Alvira's avatar
Mariano Alvira committed
305
306
307
308
309
	{ .name = "redbee-usb",
		.init = redbee_init,
	        .reset = redbee_reset,
    	        .channel = INTERFACE_B,
	},
310
	{ .name = "lisa-l",
311
		.init = lisa_l_init,
312
		.reset = ftx23_reset,
313
		.blink = lisa_l_blink,
314
315
		.channel = INTERFACE_B,
	},
316
317
318
319
320
	{ .name = "flossjtag",
		.init = flossjtag_init,
		.reset = ftx23_reset,
		.blink = flossjtag_blink,
	},
David Brownell's avatar
David Brownell committed
321
	{ .name = NULL, /* END OF TABLE */ },
322
323
};

David Brownell's avatar
David Brownell committed
324
325
326
327
328
329
/* bitmask used to drive nTRST; usually a GPIOLx signal */
static uint8_t                  nTRST;
static uint8_t                  nTRSTnOE;
/* bitmask used to drive nSRST; usually a GPIOLx signal */
static uint8_t                  nSRST;
static uint8_t                  nSRSTnOE;
330

331
/** the layout being used with this debug session */
332
static const struct ft2232_layout *layout;
333

David Brownell's avatar
David Brownell committed
334
/** default bitmask values driven on DBUS: TCK/TDI/TDO/TMS and GPIOL(0..4) */
zwelch's avatar
zwelch committed
335
static uint8_t                  low_output     = 0x0;
336
337
338

/* note that direction bit == 1 means that signal is an output */

David Brownell's avatar
David Brownell committed
339
/** default direction bitmask for DBUS: TCK/TDI/TDO/TMS and GPIOL(0..4) */
zwelch's avatar
zwelch committed
340
static uint8_t                  low_direction  = 0x0;
David Brownell's avatar
David Brownell committed
341
/** default value bitmask for CBUS GPIOH(0..4) */
zwelch's avatar
zwelch committed
342
static uint8_t                  high_output    = 0x0;
David Brownell's avatar
David Brownell committed
343
/** default direction bitmask for CBUS GPIOH(0..4) */
zwelch's avatar
zwelch committed
344
static uint8_t                  high_direction = 0x0;
345
346

#if BUILD_FT2232_FTD2XX == 1
zwelch's avatar
zwelch committed
347
348
static FT_HANDLE	ftdih = NULL;
static FT_DEVICE	ftdi_device = 0;
349
350
#elif BUILD_FT2232_LIBFTDI == 1
static struct ftdi_context ftdic;
351
static enum ftdi_chip_type ftdi_device;
352
353
#endif

354
static struct jtag_command* first_unsent;        /* next command that has to be sent */
355
static int             require_send;
356

zwelch's avatar
zwelch committed
357
/*	http://urjtag.wiki.sourceforge.net/Cable + FT2232 says:
358
359
360
361
362
363
364
365
366
367
368
369
370
371

	"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
372
static uint8_t*             ft2232_buffer = NULL;
373
374
375
static int             ft2232_buffer_size  = 0;
static int             ft2232_read_pointer = 0;
static int             ft2232_expect_read  = 0;
376

377
378
379
380
381
/**
 * 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
382
static inline void buffer_write(uint8_t val)
383
{
zwelch's avatar
zwelch committed
384
385
	assert(ft2232_buffer);
	assert((unsigned) ft2232_buffer_size < (unsigned) FT2232_BUFFER_SIZE);
386
387
388
389
390
391
392
	ft2232_buffer[ft2232_buffer_size++] = val;
}

/**
 * Function buffer_read
 * returns a byte from the byte buffer.
 */
zwelch's avatar
zwelch committed
393
static inline uint8_t buffer_read(void)
394
{
zwelch's avatar
zwelch committed
395
396
	assert(ft2232_buffer);
	assert(ft2232_read_pointer < ft2232_buffer_size);
397
398
399
400
	return ft2232_buffer[ft2232_read_pointer++];
}

/**
401
 * Clocks out \a bit_count bits on the TMS line, starting with the least
402
403
404
 * significant bit of tms_bits and progressing to more significant bits.
 * Rigorous state transition logging is done here via tap_set_state().
 *
405
 * @param mpsse_cmd One of the MPSSE TMS oriented commands such as
zwelch's avatar
zwelch committed
406
407
408
 *	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.
409
410
411
412
 *
 * @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
413
 *	cycle and held static for the duration of TMS clocking.
414
 *
415
 * See the MPSSE spec referenced above.
416
 */
zwelch's avatar
zwelch committed
417
static void clock_tms(uint8_t mpsse_cmd, int tms_bits, int tms_count, bool tdi_bit)
418
{
zwelch's avatar
zwelch committed
419
	uint8_t	tms_byte;
420
421
422
	int	i;
	int	tms_ndx;				/* bit index into tms_byte */

zwelch's avatar
zwelch committed
423
	assert(tms_count > 0);
424

425
426
	DEBUG_JTAG_IO("mpsse cmd=%02x, tms_bits = 0x%08x, bit_count=%d",
			mpsse_cmd, tms_bits, tms_count);
427
428
429
430
431

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

zwelch's avatar
zwelch committed
432
		if (bit)
zwelch's avatar
zwelch committed
433
			tms_byte |= (1 << tms_ndx);
434
435

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

zwelch's avatar
zwelch committed
438
		/*	we wrote a bit to tms_byte just above, increment bit index.  if bit was zero
439
440
441
442
			also increment.
		*/
		++tms_ndx;

zwelch's avatar
zwelch committed
443
		if (tms_ndx == 7  || i == tms_count-1)
444
		{
zwelch's avatar
zwelch committed
445
446
			buffer_write(mpsse_cmd);
			buffer_write(tms_ndx - 1);
447

zwelch's avatar
zwelch committed
448
			/*	Bit 7 of the byte is passed on to TDI/DO before the first TCK/SK of
449
450
				TMS/CS and is held static for the duration of TMS/CS clocking.
			*/
zwelch's avatar
zwelch committed
451
			buffer_write(tms_byte | (tdi_bit << 7));
452
453
454
455
456
457
458
459
460
		}
	}
}

/**
 * Function get_tms_buffer_requirements
 * returns what clock_tms() will consume if called with
 * same \a bit_count.
 */
zwelch's avatar
zwelch committed
461
static inline int get_tms_buffer_requirements(int bit_count)
462
463
464
465
466
467
468
469
470
471
472
473
{
	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
474
static void move_to_state(tap_state_t goal_state)
475
{
zwelch's avatar
zwelch committed
476
	tap_state_t	start_state = tap_get_state();
477

zwelch's avatar
zwelch committed
478
	/*	goal_state is 1/2 of a tuple/pair of states which allow convenient
479
480
481
482
483
484
485
486
		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
487
	DEBUG_JTAG_IO("start=%s goal=%s", tap_state_name(start_state), tap_state_name(goal_state));
488

zwelch's avatar
zwelch committed
489
	clock_tms(0x4b,  tms_bits, tms_count, 0);
490
491
}

492
static int ft2232_write(uint8_t* buf, int size, uint32_t* bytes_written)
493
494
495
{
#if BUILD_FT2232_FTD2XX == 1
	FT_STATUS status;
496
	DWORD dw_bytes_written;
zwelch's avatar
zwelch committed
497
	if ((status = FT_Write(ftdih, buf, size, &dw_bytes_written)) != FT_OK)
498
499
	{
		*bytes_written = dw_bytes_written;
500
		LOG_ERROR("FT_Write returned: %lu", status);
501
502
503
504
505
506
507
508
		return ERROR_JTAG_DEVICE_ERROR;
	}
	else
	{
		*bytes_written = dw_bytes_written;
	}
#elif BUILD_FT2232_LIBFTDI == 1
	int retval;
zwelch's avatar
zwelch committed
509
	if ((retval = ftdi_write_data(&ftdic, buf, size)) < 0)
510
511
	{
		*bytes_written = 0;
zwelch's avatar
zwelch committed
512
		LOG_ERROR("ftdi_write_data: %s", ftdi_get_error_string(&ftdic));
513
514
515
516
517
518
519
		return ERROR_JTAG_DEVICE_ERROR;
	}
	else
	{
		*bytes_written = retval;
	}
#endif
Marc Pignat's avatar
Marc Pignat committed
520
521
522
523
524
525
526

	if (*bytes_written != (uint32_t)size)
	{
		return ERROR_JTAG_DEVICE_ERROR;
	}

	return ERROR_OK;
527
528
}

529
static int ft2232_read(uint8_t* buf, uint32_t size, uint32_t* bytes_read)
530
531
{
#if BUILD_FT2232_FTD2XX == 1
532
	DWORD dw_bytes_read;
533
	FT_STATUS status;
534
	int timeout = 5;
535
536
	*bytes_read = 0;

zwelch's avatar
zwelch committed
537
	while ((*bytes_read < size) && timeout--)
538
	{
zwelch's avatar
zwelch committed
539
540
		if ((status = FT_Read(ftdih, buf + *bytes_read, size -
					  *bytes_read, &dw_bytes_read)) != FT_OK)
541
		{
542
			*bytes_read = 0;
543
			LOG_ERROR("FT_Read returned: %lu", status);
544
545
			return ERROR_JTAG_DEVICE_ERROR;
		}
546
		*bytes_read += dw_bytes_read;
547
	}
548

549
550
#elif BUILD_FT2232_LIBFTDI == 1
	int retval;
551
	int timeout = LIBFTDI_READ_RETRY_COUNT;
552
	*bytes_read = 0;
553

zwelch's avatar
zwelch committed
554
	while ((*bytes_read < size) && timeout--)
555
	{
zwelch's avatar
zwelch committed
556
		if ((retval = ftdi_read_data(&ftdic, buf + *bytes_read, size - *bytes_read)) < 0)
557
558
		{
			*bytes_read = 0;
zwelch's avatar
zwelch committed
559
			LOG_ERROR("ftdi_read_data: %s", ftdi_get_error_string(&ftdic));
560
561
562
563
			return ERROR_JTAG_DEVICE_ERROR;
		}
		*bytes_read += retval;
	}
564

565
566
567
568
#endif

	if (*bytes_read < size)
	{
569
570
571
572
		LOG_ERROR("couldn't read enough bytes from "
				"FT2232 device (%i < %i)",
				(unsigned)*bytes_read,
				(unsigned)size);
573
574
		return ERROR_JTAG_DEVICE_ERROR;
	}
575

576
577
578
	return ERROR_OK;
}

579
580
static bool ft2232_device_is_highspeed(void)
{
581
#if BUILD_FT2232_FTD2XX == 1
582
	return (ftdi_device == FT_DEVICE_2232H) || (ftdi_device == FT_DEVICE_4232H);
583
#elif BUILD_FT2232_LIBFTDI == 1
584
585
	return (ftdi_device == TYPE_2232H || ftdi_device == TYPE_4232H);
#endif
586
587
}

588
589
590
591
592
/*
 * Commands that only apply to the FT2232H and FT4232H devices.
 * See chapter 6 in http://www.ftdichip.com/Documents/AppNotes/
 * AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf
 */
593

594
595
596
static int ft2232h_ft4232h_adaptive_clocking(bool enable)
{
	uint8_t buf = enable ? 0x96 : 0x97;
597
598
	LOG_DEBUG("%2.2x", buf);

599
	uint32_t bytes_written;
Marc Pignat's avatar
Marc Pignat committed
600
601
602
	int retval;

	if ((retval = ft2232_write(&buf, sizeof(buf), &bytes_written)) != ERROR_OK)
603
	{
604
605
		LOG_ERROR("couldn't write command to %s adaptive clocking"
			, enable ? "enable" : "disable");
606
607
608
609
610
		return retval;
	}

	return ERROR_OK;
}
611
612
613
614
615
616
617

/**
 * Enable/disable the clk divide by 5 of the 60MHz master clock.
 * This result in a JTAG clock speed range of 91.553Hz-6MHz
 * respective 457.763Hz-30MHz.
 */
static int ft2232h_ft4232h_clk_divide_by_5(bool enable)
618
{
619
620
	uint32_t bytes_written;
	uint8_t buf = enable ?  0x8b : 0x8a;
Marc Pignat's avatar
Marc Pignat committed
621
622

	if (ft2232_write(&buf, sizeof(buf), &bytes_written) != ERROR_OK)
623
624
625
626
627
628
629
630
631
	{
		LOG_ERROR("couldn't write command to %s clk divide by 5"
			, enable ? "enable" : "disable");
		return ERROR_JTAG_INIT_FAILED;
	}
	ft2232_max_tck = enable ? FTDI_2232C_MAX_TCK : FTDI_2232H_4232H_MAX_TCK;
	LOG_INFO("max TCK change to: %u kHz", ft2232_max_tck);

	return ERROR_OK;
632
}
633

634
static int ft2232_speed(int speed)
635
{
636
	uint8_t buf[3];
637
	int retval;
638
	uint32_t bytes_written;
639

640
641
642
643
644
645
646
647
648
649
650
651
652
	retval = ERROR_OK;
	bool enable_adaptive_clocking = (RTCK_SPEED == speed);
	if (ft2232_device_is_highspeed())
		retval = ft2232h_ft4232h_adaptive_clocking(enable_adaptive_clocking);
	else if (enable_adaptive_clocking)
	{
		LOG_ERROR("ft2232 device %lu does not support RTCK"
			, (long unsigned int)ftdi_device);
		return ERROR_FAIL;
	}

	if ((enable_adaptive_clocking) || (ERROR_OK != retval))
		return retval;
653

654
655
656
	buf[0] = 0x86;					/* command "set divisor" */
	buf[1] = speed & 0xff;			/* valueL (0 = 6MHz, 1 = 3MHz, 2 = 2.0MHz, ...*/
	buf[2] = (speed >> 8) & 0xff;	/* valueH */
657

658
	LOG_DEBUG("%2.2x %2.2x %2.2x", buf[0], buf[1], buf[2]);
Marc Pignat's avatar
Marc Pignat committed
659
	if ((retval = ft2232_write(buf, sizeof(buf), &bytes_written)) != ERROR_OK)
660
	{
661
		LOG_ERROR("couldn't set FT2232 TCK speed");
662
663
664
665
666
667
		return retval;
	}

	return ERROR_OK;
}

668
static int ft2232_speed_div(int speed, int* khz)
mifi's avatar
mifi committed
669
{
670
	/* Take a look in the FT2232 manual,
ntfreak's avatar
ntfreak committed
671
672
	 * AN2232C-01 Command Processor for
	 * MPSSE and MCU Host Bus. Chapter 3.8 */
673

674
	*khz = (RTCK_SPEED == speed) ? 0 : ft2232_max_tck / (1 + speed);
675

mifi's avatar
mifi committed
676
677
678
	return ERROR_OK;
}

679
static int ft2232_khz(int khz, int* jtag_speed)
mifi's avatar
mifi committed
680
{
zwelch's avatar
zwelch committed
681
	if (khz == 0)
682
	{
683
684
685
686
687
688
689
690
691
692
		if (ft2232_device_is_highspeed())
		{
			*jtag_speed = RTCK_SPEED;
			return ERROR_OK;
		}
		else
		{
			LOG_DEBUG("RCLK not supported");
			return ERROR_FAIL;
		}
693
	}
694

695
	/* Take a look in the FT2232 manual,
ntfreak's avatar
ntfreak committed
696
697
	 * AN2232C-01 Command Processor for
	 * MPSSE and MCU Host Bus. Chapter 3.8
698
	 *
ntfreak's avatar
ntfreak committed
699
700
	 * We will calc here with a multiplier
	 * of 10 for better rounding later. */
701

702
	/* Calc speed, (ft2232_max_tck / khz) - 1 */
ntfreak's avatar
ntfreak committed
703
	/* Use 65000 for better rounding */
704
	*jtag_speed = ((ft2232_max_tck*10) / khz) - 10;
705

ntfreak's avatar
ntfreak committed
706
707
	/* Add 0.9 for rounding */
	*jtag_speed += 9;
708

ntfreak's avatar
ntfreak committed
709
710
	/* Calc real speed */
	*jtag_speed = *jtag_speed / 10;
711

ntfreak's avatar
ntfreak committed
712
713
714
715
716
	/* Check if speed is greater than 0 */
	if (*jtag_speed < 0)
	{
		*jtag_speed = 0;
	}
717

718
719
720
721
722
	/* Check max value */
	if (*jtag_speed > 0xFFFF)
	{
		*jtag_speed = 0xFFFF;
	}
723

mifi's avatar
mifi committed
724
725
726
	return ERROR_OK;
}

zwelch's avatar
zwelch committed
727
static void ft2232_end_state(tap_state_t state)
728
{
729
730
	if (tap_is_state_stable(state))
		tap_set_end_state(state);
731
732
	else
	{
733
		LOG_ERROR("BUG: %s is not a stable end state", tap_state_name(state));
734
735
736
737
		exit(-1);
	}
}

zwelch's avatar
zwelch committed
738
static void ft2232_read_scan(enum scan_type type, uint8_t* buffer, int scan_size)
739
{
740
741
742
	int num_bytes = (scan_size + 7) / 8;
	int bits_left = scan_size;
	int cur_byte  = 0;
743

744
	while (num_bytes-- > 1)
745
	{
746
747
		buffer[cur_byte++] = buffer_read();
		bits_left -= 8;
748
749
	}

750
751
752
	buffer[cur_byte] = 0x0;

	/* There is one more partial byte left from the clock data in/out instructions */
753
754
	if (bits_left > 1)
	{
755
		buffer[cur_byte] = buffer_read() >> 1;
756
	}
757
	/* 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
758
	buffer[cur_byte] = (buffer[cur_byte] | (((buffer_read()) << 1) & 0x80)) >> (8 - bits_left);
759
760
}

761
static void ft2232_debug_dump_buffer(void)
762
{
763
764
	int i;
	char line[256];
765
	char* line_p = line;
766

767
768
	for (i = 0; i < ft2232_buffer_size; i++)
	{
Marc Pignat's avatar
Marc Pignat committed
769
		line_p += snprintf(line_p, sizeof(line) - (line_p - line), "%2.2x ", ft2232_buffer[i]);
770
771
		if (i % 16 == 15)
		{
772
			LOG_DEBUG("%s", line);
773
774
775
			line_p = line;
		}
	}
776

777
	if (line_p != line)
778
		LOG_DEBUG("%s", line);
779
780
}

781
static int ft2232_send_and_recv(struct jtag_command* first, struct jtag_command* last)
782
{
783
	struct jtag_command* cmd;
784
785
	uint8_t* buffer;
	int scan_size;
786
	enum scan_type  type;
787
788
789
	int retval;
	uint32_t bytes_written = 0;
	uint32_t bytes_read = 0;
790

791
#ifdef _DEBUG_USB_IO_
792
793
	struct timeval  start, inter, inter2, end;
	struct timeval  d_inter, d_inter2, d_end;
794
795
796
#endif

#ifdef _DEBUG_USB_COMMS_
797
	LOG_DEBUG("write buffer (size %i):", ft2232_buffer_size);
798
799
800
801
	ft2232_debug_dump_buffer();
#endif

#ifdef _DEBUG_USB_IO_
802
	gettimeofday(&start, NULL);
803
804
#endif

zwelch's avatar
zwelch committed
805
	if ((retval = ft2232_write(ft2232_buffer, ft2232_buffer_size, &bytes_written)) != ERROR_OK)
806
	{
807
		LOG_ERROR("couldn't write MPSSE commands to FT2232");
808
		return retval;
809
	}
810

811
#ifdef _DEBUG_USB_IO_
812
	gettimeofday(&inter, NULL);
813
#endif
814

815
816
	if (ft2232_expect_read)
	{
817
818
		/* FIXME this "timeout" is never changed ... */
		int timeout = LIBFTDI_READ_RETRY_COUNT;
819
		ft2232_buffer_size = 0;
820

821
#ifdef _DEBUG_USB_IO_
822
		gettimeofday(&inter2, NULL);
823
#endif
824

zwelch's avatar
zwelch committed
825
		if ((retval = ft2232_read(ft2232_buffer, ft2232_expect_read, &bytes_read)) != ERROR_OK)
826
		{
827
			LOG_ERROR("couldn't read from FT2232");
828
			return retval;
829
		}
830

831
#ifdef _DEBUG_USB_IO_
832
		gettimeofday(&end, NULL);
833
834
835
836
837

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

838
839
840
841
		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);
842
#endif
843

844
		ft2232_buffer_size = bytes_read;
845

846
847
		if (ft2232_expect_read != ft2232_buffer_size)
		{
848
849
850
851
			LOG_ERROR("ft2232_expect_read (%i) != "
					"ft2232_buffer_size (%i) "
					"(%i retries)",
					ft2232_expect_read,
852
					ft2232_buffer_size,
853
					LIBFTDI_READ_RETRY_COUNT - timeout);
854
			ft2232_debug_dump_buffer();
855
856
857
858
859

			exit(-1);
		}

#ifdef _DEBUG_USB_COMMS_
860
861
862
		LOG_DEBUG("read buffer (%i retries): %i bytes",
				LIBFTDI_READ_RETRY_COUNT - timeout,
				ft2232_buffer_size);
863
864
865
866
		ft2232_debug_dump_buffer();
#endif
	}

867
	ft2232_expect_read  = 0;
868
	ft2232_read_pointer = 0;
869

870
871
	/* return ERROR_OK, unless a jtag_read_buffer returns a failed check
	 * that wasn't handled by a caller-provided error handler
872
	 */
873
	retval = ERROR_OK;
874

875
876
877
878
879
	cmd = first;
	while (cmd != last)
	{
		switch (cmd->type)
		{
880
881
882
883
884
		case JTAG_SCAN:
			type = jtag_scan_type(cmd->cmd.scan);
			if (type != SCAN_OUT)
			{
				scan_size = jtag_scan_size(cmd->cmd.scan);
Zachary T Welch's avatar
Zachary T Welch committed
885
				buffer    = calloc(DIV_ROUND_UP(scan_size, 8), 1);
886
887
888
889
890
891
892
893
894
				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;
895
		}
896

897
898
		cmd = cmd->next;
	}
899

900
901
902
903
904
	ft2232_buffer_size = 0;

	return retval;
}

905
906
907
908
909
910
911
912
913
/**
 * 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
914
static void ft2232_add_pathmove(tap_state_t* path, int num_states)
915
{
916
	int state_count = 0;
917

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

920
921
	DEBUG_JTAG_IO("-");

922
	/* this loop verifies that the path is legal and logs each state in the path */
923
	while (num_states)
924
	{
925
926
927
		unsigned char	tms_byte = 0;       /* zero this on each MPSSE batch */
		int		bit_count = 0;
		int		num_states_batch = num_states > 7 ? 7 : num_states;
928
929
930

		/* command "Clock Data to TMS/CS Pin (no Read)" */
		buffer_write(0x4b);
931

932
933
934
		/* number of states remaining */
		buffer_write(num_states_batch - 1);

935
936
937
938
		while (num_states_batch--) {
			/* either TMS=0 or TMS=1 must work ... */
			if (tap_state_transition(tap_get_state(), false)
						== path[state_count])
939
				buf_set_u32(&tms_byte, bit_count++, 1, 0x0);
940
941
			else if (tap_state_transition(tap_get_state(), true)
						== path[state_count])
942
				buf_set_u32(&tms_byte, bit_count++, 1, 0x1);
943
944
945
946
947
948
949

			/* ... or else the caller goofed BADLY */
			else {
				LOG_ERROR("BUG: %s -> %s isn't a valid "
						"TAP state transition",
					tap_state_name(tap_get_state()),
					tap_state_name(path[state_count]));
950
951
952
				exit(-1);
			}

953
			tap_set_state(path[state_count]);
954
955
956
			state_count++;
			num_states--;
		}
957

958
		buffer_write(tms_byte);
959
	}
960
	tap_set_end_state(tap_get_state());
961
962
}

zwelch's avatar
zwelch committed
963
static void ft2232_add_scan(bool ir_scan, enum scan_type type, uint8_t* buffer, int scan_size)
964
965
966
{
	int num_bytes = (scan_size + 7) / 8;
	int bits_left = scan_size;
967
	int cur_byte  = 0;
968
969
	int last_bit;

zwelch's avatar
zwelch committed
970
	if (!ir_scan)
971
	{
972
		if (tap_get_state() != TAP_DRSHIFT)
973
		{
zwelch's avatar
zwelch committed
974
			move_to_state(TAP_DRSHIFT);
975
		}
976
977
978
979
	}
	else
	{
		if (tap_get_state() != TAP_IRSHIFT)
980
		{
zwelch's avatar
zwelch committed
981
			move_to_state(TAP_IRSHIFT);
982
983
		}
	}
984