]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/mpsse.c
ftdi: extend ftdi_location format
[openocd] / src / jtag / drivers / mpsse.c
1 /**************************************************************************
2  *   Copyright (C) 2012 by Andreas Fritiofson                              *
3  *   andreas.fritiofson@gmail.com                                          *
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 #include "mpsse.h"
24 #include "helper/log.h"
25 #include <libusb.h>
26
27 /* Compatibility define for older libusb-1.0 */
28 #ifndef LIBUSB_CALL
29 #define LIBUSB_CALL
30 #endif
31
32 #ifdef _DEBUG_JTAG_IO_
33 #define DEBUG_IO(expr...) LOG_DEBUG(expr)
34 #define DEBUG_PRINT_BUF(buf, len) \
35         do { \
36                 char buf_string[32 * 3 + 1]; \
37                 int buf_string_pos = 0; \
38                 for (int i = 0; i < len; i++) { \
39                         buf_string_pos += sprintf(buf_string + buf_string_pos, " %02x", buf[i]); \
40                         if (i % 32 == 32 - 1) { \
41                                 LOG_DEBUG("%s", buf_string); \
42                                 buf_string_pos = 0; \
43                         } \
44                 } \
45                 if (buf_string_pos > 0) \
46                         LOG_DEBUG("%s", buf_string);\
47         } while (0)
48 #else
49 #define DEBUG_IO(expr...) do {} while (0)
50 #define DEBUG_PRINT_BUF(buf, len) do {} while (0)
51 #endif
52
53 #define FTDI_DEVICE_OUT_REQTYPE (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE)
54 #define FTDI_DEVICE_IN_REQTYPE (0x80 | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE)
55
56 #define BITMODE_MPSSE 0x02
57
58 #define SIO_RESET_REQUEST             0x00
59 #define SIO_SET_LATENCY_TIMER_REQUEST 0x09
60 #define SIO_GET_LATENCY_TIMER_REQUEST 0x0A
61 #define SIO_SET_BITMODE_REQUEST       0x0B
62
63 #define SIO_RESET_SIO 0
64 #define SIO_RESET_PURGE_RX 1
65 #define SIO_RESET_PURGE_TX 2
66
67 struct mpsse_ctx {
68         libusb_context *usb_ctx;
69         libusb_device_handle *usb_dev;
70         unsigned int usb_write_timeout;
71         unsigned int usb_read_timeout;
72         uint8_t in_ep;
73         uint8_t out_ep;
74         uint16_t max_packet_size;
75         uint16_t index;
76         uint8_t interface;
77         enum ftdi_chip_type type;
78         uint8_t *write_buffer;
79         unsigned write_size;
80         unsigned write_count;
81         uint8_t *read_buffer;
82         unsigned read_size;
83         unsigned read_count;
84         uint8_t *read_chunk;
85         unsigned read_chunk_size;
86         struct bit_copy_queue read_queue;
87         int retval;
88 };
89
90 /* Returns true if the string descriptor indexed by str_index in device matches string */
91 static bool string_descriptor_equal(libusb_device_handle *device, uint8_t str_index,
92         const char *string)
93 {
94         int retval;
95         char desc_string[256]; /* Max size of string descriptor */
96         retval = libusb_get_string_descriptor_ascii(device, str_index, (unsigned char *)desc_string,
97                         sizeof(desc_string));
98         if (retval < 0) {
99                 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %s", libusb_error_name(retval));
100                 return false;
101         }
102         return strncmp(string, desc_string, sizeof(desc_string)) == 0;
103 }
104
105 static bool device_location_equal(libusb_device *device, const char *location)
106 {
107         bool result = false;
108 #ifdef HAVE_LIBUSB_GET_PORT_NUMBERS
109         char *loc = strdup(location);
110         uint8_t port_path[7];
111         int path_step, path_len;
112         uint8_t dev_bus = libusb_get_bus_number(device);
113         char *ptr;
114
115         path_len = libusb_get_port_numbers(device, port_path, 7);
116         if (path_len == LIBUSB_ERROR_OVERFLOW) {
117                 LOG_ERROR("cannot determine path to usb device! (more than 7 ports in path)");
118                 goto done;
119         }
120
121         LOG_DEBUG("device path has %i steps", path_len);
122
123         ptr = strtok(loc, "-:");
124         if (ptr == NULL) {
125                 LOG_DEBUG("no ':' in path");
126                 goto done;
127         }
128         if (atoi(ptr) != dev_bus) {
129                 LOG_DEBUG("bus mismatch");
130                 goto done;
131         }
132
133         path_step = 0;
134         while (path_step < 7) {
135                 ptr = strtok(NULL, ".,");
136                 if (ptr == NULL) {
137                         LOG_DEBUG("no more tokens in path at step %i", path_step);
138                         break;
139                 }
140
141                 if (path_step < path_len
142                         && atoi(ptr) != port_path[path_step]) {
143                         LOG_DEBUG("path mismatch at step %i", path_step);
144                         break;
145                 }
146
147                 path_step++;
148         };
149
150         /* walked the full path, all elements match */
151         if (path_step == path_len)
152                 result = true;
153
154  done:
155         free(loc);
156 #endif
157         return result;
158 }
159
160 /* Helper to open a libusb device that matches vid, pid, product string and/or serial string.
161  * Set any field to 0 as a wildcard. If the device is found true is returned, with ctx containing
162  * the already opened handle. ctx->interface must be set to the desired interface (channel) number
163  * prior to calling this function. */
164 static bool open_matching_device(struct mpsse_ctx *ctx, const uint16_t *vid, const uint16_t *pid,
165         const char *product, const char *serial, const char *location)
166 {
167         libusb_device **list;
168         struct libusb_device_descriptor desc;
169         struct libusb_config_descriptor *config0;
170         int err;
171         bool found = false;
172         ssize_t cnt = libusb_get_device_list(ctx->usb_ctx, &list);
173         if (cnt < 0)
174                 LOG_ERROR("libusb_get_device_list() failed with %s", libusb_error_name(cnt));
175
176         for (ssize_t i = 0; i < cnt; i++) {
177                 libusb_device *device = list[i];
178
179                 err = libusb_get_device_descriptor(device, &desc);
180                 if (err != LIBUSB_SUCCESS) {
181                         LOG_ERROR("libusb_get_device_descriptor() failed with %s", libusb_error_name(err));
182                         continue;
183                 }
184
185                 if (vid && *vid != desc.idVendor)
186                         continue;
187                 if (pid && *pid != desc.idProduct)
188                         continue;
189
190                 err = libusb_open(device, &ctx->usb_dev);
191                 if (err != LIBUSB_SUCCESS) {
192                         LOG_ERROR("libusb_open() failed with %s",
193                                   libusb_error_name(err));
194                         continue;
195                 }
196
197                 if (location && !device_location_equal(device, location)) {
198                         libusb_close(ctx->usb_dev);
199                         continue;
200                 }
201
202                 if (product && !string_descriptor_equal(ctx->usb_dev, desc.iProduct, product)) {
203                         libusb_close(ctx->usb_dev);
204                         continue;
205                 }
206
207                 if (serial && !string_descriptor_equal(ctx->usb_dev, desc.iSerialNumber, serial)) {
208                         libusb_close(ctx->usb_dev);
209                         continue;
210                 }
211
212                 found = true;
213                 break;
214         }
215
216         libusb_free_device_list(list, 1);
217
218         if (!found) {
219                 LOG_ERROR("no device found");
220                 return false;
221         }
222
223         err = libusb_get_config_descriptor(libusb_get_device(ctx->usb_dev), 0, &config0);
224         if (err != LIBUSB_SUCCESS) {
225                 LOG_ERROR("libusb_get_config_descriptor() failed with %s", libusb_error_name(err));
226                 libusb_close(ctx->usb_dev);
227                 return false;
228         }
229
230         /* Make sure the first configuration is selected */
231         int cfg;
232         err = libusb_get_configuration(ctx->usb_dev, &cfg);
233         if (err != LIBUSB_SUCCESS) {
234                 LOG_ERROR("libusb_get_configuration() failed with %s", libusb_error_name(err));
235                 goto error;
236         }
237
238         if (desc.bNumConfigurations > 0 && cfg != config0->bConfigurationValue) {
239                 err = libusb_set_configuration(ctx->usb_dev, config0->bConfigurationValue);
240                 if (err != LIBUSB_SUCCESS) {
241                         LOG_ERROR("libusb_set_configuration() failed with %s", libusb_error_name(err));
242                         goto error;
243                 }
244         }
245
246         /* Try to detach ftdi_sio kernel module */
247         err = libusb_detach_kernel_driver(ctx->usb_dev, ctx->interface);
248         if (err != LIBUSB_SUCCESS && err != LIBUSB_ERROR_NOT_FOUND
249                         && err != LIBUSB_ERROR_NOT_SUPPORTED) {
250                 LOG_WARNING("libusb_detach_kernel_driver() failed with %s, trying to continue anyway",
251                         libusb_error_name(err));
252         }
253
254         err = libusb_claim_interface(ctx->usb_dev, ctx->interface);
255         if (err != LIBUSB_SUCCESS) {
256                 LOG_ERROR("libusb_claim_interface() failed with %s", libusb_error_name(err));
257                 goto error;
258         }
259
260         /* Reset FTDI device */
261         err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
262                         SIO_RESET_REQUEST, SIO_RESET_SIO,
263                         ctx->index, NULL, 0, ctx->usb_write_timeout);
264         if (err < 0) {
265                 LOG_ERROR("failed to reset FTDI device: %s", libusb_error_name(err));
266                 goto error;
267         }
268
269         switch (desc.bcdDevice) {
270         case 0x500:
271                 ctx->type = TYPE_FT2232C;
272                 break;
273         case 0x700:
274                 ctx->type = TYPE_FT2232H;
275                 break;
276         case 0x800:
277                 ctx->type = TYPE_FT4232H;
278                 break;
279         case 0x900:
280                 ctx->type = TYPE_FT232H;
281                 break;
282         default:
283                 LOG_ERROR("unsupported FTDI chip type: 0x%04x", desc.bcdDevice);
284                 goto error;
285         }
286
287         /* Determine maximum packet size and endpoint addresses */
288         if (!(desc.bNumConfigurations > 0 && ctx->interface < config0->bNumInterfaces
289                         && config0->interface[ctx->interface].num_altsetting > 0))
290                 goto desc_error;
291
292         const struct libusb_interface_descriptor *descriptor;
293         descriptor = &config0->interface[ctx->interface].altsetting[0];
294         if (descriptor->bNumEndpoints != 2)
295                 goto desc_error;
296
297         ctx->in_ep = 0;
298         ctx->out_ep = 0;
299         for (int i = 0; i < descriptor->bNumEndpoints; i++) {
300                 if (descriptor->endpoint[i].bEndpointAddress & 0x80) {
301                         ctx->in_ep = descriptor->endpoint[i].bEndpointAddress;
302                         ctx->max_packet_size =
303                                         descriptor->endpoint[i].wMaxPacketSize;
304                 } else {
305                         ctx->out_ep = descriptor->endpoint[i].bEndpointAddress;
306                 }
307         }
308
309         if (ctx->in_ep == 0 || ctx->out_ep == 0)
310                 goto desc_error;
311
312         libusb_free_config_descriptor(config0);
313         return true;
314
315 desc_error:
316         LOG_ERROR("unrecognized USB device descriptor");
317 error:
318         libusb_free_config_descriptor(config0);
319         libusb_close(ctx->usb_dev);
320         return false;
321 }
322
323 struct mpsse_ctx *mpsse_open(const uint16_t *vid, const uint16_t *pid, const char *description,
324         const char *serial, const char *location, int channel)
325 {
326         struct mpsse_ctx *ctx = calloc(1, sizeof(*ctx));
327         int err;
328
329         if (!ctx)
330                 return 0;
331
332         bit_copy_queue_init(&ctx->read_queue);
333         ctx->read_chunk_size = 16384;
334         ctx->read_size = 16384;
335         ctx->write_size = 16384;
336         ctx->read_chunk = malloc(ctx->read_chunk_size);
337         ctx->read_buffer = malloc(ctx->read_size);
338
339         /* Use calloc to make valgrind happy: buffer_write() sets payload
340          * on bit basis, so some bits can be left uninitialized in write_buffer.
341          * Although this is perfectly ok with MPSSE, valgrind reports
342          * Syscall param ioctl(USBDEVFS_SUBMITURB).buffer points to uninitialised byte(s) */
343         ctx->write_buffer = calloc(1, ctx->write_size);
344
345         if (!ctx->read_chunk || !ctx->read_buffer || !ctx->write_buffer)
346                 goto error;
347
348         ctx->interface = channel;
349         ctx->index = channel + 1;
350         ctx->usb_read_timeout = 5000;
351         ctx->usb_write_timeout = 5000;
352
353         err = libusb_init(&ctx->usb_ctx);
354         if (err != LIBUSB_SUCCESS) {
355                 LOG_ERROR("libusb_init() failed with %s", libusb_error_name(err));
356                 goto error;
357         }
358
359         if (!open_matching_device(ctx, vid, pid, description, serial, location)) {
360                 /* Four hex digits plus terminating zero each */
361                 char vidstr[5];
362                 char pidstr[5];
363                 LOG_ERROR("unable to open ftdi device with vid %s, pid %s, description '%s', "
364                                 "serial '%s' at bus location '%s'",
365                                 vid ? sprintf(vidstr, "%04x", *vid), vidstr : "*",
366                                 pid ? sprintf(pidstr, "%04x", *pid), pidstr : "*",
367                                 description ? description : "*",
368                                 serial ? serial : "*",
369                                 location ? location : "*");
370                 ctx->usb_dev = 0;
371                 goto error;
372         }
373
374         err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
375                         SIO_SET_LATENCY_TIMER_REQUEST, 255, ctx->index, NULL, 0,
376                         ctx->usb_write_timeout);
377         if (err < 0) {
378                 LOG_ERROR("unable to set latency timer: %s", libusb_error_name(err));
379                 goto error;
380         }
381
382         err = libusb_control_transfer(ctx->usb_dev,
383                         FTDI_DEVICE_OUT_REQTYPE,
384                         SIO_SET_BITMODE_REQUEST,
385                         0x0b | (BITMODE_MPSSE << 8),
386                         ctx->index,
387                         NULL,
388                         0,
389                         ctx->usb_write_timeout);
390         if (err < 0) {
391                 LOG_ERROR("unable to set MPSSE bitmode: %s", libusb_error_name(err));
392                 goto error;
393         }
394
395         mpsse_purge(ctx);
396
397         return ctx;
398 error:
399         mpsse_close(ctx);
400         return 0;
401 }
402
403 void mpsse_close(struct mpsse_ctx *ctx)
404 {
405         if (ctx->usb_dev)
406                 libusb_close(ctx->usb_dev);
407         if (ctx->usb_ctx)
408                 libusb_exit(ctx->usb_ctx);
409         bit_copy_discard(&ctx->read_queue);
410         if (ctx->write_buffer)
411                 free(ctx->write_buffer);
412         if (ctx->read_buffer)
413                 free(ctx->read_buffer);
414         if (ctx->read_chunk)
415                 free(ctx->read_chunk);
416
417         free(ctx);
418 }
419
420 bool mpsse_is_high_speed(struct mpsse_ctx *ctx)
421 {
422         return ctx->type != TYPE_FT2232C;
423 }
424
425 void mpsse_purge(struct mpsse_ctx *ctx)
426 {
427         int err;
428         LOG_DEBUG("-");
429         ctx->write_count = 0;
430         ctx->read_count = 0;
431         ctx->retval = ERROR_OK;
432         bit_copy_discard(&ctx->read_queue);
433         err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
434                         SIO_RESET_PURGE_RX, ctx->index, NULL, 0, ctx->usb_write_timeout);
435         if (err < 0) {
436                 LOG_ERROR("unable to purge ftdi rx buffers: %s", libusb_error_name(err));
437                 return;
438         }
439
440         err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
441                         SIO_RESET_PURGE_TX, ctx->index, NULL, 0, ctx->usb_write_timeout);
442         if (err < 0) {
443                 LOG_ERROR("unable to purge ftdi tx buffers: %s", libusb_error_name(err));
444                 return;
445         }
446 }
447
448 static unsigned buffer_write_space(struct mpsse_ctx *ctx)
449 {
450         /* Reserve one byte for SEND_IMMEDIATE */
451         return ctx->write_size - ctx->write_count - 1;
452 }
453
454 static unsigned buffer_read_space(struct mpsse_ctx *ctx)
455 {
456         return ctx->read_size - ctx->read_count;
457 }
458
459 static void buffer_write_byte(struct mpsse_ctx *ctx, uint8_t data)
460 {
461         DEBUG_IO("%02x", data);
462         assert(ctx->write_count < ctx->write_size);
463         ctx->write_buffer[ctx->write_count++] = data;
464 }
465
466 static unsigned buffer_write(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
467         unsigned bit_count)
468 {
469         DEBUG_IO("%d bits", bit_count);
470         assert(ctx->write_count + DIV_ROUND_UP(bit_count, 8) <= ctx->write_size);
471         bit_copy(ctx->write_buffer + ctx->write_count, 0, out, out_offset, bit_count);
472         ctx->write_count += DIV_ROUND_UP(bit_count, 8);
473         return bit_count;
474 }
475
476 static unsigned buffer_add_read(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset,
477         unsigned bit_count, unsigned offset)
478 {
479         DEBUG_IO("%d bits, offset %d", bit_count, offset);
480         assert(ctx->read_count + DIV_ROUND_UP(bit_count, 8) <= ctx->read_size);
481         bit_copy_queued(&ctx->read_queue, in, in_offset, ctx->read_buffer + ctx->read_count, offset,
482                 bit_count);
483         ctx->read_count += DIV_ROUND_UP(bit_count, 8);
484         return bit_count;
485 }
486
487 void mpsse_clock_data_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
488         unsigned length, uint8_t mode)
489 {
490         mpsse_clock_data(ctx, out, out_offset, 0, 0, length, mode);
491 }
492
493 void mpsse_clock_data_in(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset, unsigned length,
494         uint8_t mode)
495 {
496         mpsse_clock_data(ctx, 0, 0, in, in_offset, length, mode);
497 }
498
499 void mpsse_clock_data(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset, uint8_t *in,
500         unsigned in_offset, unsigned length, uint8_t mode)
501 {
502         /* TODO: Fix MSB first modes */
503         DEBUG_IO("%s%s %d bits", in ? "in" : "", out ? "out" : "", length);
504
505         if (ctx->retval != ERROR_OK) {
506                 DEBUG_IO("Ignoring command due to previous error");
507                 return;
508         }
509
510         /* TODO: On H chips, use command 0x8E/0x8F if in and out are both 0 */
511         if (out || (!out && !in))
512                 mode |= 0x10;
513         if (in)
514                 mode |= 0x20;
515
516         while (length > 0) {
517                 /* Guarantee buffer space enough for a minimum size transfer */
518                 if (buffer_write_space(ctx) + (length < 8) < (out || (!out && !in) ? 4 : 3)
519                                 || (in && buffer_read_space(ctx) < 1))
520                         ctx->retval = mpsse_flush(ctx);
521
522                 if (length < 8) {
523                         /* Transfer remaining bits in bit mode */
524                         buffer_write_byte(ctx, 0x02 | mode);
525                         buffer_write_byte(ctx, length - 1);
526                         if (out)
527                                 out_offset += buffer_write(ctx, out, out_offset, length);
528                         if (in)
529                                 in_offset += buffer_add_read(ctx, in, in_offset, length, 8 - length);
530                         if (!out && !in)
531                                 buffer_write_byte(ctx, 0x00);
532                         length = 0;
533                 } else {
534                         /* Byte transfer */
535                         unsigned this_bytes = length / 8;
536                         /* MPSSE command limit */
537                         if (this_bytes > 65536)
538                                 this_bytes = 65536;
539                         /* Buffer space limit. We already made sure there's space for the minimum
540                          * transfer. */
541                         if ((out || (!out && !in)) && this_bytes + 3 > buffer_write_space(ctx))
542                                 this_bytes = buffer_write_space(ctx) - 3;
543                         if (in && this_bytes > buffer_read_space(ctx))
544                                 this_bytes = buffer_read_space(ctx);
545
546                         if (this_bytes > 0) {
547                                 buffer_write_byte(ctx, mode);
548                                 buffer_write_byte(ctx, (this_bytes - 1) & 0xff);
549                                 buffer_write_byte(ctx, (this_bytes - 1) >> 8);
550                                 if (out)
551                                         out_offset += buffer_write(ctx,
552                                                         out,
553                                                         out_offset,
554                                                         this_bytes * 8);
555                                 if (in)
556                                         in_offset += buffer_add_read(ctx,
557                                                         in,
558                                                         in_offset,
559                                                         this_bytes * 8,
560                                                         0);
561                                 if (!out && !in)
562                                         for (unsigned n = 0; n < this_bytes; n++)
563                                                 buffer_write_byte(ctx, 0x00);
564                                 length -= this_bytes * 8;
565                         }
566                 }
567         }
568 }
569
570 void mpsse_clock_tms_cs_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
571         unsigned length, bool tdi, uint8_t mode)
572 {
573         mpsse_clock_tms_cs(ctx, out, out_offset, 0, 0, length, tdi, mode);
574 }
575
576 void mpsse_clock_tms_cs(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset, uint8_t *in,
577         unsigned in_offset, unsigned length, bool tdi, uint8_t mode)
578 {
579         DEBUG_IO("%sout %d bits, tdi=%d", in ? "in" : "", length, tdi);
580         assert(out);
581
582         if (ctx->retval != ERROR_OK) {
583                 DEBUG_IO("Ignoring command due to previous error");
584                 return;
585         }
586
587         mode |= 0x42;
588         if (in)
589                 mode |= 0x20;
590
591         while (length > 0) {
592                 /* Guarantee buffer space enough for a minimum size transfer */
593                 if (buffer_write_space(ctx) < 3 || (in && buffer_read_space(ctx) < 1))
594                         ctx->retval = mpsse_flush(ctx);
595
596                 /* Byte transfer */
597                 unsigned this_bits = length;
598                 /* MPSSE command limit */
599                 /* NOTE: there's a report of an FT2232 bug in this area, where shifting
600                  * exactly 7 bits can make problems with TMS signaling for the last
601                  * clock cycle:
602                  *
603                  * http://developer.intra2net.com/mailarchive/html/libftdi/2009/msg00292.html
604                  */
605                 if (this_bits > 7)
606                         this_bits = 7;
607
608                 if (this_bits > 0) {
609                         buffer_write_byte(ctx, mode);
610                         buffer_write_byte(ctx, this_bits - 1);
611                         uint8_t data = 0;
612                         /* TODO: Fix MSB first, if allowed in MPSSE */
613                         bit_copy(&data, 0, out, out_offset, this_bits);
614                         out_offset += this_bits;
615                         buffer_write_byte(ctx, data | (tdi ? 0x80 : 0x00));
616                         if (in)
617                                 in_offset += buffer_add_read(ctx,
618                                                 in,
619                                                 in_offset,
620                                                 this_bits,
621                                                 8 - this_bits);
622                         length -= this_bits;
623                 }
624         }
625 }
626
627 void mpsse_set_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
628 {
629         DEBUG_IO("-");
630
631         if (ctx->retval != ERROR_OK) {
632                 DEBUG_IO("Ignoring command due to previous error");
633                 return;
634         }
635
636         if (buffer_write_space(ctx) < 3)
637                 ctx->retval = mpsse_flush(ctx);
638
639         buffer_write_byte(ctx, 0x80);
640         buffer_write_byte(ctx, data);
641         buffer_write_byte(ctx, dir);
642 }
643
644 void mpsse_set_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
645 {
646         DEBUG_IO("-");
647
648         if (ctx->retval != ERROR_OK) {
649                 DEBUG_IO("Ignoring command due to previous error");
650                 return;
651         }
652
653         if (buffer_write_space(ctx) < 3)
654                 ctx->retval = mpsse_flush(ctx);
655
656         buffer_write_byte(ctx, 0x82);
657         buffer_write_byte(ctx, data);
658         buffer_write_byte(ctx, dir);
659 }
660
661 void mpsse_read_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t *data)
662 {
663         DEBUG_IO("-");
664
665         if (ctx->retval != ERROR_OK) {
666                 DEBUG_IO("Ignoring command due to previous error");
667                 return;
668         }
669
670         if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
671                 ctx->retval = mpsse_flush(ctx);
672
673         buffer_write_byte(ctx, 0x81);
674         buffer_add_read(ctx, data, 0, 8, 0);
675 }
676
677 void mpsse_read_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t *data)
678 {
679         DEBUG_IO("-");
680
681         if (ctx->retval != ERROR_OK) {
682                 DEBUG_IO("Ignoring command due to previous error");
683                 return;
684         }
685
686         if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
687                 ctx->retval = mpsse_flush(ctx);
688
689         buffer_write_byte(ctx, 0x83);
690         buffer_add_read(ctx, data, 0, 8, 0);
691 }
692
693 static void single_byte_boolean_helper(struct mpsse_ctx *ctx, bool var, uint8_t val_if_true,
694         uint8_t val_if_false)
695 {
696         if (ctx->retval != ERROR_OK) {
697                 DEBUG_IO("Ignoring command due to previous error");
698                 return;
699         }
700
701         if (buffer_write_space(ctx) < 1)
702                 ctx->retval = mpsse_flush(ctx);
703
704         buffer_write_byte(ctx, var ? val_if_true : val_if_false);
705 }
706
707 void mpsse_loopback_config(struct mpsse_ctx *ctx, bool enable)
708 {
709         LOG_DEBUG("%s", enable ? "on" : "off");
710         single_byte_boolean_helper(ctx, enable, 0x84, 0x85);
711 }
712
713 void mpsse_set_divisor(struct mpsse_ctx *ctx, uint16_t divisor)
714 {
715         LOG_DEBUG("%d", divisor);
716
717         if (ctx->retval != ERROR_OK) {
718                 DEBUG_IO("Ignoring command due to previous error");
719                 return;
720         }
721
722         if (buffer_write_space(ctx) < 3)
723                 ctx->retval = mpsse_flush(ctx);
724
725         buffer_write_byte(ctx, 0x86);
726         buffer_write_byte(ctx, divisor & 0xff);
727         buffer_write_byte(ctx, divisor >> 8);
728 }
729
730 int mpsse_divide_by_5_config(struct mpsse_ctx *ctx, bool enable)
731 {
732         if (!mpsse_is_high_speed(ctx))
733                 return ERROR_FAIL;
734
735         LOG_DEBUG("%s", enable ? "on" : "off");
736         single_byte_boolean_helper(ctx, enable, 0x8b, 0x8a);
737
738         return ERROR_OK;
739 }
740
741 int mpsse_rtck_config(struct mpsse_ctx *ctx, bool enable)
742 {
743         if (!mpsse_is_high_speed(ctx))
744                 return ERROR_FAIL;
745
746         LOG_DEBUG("%s", enable ? "on" : "off");
747         single_byte_boolean_helper(ctx, enable, 0x96, 0x97);
748
749         return ERROR_OK;
750 }
751
752 int mpsse_set_frequency(struct mpsse_ctx *ctx, int frequency)
753 {
754         LOG_DEBUG("target %d Hz", frequency);
755         assert(frequency >= 0);
756         int base_clock;
757
758         if (frequency == 0)
759                 return mpsse_rtck_config(ctx, true);
760
761         mpsse_rtck_config(ctx, false); /* just try */
762
763         if (frequency > 60000000 / 2 / 65536 && mpsse_divide_by_5_config(ctx, false) == ERROR_OK) {
764                 base_clock = 60000000;
765         } else {
766                 mpsse_divide_by_5_config(ctx, true); /* just try */
767                 base_clock = 12000000;
768         }
769
770         int divisor = (base_clock / 2 + frequency - 1) / frequency - 1;
771         if (divisor > 65535)
772                 divisor = 65535;
773         assert(divisor >= 0);
774
775         mpsse_set_divisor(ctx, divisor);
776
777         frequency = base_clock / 2 / (1 + divisor);
778         LOG_DEBUG("actually %d Hz", frequency);
779
780         return frequency;
781 }
782
783 /* Context needed by the callbacks */
784 struct transfer_result {
785         struct mpsse_ctx *ctx;
786         bool done;
787         unsigned transferred;
788 };
789
790 static LIBUSB_CALL void read_cb(struct libusb_transfer *transfer)
791 {
792         struct transfer_result *res = transfer->user_data;
793         struct mpsse_ctx *ctx = res->ctx;
794
795         unsigned packet_size = ctx->max_packet_size;
796
797         DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
798
799         /* Strip the two status bytes sent at the beginning of each USB packet
800          * while copying the chunk buffer to the read buffer */
801         unsigned num_packets = DIV_ROUND_UP(transfer->actual_length, packet_size);
802         unsigned chunk_remains = transfer->actual_length;
803         for (unsigned i = 0; i < num_packets && chunk_remains > 2; i++) {
804                 unsigned this_size = packet_size - 2;
805                 if (this_size > chunk_remains - 2)
806                         this_size = chunk_remains - 2;
807                 if (this_size > ctx->read_count - res->transferred)
808                         this_size = ctx->read_count - res->transferred;
809                 memcpy(ctx->read_buffer + res->transferred,
810                         ctx->read_chunk + packet_size * i + 2,
811                         this_size);
812                 res->transferred += this_size;
813                 chunk_remains -= this_size + 2;
814                 if (res->transferred == ctx->read_count) {
815                         res->done = true;
816                         break;
817                 }
818         }
819
820         DEBUG_IO("raw chunk %d, transferred %d of %d", transfer->actual_length, res->transferred,
821                 ctx->read_count);
822
823         if (!res->done)
824                 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
825                         res->done = true;
826 }
827
828 static LIBUSB_CALL void write_cb(struct libusb_transfer *transfer)
829 {
830         struct transfer_result *res = transfer->user_data;
831         struct mpsse_ctx *ctx = res->ctx;
832
833         res->transferred += transfer->actual_length;
834
835         DEBUG_IO("transferred %d of %d", res->transferred, ctx->write_count);
836
837         DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
838
839         if (res->transferred == ctx->write_count)
840                 res->done = true;
841         else {
842                 transfer->length = ctx->write_count - res->transferred;
843                 transfer->buffer = ctx->write_buffer + res->transferred;
844                 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
845                         res->done = true;
846         }
847 }
848
849 int mpsse_flush(struct mpsse_ctx *ctx)
850 {
851         int retval = ctx->retval;
852
853         if (retval != ERROR_OK) {
854                 DEBUG_IO("Ignoring flush due to previous error");
855                 assert(ctx->write_count == 0 && ctx->read_count == 0);
856                 ctx->retval = ERROR_OK;
857                 return retval;
858         }
859
860         DEBUG_IO("write %d%s, read %d", ctx->write_count, ctx->read_count ? "+1" : "",
861                         ctx->read_count);
862         assert(ctx->write_count > 0 || ctx->read_count == 0); /* No read data without write data */
863
864         if (ctx->write_count == 0)
865                 return retval;
866
867         struct libusb_transfer *read_transfer = 0;
868         struct transfer_result read_result = { .ctx = ctx, .done = true };
869         if (ctx->read_count) {
870                 buffer_write_byte(ctx, 0x87); /* SEND_IMMEDIATE */
871                 read_result.done = false;
872                 /* delay read transaction to ensure the FTDI chip can support us with data
873                    immediately after processing the MPSSE commands in the write transaction */
874         }
875
876         struct transfer_result write_result = { .ctx = ctx, .done = false };
877         struct libusb_transfer *write_transfer = libusb_alloc_transfer(0);
878         libusb_fill_bulk_transfer(write_transfer, ctx->usb_dev, ctx->out_ep, ctx->write_buffer,
879                 ctx->write_count, write_cb, &write_result, ctx->usb_write_timeout);
880         retval = libusb_submit_transfer(write_transfer);
881         if (retval != LIBUSB_SUCCESS)
882                 goto error_check;
883
884         if (ctx->read_count) {
885                 read_transfer = libusb_alloc_transfer(0);
886                 libusb_fill_bulk_transfer(read_transfer, ctx->usb_dev, ctx->in_ep, ctx->read_chunk,
887                         ctx->read_chunk_size, read_cb, &read_result,
888                         ctx->usb_read_timeout);
889                 retval = libusb_submit_transfer(read_transfer);
890                 if (retval != LIBUSB_SUCCESS)
891                         goto error_check;
892         }
893
894         /* Polling loop, more or less taken from libftdi */
895         while (!write_result.done || !read_result.done) {
896                 struct timeval timeout_usb;
897
898                 timeout_usb.tv_sec = 1;
899                 timeout_usb.tv_usec = 0;
900
901                 retval = libusb_handle_events_timeout_completed(ctx->usb_ctx, &timeout_usb, NULL);
902                 keep_alive();
903                 if (retval == LIBUSB_ERROR_NO_DEVICE || retval == LIBUSB_ERROR_INTERRUPTED)
904                         break;
905
906                 if (retval != LIBUSB_SUCCESS) {
907                         libusb_cancel_transfer(write_transfer);
908                         if (read_transfer)
909                                 libusb_cancel_transfer(read_transfer);
910                         while (!write_result.done || !read_result.done) {
911                                 retval = libusb_handle_events_timeout_completed(ctx->usb_ctx,
912                                                                 &timeout_usb, NULL);
913                                 if (retval != LIBUSB_SUCCESS)
914                                         break;
915                         }
916                 }
917         }
918
919 error_check:
920         if (retval != LIBUSB_SUCCESS) {
921                 LOG_ERROR("libusb_handle_events() failed with %s", libusb_error_name(retval));
922                 retval = ERROR_FAIL;
923         } else if (write_result.transferred < ctx->write_count) {
924                 LOG_ERROR("ftdi device did not accept all data: %d, tried %d",
925                         write_result.transferred,
926                         ctx->write_count);
927                 retval = ERROR_FAIL;
928         } else if (read_result.transferred < ctx->read_count) {
929                 LOG_ERROR("ftdi device did not return all data: %d, expected %d",
930                         read_result.transferred,
931                         ctx->read_count);
932                 retval = ERROR_FAIL;
933         } else if (ctx->read_count) {
934                 ctx->write_count = 0;
935                 ctx->read_count = 0;
936                 bit_copy_execute(&ctx->read_queue);
937                 retval = ERROR_OK;
938         } else {
939                 ctx->write_count = 0;
940                 bit_copy_discard(&ctx->read_queue);
941                 retval = ERROR_OK;
942         }
943
944         libusb_free_transfer(write_transfer);
945         if (read_transfer)
946                 libusb_free_transfer(read_transfer);
947
948         if (retval != ERROR_OK)
949                 mpsse_purge(ctx);
950
951         return retval;
952 }