1 // SPDX-License-Identifier: GPL-2.0-or-later
3 /**************************************************************************
4 * Copyright (C) 2012 by Andreas Fritiofson *
5 * andreas.fritiofson@gmail.com *
6 ***************************************************************************/
13 #include "helper/log.h"
14 #include "helper/replacements.h"
15 #include "helper/time_support.h"
18 /* Compatibility define for older libusb-1.0 */
23 #define DEBUG_PRINT_BUF(buf, len) \
25 if (LOG_LEVEL_IS(LOG_LVL_DEBUG_IO)) { \
26 char buf_string[32 * 3 + 1]; \
27 int buf_string_pos = 0; \
28 for (int i = 0; i < len; i++) { \
29 buf_string_pos += sprintf(buf_string + buf_string_pos, " %02x", buf[i]); \
30 if (i % 32 == 32 - 1) { \
31 LOG_DEBUG_IO("%s", buf_string); \
35 if (buf_string_pos > 0) \
36 LOG_DEBUG_IO("%s", buf_string);\
40 #define FTDI_DEVICE_OUT_REQTYPE (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE)
41 #define FTDI_DEVICE_IN_REQTYPE (0x80 | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE)
43 #define BITMODE_MPSSE 0x02
45 #define SIO_RESET_REQUEST 0x00
46 #define SIO_SET_LATENCY_TIMER_REQUEST 0x09
47 #define SIO_GET_LATENCY_TIMER_REQUEST 0x0A
48 #define SIO_SET_BITMODE_REQUEST 0x0B
50 #define SIO_RESET_SIO 0
51 #define SIO_RESET_PURGE_RX 1
52 #define SIO_RESET_PURGE_TX 2
55 struct libusb_context *usb_ctx;
56 struct libusb_device_handle *usb_dev;
57 unsigned int usb_write_timeout;
58 unsigned int usb_read_timeout;
61 uint16_t max_packet_size;
64 enum ftdi_chip_type type;
65 uint8_t *write_buffer;
72 unsigned read_chunk_size;
73 struct bit_copy_queue read_queue;
77 /* Returns true if the string descriptor indexed by str_index in device matches string */
78 static bool string_descriptor_equal(struct libusb_device_handle *device, uint8_t str_index,
82 char desc_string[256]; /* Max size of string descriptor */
83 retval = libusb_get_string_descriptor_ascii(device, str_index, (unsigned char *)desc_string,
86 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %s", libusb_error_name(retval));
89 return strncmp(string, desc_string, sizeof(desc_string)) == 0;
92 static bool device_location_equal(struct libusb_device *device, const char *location)
95 #ifdef HAVE_LIBUSB_GET_PORT_NUMBERS
96 char *loc = strdup(location);
98 int path_step, path_len;
99 uint8_t dev_bus = libusb_get_bus_number(device);
102 path_len = libusb_get_port_numbers(device, port_path, 7);
103 if (path_len == LIBUSB_ERROR_OVERFLOW) {
104 LOG_ERROR("cannot determine path to usb device! (more than 7 ports in path)");
108 LOG_DEBUG("device path has %i steps", path_len);
110 ptr = strtok(loc, "-:");
112 LOG_DEBUG("no ':' in path");
115 if (atoi(ptr) != dev_bus) {
116 LOG_DEBUG("bus mismatch");
121 while (path_step < 7) {
122 ptr = strtok(NULL, ".,");
124 LOG_DEBUG("no more tokens in path at step %i", path_step);
128 if (path_step < path_len
129 && atoi(ptr) != port_path[path_step]) {
130 LOG_DEBUG("path mismatch at step %i", path_step);
137 /* walked the full path, all elements match */
138 if (path_step == path_len)
147 /* Helper to open a libusb device that matches vid, pid, product string and/or serial string.
148 * Set any field to 0 as a wildcard. If the device is found true is returned, with ctx containing
149 * the already opened handle. ctx->interface must be set to the desired interface (channel) number
150 * prior to calling this function. */
151 static bool open_matching_device(struct mpsse_ctx *ctx, const uint16_t *vid, const uint16_t *pid,
152 const char *product, const char *serial, const char *location)
154 struct libusb_device **list;
155 struct libusb_device_descriptor desc;
156 struct libusb_config_descriptor *config0;
159 ssize_t cnt = libusb_get_device_list(ctx->usb_ctx, &list);
161 LOG_ERROR("libusb_get_device_list() failed with %s", libusb_error_name(cnt));
163 for (ssize_t i = 0; i < cnt; i++) {
164 struct libusb_device *device = list[i];
166 err = libusb_get_device_descriptor(device, &desc);
167 if (err != LIBUSB_SUCCESS) {
168 LOG_ERROR("libusb_get_device_descriptor() failed with %s", libusb_error_name(err));
172 if (vid && *vid != desc.idVendor)
174 if (pid && *pid != desc.idProduct)
177 err = libusb_open(device, &ctx->usb_dev);
178 if (err != LIBUSB_SUCCESS) {
179 LOG_ERROR("libusb_open() failed with %s",
180 libusb_error_name(err));
184 if (location && !device_location_equal(device, location)) {
185 libusb_close(ctx->usb_dev);
189 if (product && !string_descriptor_equal(ctx->usb_dev, desc.iProduct, product)) {
190 libusb_close(ctx->usb_dev);
194 if (serial && !string_descriptor_equal(ctx->usb_dev, desc.iSerialNumber, serial)) {
195 libusb_close(ctx->usb_dev);
203 libusb_free_device_list(list, 1);
206 LOG_ERROR("no device found");
210 err = libusb_get_config_descriptor(libusb_get_device(ctx->usb_dev), 0, &config0);
211 if (err != LIBUSB_SUCCESS) {
212 LOG_ERROR("libusb_get_config_descriptor() failed with %s", libusb_error_name(err));
213 libusb_close(ctx->usb_dev);
217 /* Make sure the first configuration is selected */
219 err = libusb_get_configuration(ctx->usb_dev, &cfg);
220 if (err != LIBUSB_SUCCESS) {
221 LOG_ERROR("libusb_get_configuration() failed with %s", libusb_error_name(err));
225 if (desc.bNumConfigurations > 0 && cfg != config0->bConfigurationValue) {
226 err = libusb_set_configuration(ctx->usb_dev, config0->bConfigurationValue);
227 if (err != LIBUSB_SUCCESS) {
228 LOG_ERROR("libusb_set_configuration() failed with %s", libusb_error_name(err));
233 /* Try to detach ftdi_sio kernel module */
234 err = libusb_detach_kernel_driver(ctx->usb_dev, ctx->interface);
235 if (err != LIBUSB_SUCCESS && err != LIBUSB_ERROR_NOT_FOUND
236 && err != LIBUSB_ERROR_NOT_SUPPORTED) {
237 LOG_WARNING("libusb_detach_kernel_driver() failed with %s, trying to continue anyway",
238 libusb_error_name(err));
241 err = libusb_claim_interface(ctx->usb_dev, ctx->interface);
242 if (err != LIBUSB_SUCCESS) {
243 LOG_ERROR("libusb_claim_interface() failed with %s", libusb_error_name(err));
247 /* Reset FTDI device */
248 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
249 SIO_RESET_REQUEST, SIO_RESET_SIO,
250 ctx->index, NULL, 0, ctx->usb_write_timeout);
252 LOG_ERROR("failed to reset FTDI device: %s", libusb_error_name(err));
256 switch (desc.bcdDevice) {
258 ctx->type = TYPE_FT2232C;
261 ctx->type = TYPE_FT2232H;
264 ctx->type = TYPE_FT4232H;
267 ctx->type = TYPE_FT232H;
270 LOG_ERROR("unsupported FTDI chip type: 0x%04x", desc.bcdDevice);
274 /* Determine maximum packet size and endpoint addresses */
275 if (!(desc.bNumConfigurations > 0 && ctx->interface < config0->bNumInterfaces
276 && config0->interface[ctx->interface].num_altsetting > 0))
279 const struct libusb_interface_descriptor *descriptor;
280 descriptor = &config0->interface[ctx->interface].altsetting[0];
281 if (descriptor->bNumEndpoints != 2)
286 for (int i = 0; i < descriptor->bNumEndpoints; i++) {
287 if (descriptor->endpoint[i].bEndpointAddress & 0x80) {
288 ctx->in_ep = descriptor->endpoint[i].bEndpointAddress;
289 ctx->max_packet_size =
290 descriptor->endpoint[i].wMaxPacketSize;
292 ctx->out_ep = descriptor->endpoint[i].bEndpointAddress;
296 if (ctx->in_ep == 0 || ctx->out_ep == 0)
299 libusb_free_config_descriptor(config0);
303 LOG_ERROR("unrecognized USB device descriptor");
305 libusb_free_config_descriptor(config0);
306 libusb_close(ctx->usb_dev);
310 struct mpsse_ctx *mpsse_open(const uint16_t *vid, const uint16_t *pid, const char *description,
311 const char *serial, const char *location, int channel)
313 struct mpsse_ctx *ctx = calloc(1, sizeof(*ctx));
319 bit_copy_queue_init(&ctx->read_queue);
320 ctx->read_chunk_size = 16384;
321 ctx->read_size = 16384;
322 ctx->write_size = 16384;
323 ctx->read_chunk = malloc(ctx->read_chunk_size);
324 ctx->read_buffer = malloc(ctx->read_size);
326 /* Use calloc to make valgrind happy: buffer_write() sets payload
327 * on bit basis, so some bits can be left uninitialized in write_buffer.
328 * Although this is perfectly ok with MPSSE, valgrind reports
329 * Syscall param ioctl(USBDEVFS_SUBMITURB).buffer points to uninitialised byte(s) */
330 ctx->write_buffer = calloc(1, ctx->write_size);
332 if (!ctx->read_chunk || !ctx->read_buffer || !ctx->write_buffer)
335 ctx->interface = channel;
336 ctx->index = channel + 1;
337 ctx->usb_read_timeout = 5000;
338 ctx->usb_write_timeout = 5000;
340 err = libusb_init(&ctx->usb_ctx);
341 if (err != LIBUSB_SUCCESS) {
342 LOG_ERROR("libusb_init() failed with %s", libusb_error_name(err));
346 if (!open_matching_device(ctx, vid, pid, description, serial, location)) {
347 /* Four hex digits plus terminating zero each */
350 LOG_ERROR("unable to open ftdi device with vid %s, pid %s, description '%s', "
351 "serial '%s' at bus location '%s'",
352 vid ? sprintf(vidstr, "%04x", *vid), vidstr : "*",
353 pid ? sprintf(pidstr, "%04x", *pid), pidstr : "*",
354 description ? description : "*",
355 serial ? serial : "*",
356 location ? location : "*");
361 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
362 SIO_SET_LATENCY_TIMER_REQUEST, 255, ctx->index, NULL, 0,
363 ctx->usb_write_timeout);
365 LOG_ERROR("unable to set latency timer: %s", libusb_error_name(err));
369 err = libusb_control_transfer(ctx->usb_dev,
370 FTDI_DEVICE_OUT_REQTYPE,
371 SIO_SET_BITMODE_REQUEST,
372 0x0b | (BITMODE_MPSSE << 8),
376 ctx->usb_write_timeout);
378 LOG_ERROR("unable to set MPSSE bitmode: %s", libusb_error_name(err));
390 void mpsse_close(struct mpsse_ctx *ctx)
393 libusb_close(ctx->usb_dev);
395 libusb_exit(ctx->usb_ctx);
396 bit_copy_discard(&ctx->read_queue);
398 free(ctx->write_buffer);
399 free(ctx->read_buffer);
400 free(ctx->read_chunk);
404 bool mpsse_is_high_speed(struct mpsse_ctx *ctx)
406 return ctx->type != TYPE_FT2232C;
409 void mpsse_purge(struct mpsse_ctx *ctx)
413 ctx->write_count = 0;
415 ctx->retval = ERROR_OK;
416 bit_copy_discard(&ctx->read_queue);
417 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
418 SIO_RESET_PURGE_RX, ctx->index, NULL, 0, ctx->usb_write_timeout);
420 LOG_ERROR("unable to purge ftdi rx buffers: %s", libusb_error_name(err));
424 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
425 SIO_RESET_PURGE_TX, ctx->index, NULL, 0, ctx->usb_write_timeout);
427 LOG_ERROR("unable to purge ftdi tx buffers: %s", libusb_error_name(err));
432 static unsigned buffer_write_space(struct mpsse_ctx *ctx)
434 /* Reserve one byte for SEND_IMMEDIATE */
435 return ctx->write_size - ctx->write_count - 1;
438 static unsigned buffer_read_space(struct mpsse_ctx *ctx)
440 return ctx->read_size - ctx->read_count;
443 static void buffer_write_byte(struct mpsse_ctx *ctx, uint8_t data)
445 LOG_DEBUG_IO("%02x", data);
446 assert(ctx->write_count < ctx->write_size);
447 ctx->write_buffer[ctx->write_count++] = data;
450 static unsigned buffer_write(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
453 LOG_DEBUG_IO("%d bits", bit_count);
454 assert(ctx->write_count + DIV_ROUND_UP(bit_count, 8) <= ctx->write_size);
455 bit_copy(ctx->write_buffer + ctx->write_count, 0, out, out_offset, bit_count);
456 ctx->write_count += DIV_ROUND_UP(bit_count, 8);
460 static unsigned buffer_add_read(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset,
461 unsigned bit_count, unsigned offset)
463 LOG_DEBUG_IO("%d bits, offset %d", bit_count, offset);
464 assert(ctx->read_count + DIV_ROUND_UP(bit_count, 8) <= ctx->read_size);
465 bit_copy_queued(&ctx->read_queue, in, in_offset, ctx->read_buffer + ctx->read_count, offset,
467 ctx->read_count += DIV_ROUND_UP(bit_count, 8);
471 void mpsse_clock_data_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
472 unsigned length, uint8_t mode)
474 mpsse_clock_data(ctx, out, out_offset, 0, 0, length, mode);
477 void mpsse_clock_data_in(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset, unsigned length,
480 mpsse_clock_data(ctx, 0, 0, in, in_offset, length, mode);
483 void mpsse_clock_data(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset, uint8_t *in,
484 unsigned in_offset, unsigned length, uint8_t mode)
486 /* TODO: Fix MSB first modes */
487 LOG_DEBUG_IO("%s%s %d bits", in ? "in" : "", out ? "out" : "", length);
489 if (ctx->retval != ERROR_OK) {
490 LOG_DEBUG_IO("Ignoring command due to previous error");
494 /* TODO: On H chips, use command 0x8E/0x8F if in and out are both 0 */
495 if (out || (!out && !in))
501 /* Guarantee buffer space enough for a minimum size transfer */
502 if (buffer_write_space(ctx) + (length < 8) < (out || (!out && !in) ? 4 : 3)
503 || (in && buffer_read_space(ctx) < 1))
504 ctx->retval = mpsse_flush(ctx);
507 /* Transfer remaining bits in bit mode */
508 buffer_write_byte(ctx, 0x02 | mode);
509 buffer_write_byte(ctx, length - 1);
511 out_offset += buffer_write(ctx, out, out_offset, length);
513 in_offset += buffer_add_read(ctx, in, in_offset, length, 8 - length);
515 buffer_write_byte(ctx, 0x00);
519 unsigned this_bytes = length / 8;
520 /* MPSSE command limit */
521 if (this_bytes > 65536)
523 /* Buffer space limit. We already made sure there's space for the minimum
525 if ((out || (!out && !in)) && this_bytes + 3 > buffer_write_space(ctx))
526 this_bytes = buffer_write_space(ctx) - 3;
527 if (in && this_bytes > buffer_read_space(ctx))
528 this_bytes = buffer_read_space(ctx);
530 if (this_bytes > 0) {
531 buffer_write_byte(ctx, mode);
532 buffer_write_byte(ctx, (this_bytes - 1) & 0xff);
533 buffer_write_byte(ctx, (this_bytes - 1) >> 8);
535 out_offset += buffer_write(ctx,
540 in_offset += buffer_add_read(ctx,
546 for (unsigned n = 0; n < this_bytes; n++)
547 buffer_write_byte(ctx, 0x00);
548 length -= this_bytes * 8;
554 void mpsse_clock_tms_cs_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
555 unsigned length, bool tdi, uint8_t mode)
557 mpsse_clock_tms_cs(ctx, out, out_offset, 0, 0, length, tdi, mode);
560 void mpsse_clock_tms_cs(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset, uint8_t *in,
561 unsigned in_offset, unsigned length, bool tdi, uint8_t mode)
563 LOG_DEBUG_IO("%sout %d bits, tdi=%d", in ? "in" : "", length, tdi);
566 if (ctx->retval != ERROR_OK) {
567 LOG_DEBUG_IO("Ignoring command due to previous error");
576 /* Guarantee buffer space enough for a minimum size transfer */
577 if (buffer_write_space(ctx) < 3 || (in && buffer_read_space(ctx) < 1))
578 ctx->retval = mpsse_flush(ctx);
581 unsigned this_bits = length;
582 /* MPSSE command limit */
583 /* NOTE: there's a report of an FT2232 bug in this area, where shifting
584 * exactly 7 bits can make problems with TMS signaling for the last
587 * http://developer.intra2net.com/mailarchive/html/libftdi/2009/msg00292.html
593 buffer_write_byte(ctx, mode);
594 buffer_write_byte(ctx, this_bits - 1);
596 /* TODO: Fix MSB first, if allowed in MPSSE */
597 bit_copy(&data, 0, out, out_offset, this_bits);
598 out_offset += this_bits;
599 buffer_write_byte(ctx, data | (tdi ? 0x80 : 0x00));
601 in_offset += buffer_add_read(ctx,
611 void mpsse_set_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
615 if (ctx->retval != ERROR_OK) {
616 LOG_DEBUG_IO("Ignoring command due to previous error");
620 if (buffer_write_space(ctx) < 3)
621 ctx->retval = mpsse_flush(ctx);
623 buffer_write_byte(ctx, 0x80);
624 buffer_write_byte(ctx, data);
625 buffer_write_byte(ctx, dir);
628 void mpsse_set_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
632 if (ctx->retval != ERROR_OK) {
633 LOG_DEBUG_IO("Ignoring command due to previous error");
637 if (buffer_write_space(ctx) < 3)
638 ctx->retval = mpsse_flush(ctx);
640 buffer_write_byte(ctx, 0x82);
641 buffer_write_byte(ctx, data);
642 buffer_write_byte(ctx, dir);
645 void mpsse_read_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t *data)
649 if (ctx->retval != ERROR_OK) {
650 LOG_DEBUG_IO("Ignoring command due to previous error");
654 if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
655 ctx->retval = mpsse_flush(ctx);
657 buffer_write_byte(ctx, 0x81);
658 buffer_add_read(ctx, data, 0, 8, 0);
661 void mpsse_read_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t *data)
665 if (ctx->retval != ERROR_OK) {
666 LOG_DEBUG_IO("Ignoring command due to previous error");
670 if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
671 ctx->retval = mpsse_flush(ctx);
673 buffer_write_byte(ctx, 0x83);
674 buffer_add_read(ctx, data, 0, 8, 0);
677 static void single_byte_boolean_helper(struct mpsse_ctx *ctx, bool var, uint8_t val_if_true,
678 uint8_t val_if_false)
680 if (ctx->retval != ERROR_OK) {
681 LOG_DEBUG_IO("Ignoring command due to previous error");
685 if (buffer_write_space(ctx) < 1)
686 ctx->retval = mpsse_flush(ctx);
688 buffer_write_byte(ctx, var ? val_if_true : val_if_false);
691 void mpsse_loopback_config(struct mpsse_ctx *ctx, bool enable)
693 LOG_DEBUG("%s", enable ? "on" : "off");
694 single_byte_boolean_helper(ctx, enable, 0x84, 0x85);
697 void mpsse_set_divisor(struct mpsse_ctx *ctx, uint16_t divisor)
699 LOG_DEBUG("%d", divisor);
701 if (ctx->retval != ERROR_OK) {
702 LOG_DEBUG_IO("Ignoring command due to previous error");
706 if (buffer_write_space(ctx) < 3)
707 ctx->retval = mpsse_flush(ctx);
709 buffer_write_byte(ctx, 0x86);
710 buffer_write_byte(ctx, divisor & 0xff);
711 buffer_write_byte(ctx, divisor >> 8);
714 int mpsse_divide_by_5_config(struct mpsse_ctx *ctx, bool enable)
716 if (!mpsse_is_high_speed(ctx))
719 LOG_DEBUG("%s", enable ? "on" : "off");
720 single_byte_boolean_helper(ctx, enable, 0x8b, 0x8a);
725 int mpsse_rtck_config(struct mpsse_ctx *ctx, bool enable)
727 if (!mpsse_is_high_speed(ctx))
730 LOG_DEBUG("%s", enable ? "on" : "off");
731 single_byte_boolean_helper(ctx, enable, 0x96, 0x97);
736 int mpsse_set_frequency(struct mpsse_ctx *ctx, int frequency)
738 LOG_DEBUG("target %d Hz", frequency);
739 assert(frequency >= 0);
743 return mpsse_rtck_config(ctx, true);
745 mpsse_rtck_config(ctx, false); /* just try */
747 if (frequency > 60000000 / 2 / 65536 && mpsse_divide_by_5_config(ctx, false) == ERROR_OK) {
748 base_clock = 60000000;
750 mpsse_divide_by_5_config(ctx, true); /* just try */
751 base_clock = 12000000;
754 int divisor = (base_clock / 2 + frequency - 1) / frequency - 1;
757 assert(divisor >= 0);
759 mpsse_set_divisor(ctx, divisor);
761 frequency = base_clock / 2 / (1 + divisor);
762 LOG_DEBUG("actually %d Hz", frequency);
767 /* Context needed by the callbacks */
768 struct transfer_result {
769 struct mpsse_ctx *ctx;
771 unsigned transferred;
774 static LIBUSB_CALL void read_cb(struct libusb_transfer *transfer)
776 struct transfer_result *res = transfer->user_data;
777 struct mpsse_ctx *ctx = res->ctx;
779 unsigned packet_size = ctx->max_packet_size;
781 DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
783 /* Strip the two status bytes sent at the beginning of each USB packet
784 * while copying the chunk buffer to the read buffer */
785 unsigned num_packets = DIV_ROUND_UP(transfer->actual_length, packet_size);
786 unsigned chunk_remains = transfer->actual_length;
787 for (unsigned i = 0; i < num_packets && chunk_remains > 2; i++) {
788 unsigned this_size = packet_size - 2;
789 if (this_size > chunk_remains - 2)
790 this_size = chunk_remains - 2;
791 if (this_size > ctx->read_count - res->transferred)
792 this_size = ctx->read_count - res->transferred;
793 memcpy(ctx->read_buffer + res->transferred,
794 ctx->read_chunk + packet_size * i + 2,
796 res->transferred += this_size;
797 chunk_remains -= this_size + 2;
798 if (res->transferred == ctx->read_count) {
804 LOG_DEBUG_IO("raw chunk %d, transferred %d of %d", transfer->actual_length, res->transferred,
808 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
812 static LIBUSB_CALL void write_cb(struct libusb_transfer *transfer)
814 struct transfer_result *res = transfer->user_data;
815 struct mpsse_ctx *ctx = res->ctx;
817 res->transferred += transfer->actual_length;
819 LOG_DEBUG_IO("transferred %d of %d", res->transferred, ctx->write_count);
821 DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
823 if (res->transferred == ctx->write_count)
826 transfer->length = ctx->write_count - res->transferred;
827 transfer->buffer = ctx->write_buffer + res->transferred;
828 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
833 int mpsse_flush(struct mpsse_ctx *ctx)
835 int retval = ctx->retval;
837 if (retval != ERROR_OK) {
838 LOG_DEBUG_IO("Ignoring flush due to previous error");
839 assert(ctx->write_count == 0 && ctx->read_count == 0);
840 ctx->retval = ERROR_OK;
844 LOG_DEBUG_IO("write %d%s, read %d", ctx->write_count, ctx->read_count ? "+1" : "",
846 assert(ctx->write_count > 0 || ctx->read_count == 0); /* No read data without write data */
848 if (ctx->write_count == 0)
851 struct libusb_transfer *read_transfer = 0;
852 struct transfer_result read_result = { .ctx = ctx, .done = true };
853 if (ctx->read_count) {
854 buffer_write_byte(ctx, 0x87); /* SEND_IMMEDIATE */
855 read_result.done = false;
856 /* delay read transaction to ensure the FTDI chip can support us with data
857 immediately after processing the MPSSE commands in the write transaction */
860 struct transfer_result write_result = { .ctx = ctx, .done = false };
861 struct libusb_transfer *write_transfer = libusb_alloc_transfer(0);
862 libusb_fill_bulk_transfer(write_transfer, ctx->usb_dev, ctx->out_ep, ctx->write_buffer,
863 ctx->write_count, write_cb, &write_result, ctx->usb_write_timeout);
864 retval = libusb_submit_transfer(write_transfer);
865 if (retval != LIBUSB_SUCCESS)
868 if (ctx->read_count) {
869 read_transfer = libusb_alloc_transfer(0);
870 libusb_fill_bulk_transfer(read_transfer, ctx->usb_dev, ctx->in_ep, ctx->read_chunk,
871 ctx->read_chunk_size, read_cb, &read_result,
872 ctx->usb_read_timeout);
873 retval = libusb_submit_transfer(read_transfer);
874 if (retval != LIBUSB_SUCCESS)
878 /* Polling loop, more or less taken from libftdi */
879 int64_t start = timeval_ms();
880 int64_t warn_after = 2000;
881 while (!write_result.done || !read_result.done) {
882 struct timeval timeout_usb;
884 timeout_usb.tv_sec = 1;
885 timeout_usb.tv_usec = 0;
887 retval = libusb_handle_events_timeout_completed(ctx->usb_ctx, &timeout_usb, NULL);
889 if (retval == LIBUSB_ERROR_NO_DEVICE || retval == LIBUSB_ERROR_INTERRUPTED)
892 if (retval != LIBUSB_SUCCESS) {
893 libusb_cancel_transfer(write_transfer);
895 libusb_cancel_transfer(read_transfer);
896 while (!write_result.done || !read_result.done) {
897 retval = libusb_handle_events_timeout_completed(ctx->usb_ctx,
899 if (retval != LIBUSB_SUCCESS)
904 int64_t now = timeval_ms();
905 if (now - start > warn_after) {
906 LOG_WARNING("Haven't made progress in mpsse_flush() for %" PRId64
913 if (retval != LIBUSB_SUCCESS) {
914 LOG_ERROR("libusb_handle_events() failed with %s", libusb_error_name(retval));
916 } else if (write_result.transferred < ctx->write_count) {
917 LOG_ERROR("ftdi device did not accept all data: %d, tried %d",
918 write_result.transferred,
921 } else if (read_result.transferred < ctx->read_count) {
922 LOG_ERROR("ftdi device did not return all data: %d, expected %d",
923 read_result.transferred,
926 } else if (ctx->read_count) {
927 ctx->write_count = 0;
929 bit_copy_execute(&ctx->read_queue);
932 ctx->write_count = 0;
933 bit_copy_discard(&ctx->read_queue);
937 if (retval != ERROR_OK)
940 libusb_free_transfer(write_transfer);
942 libusb_free_transfer(read_transfer);