0389427d881fe553658177cd0d2b3ea6de930903
[fw/openocd] / src / jtag / drivers / ft232r.c
1 /***************************************************************************
2  *   Copyright (C) 2010 Serge Vakulenko                                    *
3  *   serge@vak.ru                                                          *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
17  ***************************************************************************/
18
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
22
23 #if IS_CYGWIN == 1
24 #include "windows.h"
25 #undef LOG_ERROR
26 #endif
27
28 /* project specific includes */
29 #include <jtag/interface.h>
30 #include <jtag/commands.h>
31 #include <helper/time_support.h>
32 #include "libusb1_common.h"
33
34 /* system includes */
35 #include <string.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <sys/time.h>
39 #include <time.h>
40
41 /*
42  * Sync bit bang mode is implemented as described in FTDI Application
43  * Note AN232R-01: "Bit Bang Modes for the FT232R and FT245R".
44  */
45
46 /*
47  * USB endpoints.
48  */
49 #define IN_EP                   0x02
50 #define OUT_EP                  0x81
51
52 /* Requests */
53 #define SIO_RESET               0 /* Reset the port */
54 #define SIO_MODEM_CTRL          1 /* Set the modem control register */
55 #define SIO_SET_FLOW_CTRL       2 /* Set flow control register */
56 #define SIO_SET_BAUD_RATE       3 /* Set baud rate */
57 #define SIO_SET_DATA            4 /* Set the data characteristics of the port */
58 #define SIO_POLL_MODEM_STATUS   5
59 #define SIO_SET_EVENT_CHAR      6
60 #define SIO_SET_ERROR_CHAR      7
61 #define SIO_SET_LATENCY_TIMER   9
62 #define SIO_GET_LATENCY_TIMER   10
63 #define SIO_SET_BITMODE         11
64 #define SIO_READ_PINS           12
65 #define SIO_READ_EEPROM         0x90
66 #define SIO_WRITE_EEPROM        0x91
67 #define SIO_ERASE_EEPROM        0x92
68
69 #define FT232R_BUF_SIZE_EXTRA   4096
70
71 static char *ft232r_serial_desc;
72 static uint16_t ft232r_vid = 0x0403; /* FTDI */
73 static uint16_t ft232r_pid = 0x6001; /* FT232R */
74 static jtag_libusb_device_handle *adapter;
75
76 static uint8_t *ft232r_output;
77 static size_t ft232r_output_len;
78
79 /**
80  * FT232R GPIO bit number to RS232 name
81  */
82 #define FT232R_BIT_COUNT 8
83 static char *ft232r_bit_name_array[FT232R_BIT_COUNT] = {
84         "TXD", /* 0: pin 1  TCK output */
85         "RXD", /* 1: pin 5  TDI output */
86         "RTS", /* 2: pin 3  TDO input */
87         "CTS", /* 3: pin 11 TMS output */
88         "DTR", /* 4: pin 2  /TRST output */
89         "DSR", /* 5: pin 9  unused */
90         "DCD", /* 6: pin 10 /SYSRST output */
91         "RI"   /* 7: pin 6  unused */
92 };
93
94 static int tck_gpio; /* initialized to 0 by default */
95 static int tdi_gpio = 1;
96 static int tdo_gpio = 2;
97 static int tms_gpio = 3;
98 static int ntrst_gpio = 4;
99 static int nsysrst_gpio = 6;
100 static size_t ft232r_buf_size = FT232R_BUF_SIZE_EXTRA;
101 /** 0xFFFF disables restore by default, after exit serial port will not work.
102  *  0x15 sets TXD RTS DTR as outputs, after exit serial port will continue to work.
103  */
104 static uint16_t ft232r_restore_bitmode = 0xFFFF;
105
106 /**
107  * Perform sync bitbang output/input transaction.
108  * Before call, an array ft232r_output[] should be filled with data to send.
109  * Counter ft232r_output_len contains the number of bytes to send.
110  * On return, received data is put back to array ft232r_output[].
111  */
112 static int ft232r_send_recv(void)
113 {
114         /* FIFO TX buffer has 128 bytes.
115          * FIFO RX buffer has 256 bytes.
116          * First two bytes of received packet contain contain modem
117          * and line status and are ignored.
118          * Unfortunately, transfer sizes bigger than 64 bytes
119          * frequently cause hang ups. */
120         assert(ft232r_output_len > 0);
121
122         size_t total_written = 0;
123         size_t total_read = 0;
124         int rxfifo_free = 128;
125
126         while (total_read < ft232r_output_len) {
127                 /* Write */
128                 int bytes_to_write = ft232r_output_len - total_written;
129                 if (bytes_to_write > 64)
130                         bytes_to_write = 64;
131                 if (bytes_to_write > rxfifo_free)
132                         bytes_to_write = rxfifo_free;
133
134                 if (bytes_to_write) {
135                         int n = jtag_libusb_bulk_write(adapter, IN_EP,
136                                 (char *) ft232r_output + total_written,
137                                 bytes_to_write, 1000);
138
139                         if (n == 0) {
140                                 LOG_ERROR("usb bulk write failed");
141                                 return ERROR_JTAG_DEVICE_ERROR;
142                         }
143
144                         total_written += n;
145                         rxfifo_free -= n;
146                 }
147
148                 /* Read */
149                 uint8_t reply[64];
150
151                 int n = jtag_libusb_bulk_read(adapter, OUT_EP,
152                         (char *) reply,
153                         sizeof(reply), 1000);
154
155                 if (n == 0) {
156                         LOG_ERROR("usb bulk read failed");
157                         return ERROR_JTAG_DEVICE_ERROR;
158                 }
159                 if (n > 2) {
160                         /* Copy data, ignoring first 2 bytes. */
161                         memcpy(ft232r_output + total_read, reply + 2, n - 2);
162                         int bytes_read = n - 2;
163                         total_read += bytes_read;
164                         rxfifo_free += bytes_read;
165                         if (total_read > total_written) {
166                                 LOG_ERROR("read more bytes than wrote");
167                                 return ERROR_JTAG_DEVICE_ERROR;
168                         }
169                 }
170         }
171         ft232r_output_len = 0;
172         return ERROR_OK;
173 }
174
175 void ft232r_increase_buf_size(size_t new_buf_size)
176 {
177         uint8_t *new_buf_ptr;
178         if (new_buf_size >= ft232r_buf_size) {
179                 new_buf_size += FT232R_BUF_SIZE_EXTRA;
180                 new_buf_ptr = realloc(ft232r_output, new_buf_size);
181                 if (new_buf_ptr != NULL) {
182                         ft232r_output = new_buf_ptr;
183                         ft232r_buf_size = new_buf_size;
184                 }
185         }
186 }
187
188 /**
189  * Add one TCK/TMS/TDI sample to send buffer.
190  */
191 static void ft232r_write(int tck, int tms, int tdi)
192 {
193         unsigned out_value = (1<<ntrst_gpio) | (1<<nsysrst_gpio);
194         if (tck)
195                 out_value |= (1<<tck_gpio);
196         if (tms)
197                 out_value |= (1<<tms_gpio);
198         if (tdi)
199                 out_value |= (1<<tdi_gpio);
200
201         ft232r_increase_buf_size(ft232r_output_len);
202
203         if (ft232r_output_len >= ft232r_buf_size) {
204                 /* FIXME: should we just execute queue here? */
205                 LOG_ERROR("ft232r_write: buffer overflow");
206                 return;
207         }
208         ft232r_output[ft232r_output_len++] = out_value;
209 }
210
211 /**
212  * Control /TRST and /SYSRST pins.
213  * Perform immediate bitbang transaction.
214  */
215 static void ft232r_reset(int trst, int srst)
216 {
217         unsigned out_value = (1<<ntrst_gpio) | (1<<nsysrst_gpio);
218         LOG_DEBUG("ft232r_reset(%d,%d)", trst, srst);
219
220         if (trst == 1)
221                 out_value &= ~(1<<ntrst_gpio);          /* switch /TRST low */
222         else if (trst == 0)
223                 out_value |= (1<<ntrst_gpio);                   /* switch /TRST high */
224
225         if (srst == 1)
226                 out_value &= ~(1<<nsysrst_gpio);                /* switch /SYSRST low */
227         else if (srst == 0)
228                 out_value |= (1<<nsysrst_gpio);         /* switch /SYSRST high */
229
230         ft232r_increase_buf_size(ft232r_output_len);
231
232         if (ft232r_output_len >= ft232r_buf_size) {
233                 /* FIXME: should we just execute queue here? */
234                 LOG_ERROR("ft232r_write: buffer overflow");
235                 return;
236         }
237
238         ft232r_output[ft232r_output_len++] = out_value;
239         ft232r_send_recv();
240 }
241
242 static int ft232r_speed(int divisor)
243 {
244         int baud = (divisor == 0) ? 3000000 :
245                 (divisor == 1) ? 2000000 :
246                 3000000 / divisor;
247         LOG_DEBUG("ft232r_speed(%d) rate %d bits/sec", divisor, baud);
248
249         if (jtag_libusb_control_transfer(adapter,
250                 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_OUT,
251                 SIO_SET_BAUD_RATE, divisor, 0, 0, 0, 1000) != 0) {
252                 LOG_ERROR("cannot set baud rate");
253                 return ERROR_JTAG_DEVICE_ERROR;
254         }
255         return ERROR_OK;
256 }
257
258 static int ft232r_init(void)
259 {
260         uint16_t avids[] = {ft232r_vid, 0};
261         uint16_t apids[] = {ft232r_pid, 0};
262         if (jtag_libusb_open(avids, apids, ft232r_serial_desc, &adapter)) {
263                 LOG_ERROR("ft232r not found: vid=%04x, pid=%04x, serial=%s\n",
264                         ft232r_vid, ft232r_pid, (ft232r_serial_desc == NULL) ? "[any]" : ft232r_serial_desc);
265                 return ERROR_JTAG_INIT_FAILED;
266         }
267
268         if (ft232r_restore_bitmode == 0xFFFF) /* serial port will not be restored after jtag: */
269                 libusb_detach_kernel_driver(adapter, 0);
270         else /* serial port will be restored after jtag: */
271                 libusb_set_auto_detach_kernel_driver(adapter, 1); /* 1: DONT_DETACH_SIO_MODULE */
272
273         if (jtag_libusb_claim_interface(adapter, 0)) {
274                 LOG_ERROR("unable to claim interface");
275                 return ERROR_JTAG_INIT_FAILED;
276         }
277
278         /* Reset the device. */
279         if (jtag_libusb_control_transfer(adapter,
280                 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_OUT,
281                 SIO_RESET, 0, 0, 0, 0, 1000) != 0) {
282                 LOG_ERROR("unable to reset device");
283                 return ERROR_JTAG_INIT_FAILED;
284         }
285
286         /* Sync bit bang mode. */
287         if (jtag_libusb_control_transfer(adapter,
288                 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_OUT,
289                 SIO_SET_BITMODE, (1<<tck_gpio) | (1<<tdi_gpio) | (1<<tms_gpio) | (1<<ntrst_gpio) | (1<<nsysrst_gpio) | 0x400,
290                 0, 0, 0, 1000) != 0) {
291                 LOG_ERROR("cannot set sync bitbang mode");
292                 return ERROR_JTAG_INIT_FAILED;
293         }
294
295         /* Exactly 500 nsec between updates. */
296         unsigned divisor = 1;
297         unsigned char latency_timer = 1;
298
299         /* Frequency divisor is 14-bit non-zero value. */
300         if (jtag_libusb_control_transfer(adapter,
301                 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_OUT,
302                 SIO_SET_BAUD_RATE, divisor,
303                 0, 0, 0, 1000) != 0) {
304                 LOG_ERROR("cannot set baud rate");
305                 return ERROR_JTAG_INIT_FAILED;
306         }
307         if (jtag_libusb_control_transfer(adapter,
308                 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_OUT,
309                 SIO_SET_LATENCY_TIMER, latency_timer, 0, 0, 0, 1000) != 0) {
310                 LOG_ERROR("unable to set latency timer");
311                 return ERROR_JTAG_INIT_FAILED;
312         }
313
314         ft232r_output = malloc(ft232r_buf_size);
315         if (ft232r_output == NULL) {
316                 LOG_ERROR("Unable to allocate memory for the buffer");
317                 return ERROR_JTAG_INIT_FAILED;
318         }
319
320         return ERROR_OK;
321 }
322
323 static int ft232r_quit(void)
324 {
325         /* to restore serial port: set TXD RTS DTR as outputs, others as inputs, disable sync bit bang mode. */
326         if (ft232r_restore_bitmode != 0xFFFF) {
327                 if (jtag_libusb_control_transfer(adapter,
328                         LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_OUT,
329                         SIO_SET_BITMODE, ft232r_restore_bitmode,
330                         0, 0, 0, 1000) != 0) {
331                         LOG_ERROR("cannot set bitmode to restore serial port");
332                 }
333         }
334
335         if (jtag_libusb_release_interface(adapter, 0) != 0)
336                 LOG_ERROR("usb release interface failed");
337
338         jtag_libusb_close(adapter);
339
340         free(ft232r_output); /* free used memory */
341         ft232r_output = NULL; /* reset pointer to memory */
342         ft232r_buf_size = FT232R_BUF_SIZE_EXTRA; /* reset next initial buffer size */
343
344         return ERROR_OK;
345 }
346
347 static int ft232r_speed_div(int divisor, int *khz)
348 {
349         /* Maximum 3 Mbaud for bit bang mode. */
350         if (divisor == 0)
351                 *khz = 3000;
352         else if (divisor == 1)
353                 *khz = 2000;
354         else
355                 *khz = 3000 / divisor;
356         return ERROR_OK;
357 }
358
359 static int ft232r_khz(int khz, int *divisor)
360 {
361         if (khz == 0) {
362                 LOG_DEBUG("RCLK not supported");
363                 return ERROR_FAIL;
364         }
365
366         /* Calculate frequency divisor. */
367         if (khz > 2500)
368                 *divisor = 0;           /* Special case: 3 MHz */
369         else if (khz > 1700)
370                 *divisor = 1;           /* Special case: 2 MHz */
371         else {
372                 *divisor = (2*3000 / khz + 1) / 2;
373                 if (*divisor > 0x3FFF)
374                         *divisor = 0x3FFF;
375         }
376         return ERROR_OK;
377 }
378
379 static char *ft232r_bit_number_to_name(int bit)
380 {
381         if (bit >= 0 && bit < FT232R_BIT_COUNT)
382                 return ft232r_bit_name_array[bit];
383         return "?";
384 }
385
386 static int ft232r_bit_name_to_number(const char *name)
387 {
388         int i;
389         if (name[0] >= '0' && name[0] <= '9' && name[1] == '\0') {
390                 i = atoi(name);
391                 if (i >= 0 && i < FT232R_BIT_COUNT)
392                         return i;
393         }
394         for (i = 0; i < FT232R_BIT_COUNT; i++)
395                 if (strcasecmp(name, ft232r_bit_name_array[i]) == 0)
396                         return i;
397         return -1;
398 }
399
400 COMMAND_HANDLER(ft232r_handle_serial_desc_command)
401 {
402         if (CMD_ARGC == 1)
403                 ft232r_serial_desc = strdup(CMD_ARGV[0]);
404         else
405                 LOG_ERROR("require exactly one argument to "
406                                   "ft232r_serial_desc <serial>");
407         return ERROR_OK;
408 }
409
410 COMMAND_HANDLER(ft232r_handle_vid_pid_command)
411 {
412         if (CMD_ARGC > 2) {
413                 LOG_WARNING("ignoring extra IDs in ft232r_vid_pid "
414                                         "(maximum is 1 pair)");
415                 CMD_ARGC = 2;
416         }
417         if (CMD_ARGC == 2) {
418                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[0], ft232r_vid);
419                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], ft232r_pid);
420         } else
421                 LOG_WARNING("incomplete ft232r_vid_pid configuration");
422
423         return ERROR_OK;
424 }
425
426 COMMAND_HANDLER(ft232r_handle_jtag_nums_command)
427 {
428         if (CMD_ARGC == 4) {
429                 tck_gpio = ft232r_bit_name_to_number(CMD_ARGV[0]);
430                 tms_gpio = ft232r_bit_name_to_number(CMD_ARGV[1]);
431                 tdi_gpio = ft232r_bit_name_to_number(CMD_ARGV[2]);
432                 tdo_gpio = ft232r_bit_name_to_number(CMD_ARGV[3]);
433         } else if (CMD_ARGC != 0)
434                 return ERROR_COMMAND_SYNTAX_ERROR;
435
436         if (tck_gpio < 0)
437                 return ERROR_COMMAND_SYNTAX_ERROR;
438         if (tms_gpio < 0)
439                 return ERROR_COMMAND_SYNTAX_ERROR;
440         if (tdi_gpio < 0)
441                 return ERROR_COMMAND_SYNTAX_ERROR;
442         if (tdo_gpio < 0)
443                 return ERROR_COMMAND_SYNTAX_ERROR;
444
445         command_print(CMD,
446                         "FT232R nums: TCK = %d %s, TMS = %d %s, TDI = %d %s, TDO = %d %s",
447                         tck_gpio, ft232r_bit_number_to_name(tck_gpio),
448                         tms_gpio, ft232r_bit_number_to_name(tms_gpio),
449                         tdi_gpio, ft232r_bit_number_to_name(tdi_gpio),
450                         tdo_gpio, ft232r_bit_number_to_name(tdo_gpio));
451
452         return ERROR_OK;
453 }
454
455 COMMAND_HANDLER(ft232r_handle_tck_num_command)
456 {
457         if (CMD_ARGC == 1)
458                 tck_gpio = ft232r_bit_name_to_number(CMD_ARGV[0]);
459         else if (CMD_ARGC != 0)
460                 return ERROR_COMMAND_SYNTAX_ERROR;
461
462         if (tck_gpio < 0)
463                 return ERROR_COMMAND_SYNTAX_ERROR;
464
465         command_print(CMD,
466                         "FT232R num: TCK = %d %s", tck_gpio, ft232r_bit_number_to_name(tck_gpio));
467
468         return ERROR_OK;
469 }
470
471 COMMAND_HANDLER(ft232r_handle_tms_num_command)
472 {
473         if (CMD_ARGC == 1)
474                 tms_gpio = ft232r_bit_name_to_number(CMD_ARGV[0]);
475         else if (CMD_ARGC != 0)
476                 return ERROR_COMMAND_SYNTAX_ERROR;
477
478         if (tms_gpio < 0)
479                 return ERROR_COMMAND_SYNTAX_ERROR;
480
481         command_print(CMD,
482                         "FT232R num: TMS = %d %s", tms_gpio, ft232r_bit_number_to_name(tms_gpio));
483
484         return ERROR_OK;
485 }
486
487 COMMAND_HANDLER(ft232r_handle_tdo_num_command)
488 {
489         if (CMD_ARGC == 1)
490                 tdo_gpio = ft232r_bit_name_to_number(CMD_ARGV[0]);
491         else if (CMD_ARGC != 0)
492                 return ERROR_COMMAND_SYNTAX_ERROR;
493
494         if (tdo_gpio < 0)
495                 return ERROR_COMMAND_SYNTAX_ERROR;
496
497         command_print(CMD,
498                         "FT232R num: TDO = %d %s", tdo_gpio, ft232r_bit_number_to_name(tdo_gpio));
499
500         return ERROR_OK;
501 }
502
503 COMMAND_HANDLER(ft232r_handle_tdi_num_command)
504 {
505         if (CMD_ARGC == 1)
506                 tdi_gpio = ft232r_bit_name_to_number(CMD_ARGV[0]);
507         else if (CMD_ARGC != 0)
508                 return ERROR_COMMAND_SYNTAX_ERROR;
509
510         if (tdi_gpio < 0)
511                 return ERROR_COMMAND_SYNTAX_ERROR;
512
513         command_print(CMD,
514                         "FT232R num: TDI = %d %s", tdi_gpio, ft232r_bit_number_to_name(tdi_gpio));
515
516         return ERROR_OK;
517 }
518
519 COMMAND_HANDLER(ft232r_handle_trst_num_command)
520 {
521         if (CMD_ARGC == 1)
522                 ntrst_gpio = ft232r_bit_name_to_number(CMD_ARGV[0]);
523         else if (CMD_ARGC != 0)
524                 return ERROR_COMMAND_SYNTAX_ERROR;
525
526         if (ntrst_gpio < 0)
527                 return ERROR_COMMAND_SYNTAX_ERROR;
528
529         command_print(CMD,
530                         "FT232R num: TRST = %d %s", ntrst_gpio, ft232r_bit_number_to_name(ntrst_gpio));
531
532         return ERROR_OK;
533 }
534
535 COMMAND_HANDLER(ft232r_handle_srst_num_command)
536 {
537         if (CMD_ARGC == 1)
538                 nsysrst_gpio = ft232r_bit_name_to_number(CMD_ARGV[0]);
539         else if (CMD_ARGC != 0)
540                 return ERROR_COMMAND_SYNTAX_ERROR;
541
542         if (nsysrst_gpio < 0)
543                 return ERROR_COMMAND_SYNTAX_ERROR;
544
545         command_print(CMD,
546                         "FT232R num: SRST = %d %s", nsysrst_gpio, ft232r_bit_number_to_name(nsysrst_gpio));
547
548         return ERROR_OK;
549 }
550
551 COMMAND_HANDLER(ft232r_handle_restore_serial_command)
552 {
553         if (CMD_ARGC == 1)
554                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[0], ft232r_restore_bitmode);
555         else if (CMD_ARGC != 0)
556                 return ERROR_COMMAND_SYNTAX_ERROR;
557
558         command_print(CMD,
559                         "FT232R restore serial: 0x%04X (%s)",
560                         ft232r_restore_bitmode, ft232r_restore_bitmode == 0xFFFF ? "disabled" : "enabled");
561
562         return ERROR_OK;
563 }
564
565 static const struct command_registration ft232r_command_handlers[] = {
566         {
567                 .name = "ft232r_serial_desc",
568                 .handler = ft232r_handle_serial_desc_command,
569                 .mode = COMMAND_CONFIG,
570                 .help = "USB serial descriptor of the adapter",
571                 .usage = "serial string",
572         },
573         {
574                 .name = "ft232r_vid_pid",
575                 .handler = ft232r_handle_vid_pid_command,
576                 .mode = COMMAND_CONFIG,
577                 .help = "USB VID and PID of the adapter",
578                 .usage = "vid pid",
579         },
580         {
581                 .name = "ft232r_jtag_nums",
582                 .handler = ft232r_handle_jtag_nums_command,
583                 .mode = COMMAND_CONFIG,
584                 .help = "gpio numbers for tck, tms, tdi, tdo. (in that order)",
585                 .usage = "<0-7|TXD-RI> <0-7|TXD-RI> <0-7|TXD-RI> <0-7|TXD-RI>",
586         },
587         {
588                 .name = "ft232r_tck_num",
589                 .handler = ft232r_handle_tck_num_command,
590                 .mode = COMMAND_CONFIG,
591                 .help = "gpio number for tck.",
592                 .usage = "<0-7|TXD|RXD|RTS|CTS|DTR|DSR|DCD|RI>",
593         },
594         {
595                 .name = "ft232r_tms_num",
596                 .handler = ft232r_handle_tms_num_command,
597                 .mode = COMMAND_CONFIG,
598                 .help = "gpio number for tms.",
599                 .usage = "<0-7|TXD|RXD|RTS|CTS|DTR|DSR|DCD|RI>",
600         },
601         {
602                 .name = "ft232r_tdo_num",
603                 .handler = ft232r_handle_tdo_num_command,
604                 .mode = COMMAND_CONFIG,
605                 .help = "gpio number for tdo.",
606                 .usage = "<0-7|TXD|RXD|RTS|CTS|DTR|DSR|DCD|RI>",
607         },
608         {
609                 .name = "ft232r_tdi_num",
610                 .handler = ft232r_handle_tdi_num_command,
611                 .mode = COMMAND_CONFIG,
612                 .help = "gpio number for tdi.",
613                 .usage = "<0-7|TXD|RXD|RTS|CTS|DTR|DSR|DCD|RI>",
614         },
615         {
616                 .name = "ft232r_srst_num",
617                 .handler = ft232r_handle_srst_num_command,
618                 .mode = COMMAND_CONFIG,
619                 .help = "gpio number for srst.",
620                 .usage = "<0-7|TXD|RXD|RTS|CTS|DTR|DSR|DCD|RI>",
621         },
622         {
623                 .name = "ft232r_trst_num",
624                 .handler = ft232r_handle_trst_num_command,
625                 .mode = COMMAND_CONFIG,
626                 .help = "gpio number for trst.",
627                 .usage = "<0-7|TXD|RXD|RTS|CTS|DTR|DSR|DCD|RI>",
628         },
629         {
630                 .name = "ft232r_restore_serial",
631                 .handler = ft232r_handle_restore_serial_command,
632                 .mode = COMMAND_CONFIG,
633                 .help = "bitmode control word that restores serial port.",
634                 .usage = "bitmode_control_word",
635         },
636         COMMAND_REGISTRATION_DONE
637 };
638
639 /*
640  * Synchronous bitbang protocol implementation.
641  */
642
643 static void syncbb_end_state(tap_state_t state)
644 {
645         if (tap_is_state_stable(state))
646                 tap_set_end_state(state);
647         else {
648                 LOG_ERROR("BUG: %i is not a valid end state", state);
649                 exit(-1);
650         }
651 }
652
653 static void syncbb_state_move(int skip)
654 {
655         int i = 0, tms = 0;
656         uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
657         int tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
658
659         for (i = skip; i < tms_count; i++) {
660                 tms = (tms_scan >> i) & 1;
661                 ft232r_write(0, tms, 0);
662                 ft232r_write(1, tms, 0);
663         }
664         ft232r_write(0, tms, 0);
665
666         tap_set_state(tap_get_end_state());
667 }
668
669 /**
670  * Clock a bunch of TMS (or SWDIO) transitions, to change the JTAG
671  * (or SWD) state machine.
672  */
673 static int syncbb_execute_tms(struct jtag_command *cmd)
674 {
675         unsigned num_bits = cmd->cmd.tms->num_bits;
676         const uint8_t *bits = cmd->cmd.tms->bits;
677
678         DEBUG_JTAG_IO("TMS: %d bits", num_bits);
679
680         int tms = 0;
681         for (unsigned i = 0; i < num_bits; i++) {
682                 tms = ((bits[i/8] >> (i % 8)) & 1);
683                 ft232r_write(0, tms, 0);
684                 ft232r_write(1, tms, 0);
685         }
686         ft232r_write(0, tms, 0);
687
688         return ERROR_OK;
689 }
690
691 static void syncbb_path_move(struct pathmove_command *cmd)
692 {
693         int num_states = cmd->num_states;
694         int state_count;
695         int tms = 0;
696
697         state_count = 0;
698         while (num_states) {
699                 if (tap_state_transition(tap_get_state(), false) == cmd->path[state_count]) {
700                         tms = 0;
701                 } else if (tap_state_transition(tap_get_state(), true) == cmd->path[state_count]) {
702                         tms = 1;
703                 } else {
704                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
705                                 tap_state_name(tap_get_state()),
706                                 tap_state_name(cmd->path[state_count]));
707                         exit(-1);
708                 }
709
710                 ft232r_write(0, tms, 0);
711                 ft232r_write(1, tms, 0);
712
713                 tap_set_state(cmd->path[state_count]);
714                 state_count++;
715                 num_states--;
716         }
717
718         ft232r_write(0, tms, 0);
719
720         tap_set_end_state(tap_get_state());
721 }
722
723 static void syncbb_runtest(int num_cycles)
724 {
725         int i;
726
727         tap_state_t saved_end_state = tap_get_end_state();
728
729         /* only do a state_move when we're not already in IDLE */
730         if (tap_get_state() != TAP_IDLE) {
731                 syncbb_end_state(TAP_IDLE);
732                 syncbb_state_move(0);
733         }
734
735         /* execute num_cycles */
736         for (i = 0; i < num_cycles; i++) {
737                 ft232r_write(0, 0, 0);
738                 ft232r_write(1, 0, 0);
739         }
740         ft232r_write(0, 0, 0);
741
742         /* finish in end_state */
743         syncbb_end_state(saved_end_state);
744         if (tap_get_state() != tap_get_end_state())
745                 syncbb_state_move(0);
746 }
747
748 /**
749  * Function syncbb_stableclocks
750  * issues a number of clock cycles while staying in a stable state.
751  * Because the TMS value required to stay in the RESET state is a 1, whereas
752  * the TMS value required to stay in any of the other stable states is a 0,
753  * this function checks the current stable state to decide on the value of TMS
754  * to use.
755  */
756 static void syncbb_stableclocks(int num_cycles)
757 {
758         int tms = (tap_get_state() == TAP_RESET ? 1 : 0);
759         int i;
760
761         /* send num_cycles clocks onto the cable */
762         for (i = 0; i < num_cycles; i++) {
763                 ft232r_write(1, tms, 0);
764                 ft232r_write(0, tms, 0);
765         }
766 }
767
768 static void syncbb_scan(bool ir_scan, enum scan_type type, uint8_t *buffer, int scan_size)
769 {
770         tap_state_t saved_end_state = tap_get_end_state();
771         int bit_cnt, bit0_index;
772
773         if (!((!ir_scan && (tap_get_state() == TAP_DRSHIFT)) || (ir_scan && (tap_get_state() == TAP_IRSHIFT)))) {
774                 if (ir_scan)
775                         syncbb_end_state(TAP_IRSHIFT);
776                 else
777                         syncbb_end_state(TAP_DRSHIFT);
778
779                 syncbb_state_move(0);
780                 syncbb_end_state(saved_end_state);
781         }
782
783         bit0_index = ft232r_output_len;
784         for (bit_cnt = 0; bit_cnt < scan_size; bit_cnt++) {
785                 int tms = (bit_cnt == scan_size-1) ? 1 : 0;
786                 int tdi;
787                 int bytec = bit_cnt/8;
788                 int bcval = 1 << (bit_cnt % 8);
789
790                 /* if we're just reading the scan, but don't care about the output
791                  * default to outputting 'low', this also makes valgrind traces more readable,
792                  * as it removes the dependency on an uninitialised value
793                  */
794                 tdi = 0;
795                 if ((type != SCAN_IN) && (buffer[bytec] & bcval))
796                         tdi = 1;
797
798                 ft232r_write(0, tms, tdi);
799                 ft232r_write(1, tms, tdi);
800         }
801
802         if (tap_get_state() != tap_get_end_state()) {
803                 /* we *KNOW* the above loop transitioned out of
804                  * the shift state, so we skip the first state
805                  * and move directly to the end state.
806                  */
807                 syncbb_state_move(1);
808         }
809         ft232r_send_recv();
810
811         if (type != SCAN_OUT)
812                 for (bit_cnt = 0; bit_cnt < scan_size; bit_cnt++) {
813                         int bytec = bit_cnt/8;
814                         int bcval = 1 << (bit_cnt % 8);
815                         int val = ft232r_output[bit0_index + bit_cnt*2 + 1];
816
817                         if (val & (1<<tdo_gpio))
818                                 buffer[bytec] |= bcval;
819                         else
820                                 buffer[bytec] &= ~bcval;
821                 }
822 }
823
824 static int syncbb_execute_queue(void)
825 {
826         struct jtag_command *cmd = jtag_command_queue; /* currently processed command */
827         int scan_size;
828         enum scan_type type;
829         uint8_t *buffer;
830         int retval;
831
832         /* return ERROR_OK, unless a jtag_read_buffer returns a failed check
833          * that wasn't handled by a caller-provided error handler
834          */
835         retval = ERROR_OK;
836
837 /*      ft232r_blink(1);*/
838
839         while (cmd) {
840                 switch (cmd->type) {
841                         case JTAG_RESET:
842                                 LOG_DEBUG_IO("reset trst: %i srst %i", cmd->cmd.reset->trst, cmd->cmd.reset->srst);
843
844                                 if ((cmd->cmd.reset->trst == 1) ||
845                                         (cmd->cmd.reset->srst &&
846                                         (jtag_get_reset_config() & RESET_SRST_PULLS_TRST))) {
847                                         tap_set_state(TAP_RESET);
848                                 }
849                                 ft232r_reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
850                                 break;
851
852                         case JTAG_RUNTEST:
853                                 LOG_DEBUG_IO("runtest %i cycles, end in %s", cmd->cmd.runtest->num_cycles,
854                                         tap_state_name(cmd->cmd.runtest->end_state));
855
856                                 syncbb_end_state(cmd->cmd.runtest->end_state);
857                                 syncbb_runtest(cmd->cmd.runtest->num_cycles);
858                                 break;
859
860                         case JTAG_STABLECLOCKS:
861                                 /* this is only allowed while in a stable state.  A check for a stable
862                                  * state was done in jtag_add_clocks()
863                                  */
864                                 syncbb_stableclocks(cmd->cmd.stableclocks->num_cycles);
865                                 break;
866
867                         case JTAG_TLR_RESET: /* renamed from JTAG_STATEMOVE */
868                                 LOG_DEBUG_IO("statemove end in %s", tap_state_name(cmd->cmd.statemove->end_state));
869
870                                 syncbb_end_state(cmd->cmd.statemove->end_state);
871                                 syncbb_state_move(0);
872                                 break;
873
874                         case JTAG_PATHMOVE:
875                                 LOG_DEBUG_IO("pathmove: %i states, end in %s", cmd->cmd.pathmove->num_states,
876                                         tap_state_name(cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]));
877
878                                 syncbb_path_move(cmd->cmd.pathmove);
879                                 break;
880
881                         case JTAG_SCAN:
882                                 LOG_DEBUG_IO("%s scan end in %s",  (cmd->cmd.scan->ir_scan) ? "IR" : "DR",
883                                         tap_state_name(cmd->cmd.scan->end_state));
884
885                                 syncbb_end_state(cmd->cmd.scan->end_state);
886                                 scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
887                                 type = jtag_scan_type(cmd->cmd.scan);
888                                 syncbb_scan(cmd->cmd.scan->ir_scan, type, buffer, scan_size);
889                                 if (jtag_read_buffer(buffer, cmd->cmd.scan) != ERROR_OK)
890                                         retval = ERROR_JTAG_QUEUE_FAILED;
891                                 if (buffer)
892                                         free(buffer);
893                                 break;
894
895                         case JTAG_SLEEP:
896                                 LOG_DEBUG_IO("sleep %" PRIi32, cmd->cmd.sleep->us);
897
898                                 jtag_sleep(cmd->cmd.sleep->us);
899                                 break;
900
901                         case JTAG_TMS:
902                                 retval = syncbb_execute_tms(cmd);
903                                 break;
904                         default:
905                                 LOG_ERROR("BUG: unknown JTAG command type encountered");
906                                 exit(-1);
907                 }
908                 if (ft232r_output_len > 0)
909                         ft232r_send_recv();
910                 cmd = cmd->next;
911         }
912 /*      ft232r_blink(0);*/
913
914         return retval;
915 }
916
917 struct jtag_interface ft232r_interface = {
918         .name = "ft232r",
919         .commands = ft232r_command_handlers,
920         .transports = jtag_only,
921         .supported = DEBUG_CAP_TMS_SEQ,
922
923         .execute_queue = syncbb_execute_queue,
924
925         .speed = ft232r_speed,
926         .init = ft232r_init,
927         .quit = ft232r_quit,
928         .speed_div = ft232r_speed_div,
929         .khz = ft232r_khz,
930 };