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