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