1 /**************************************************************************
2 * Copyright (C) 2012 by Andreas Fritiofson *
3 * andreas.fritiofson@gmail.com *
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. *
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. *
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 ***************************************************************************/
24 #include "helper/log.h"
25 #include "helper/replacements.h"
26 #include "helper/time_support.h"
29 /* Compatibility define for older libusb-1.0 */
34 #define DEBUG_PRINT_BUF(buf, len) \
36 if (LOG_LEVEL_IS(LOG_LVL_DEBUG_IO)) { \
37 char buf_string[32 * 3 + 1]; \
38 int buf_string_pos = 0; \
39 for (int i = 0; i < len; i++) { \
40 buf_string_pos += sprintf(buf_string + buf_string_pos, " %02x", buf[i]); \
41 if (i % 32 == 32 - 1) { \
42 LOG_DEBUG_IO("%s", buf_string); \
46 if (buf_string_pos > 0) \
47 LOG_DEBUG_IO("%s", buf_string);\
51 #define FTDI_DEVICE_OUT_REQTYPE (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE)
52 #define FTDI_DEVICE_IN_REQTYPE (0x80 | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE)
54 #define BITMODE_MPSSE 0x02
56 #define SIO_RESET_REQUEST 0x00
57 #define SIO_SET_LATENCY_TIMER_REQUEST 0x09
58 #define SIO_GET_LATENCY_TIMER_REQUEST 0x0A
59 #define SIO_SET_BITMODE_REQUEST 0x0B
61 #define SIO_RESET_SIO 0
62 #define SIO_RESET_PURGE_RX 1
63 #define SIO_RESET_PURGE_TX 2
66 struct libusb_context *usb_ctx;
67 struct libusb_device_handle *usb_dev;
68 unsigned int usb_write_timeout;
69 unsigned int usb_read_timeout;
72 uint16_t max_packet_size;
75 enum ftdi_chip_type type;
76 uint8_t *write_buffer;
83 unsigned read_chunk_size;
84 struct bit_copy_queue read_queue;
88 /* Returns true if the string descriptor indexed by str_index in device matches string */
89 static bool string_descriptor_equal(struct libusb_device_handle *device, uint8_t str_index,
93 char desc_string[256]; /* Max size of string descriptor */
94 retval = libusb_get_string_descriptor_ascii(device, str_index, (unsigned char *)desc_string,
97 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %s", libusb_error_name(retval));
100 return strncmp(string, desc_string, sizeof(desc_string)) == 0;
103 static bool device_location_equal(struct libusb_device *device, const char *location)
106 #ifdef HAVE_LIBUSB_GET_PORT_NUMBERS
107 char *loc = strdup(location);
108 uint8_t port_path[7];
109 int path_step, path_len;
110 uint8_t dev_bus = libusb_get_bus_number(device);
113 path_len = libusb_get_port_numbers(device, port_path, 7);
114 if (path_len == LIBUSB_ERROR_OVERFLOW) {
115 LOG_ERROR("cannot determine path to usb device! (more than 7 ports in path)");
119 LOG_DEBUG("device path has %i steps", path_len);
121 ptr = strtok(loc, "-:");
123 LOG_DEBUG("no ':' in path");
126 if (atoi(ptr) != dev_bus) {
127 LOG_DEBUG("bus mismatch");
132 while (path_step < 7) {
133 ptr = strtok(NULL, ".,");
135 LOG_DEBUG("no more tokens in path at step %i", path_step);
139 if (path_step < path_len
140 && atoi(ptr) != port_path[path_step]) {
141 LOG_DEBUG("path mismatch at step %i", path_step);
148 /* walked the full path, all elements match */
149 if (path_step == path_len)
158 /* Helper to open a libusb device that matches vid, pid, product string and/or serial string.
159 * Set any field to 0 as a wildcard. If the device is found true is returned, with ctx containing
160 * the already opened handle. ctx->interface must be set to the desired interface (channel) number
161 * prior to calling this function. */
162 static bool open_matching_device(struct mpsse_ctx *ctx, const uint16_t *vid, const uint16_t *pid,
163 const char *product, const char *serial, const char *location)
165 struct libusb_device **list;
166 struct libusb_device_descriptor desc;
167 struct libusb_config_descriptor *config0;
170 ssize_t cnt = libusb_get_device_list(ctx->usb_ctx, &list);
172 LOG_ERROR("libusb_get_device_list() failed with %s", libusb_error_name(cnt));
174 for (ssize_t i = 0; i < cnt; i++) {
175 struct libusb_device *device = list[i];
177 err = libusb_get_device_descriptor(device, &desc);
178 if (err != LIBUSB_SUCCESS) {
179 LOG_ERROR("libusb_get_device_descriptor() failed with %s", libusb_error_name(err));
183 if (vid && *vid != desc.idVendor)
185 if (pid && *pid != desc.idProduct)
188 err = libusb_open(device, &ctx->usb_dev);
189 if (err != LIBUSB_SUCCESS) {
190 LOG_ERROR("libusb_open() failed with %s",
191 libusb_error_name(err));
195 if (location && !device_location_equal(device, location)) {
196 libusb_close(ctx->usb_dev);
200 if (product && !string_descriptor_equal(ctx->usb_dev, desc.iProduct, product)) {
201 libusb_close(ctx->usb_dev);
205 if (serial && !string_descriptor_equal(ctx->usb_dev, desc.iSerialNumber, serial)) {
206 libusb_close(ctx->usb_dev);
214 libusb_free_device_list(list, 1);
217 LOG_ERROR("no device found");
221 err = libusb_get_config_descriptor(libusb_get_device(ctx->usb_dev), 0, &config0);
222 if (err != LIBUSB_SUCCESS) {
223 LOG_ERROR("libusb_get_config_descriptor() failed with %s", libusb_error_name(err));
224 libusb_close(ctx->usb_dev);
228 /* Make sure the first configuration is selected */
230 err = libusb_get_configuration(ctx->usb_dev, &cfg);
231 if (err != LIBUSB_SUCCESS) {
232 LOG_ERROR("libusb_get_configuration() failed with %s", libusb_error_name(err));
236 if (desc.bNumConfigurations > 0 && cfg != config0->bConfigurationValue) {
237 err = libusb_set_configuration(ctx->usb_dev, config0->bConfigurationValue);
238 if (err != LIBUSB_SUCCESS) {
239 LOG_ERROR("libusb_set_configuration() failed with %s", libusb_error_name(err));
244 /* Try to detach ftdi_sio kernel module */
245 err = libusb_detach_kernel_driver(ctx->usb_dev, ctx->interface);
246 if (err != LIBUSB_SUCCESS && err != LIBUSB_ERROR_NOT_FOUND
247 && err != LIBUSB_ERROR_NOT_SUPPORTED) {
248 LOG_WARNING("libusb_detach_kernel_driver() failed with %s, trying to continue anyway",
249 libusb_error_name(err));
252 err = libusb_claim_interface(ctx->usb_dev, ctx->interface);
253 if (err != LIBUSB_SUCCESS) {
254 LOG_ERROR("libusb_claim_interface() failed with %s", libusb_error_name(err));
258 /* Reset FTDI device */
259 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
260 SIO_RESET_REQUEST, SIO_RESET_SIO,
261 ctx->index, NULL, 0, ctx->usb_write_timeout);
263 LOG_ERROR("failed to reset FTDI device: %s", libusb_error_name(err));
267 switch (desc.bcdDevice) {
269 ctx->type = TYPE_FT2232C;
272 ctx->type = TYPE_FT2232H;
275 ctx->type = TYPE_FT4232H;
278 ctx->type = TYPE_FT232H;
281 LOG_ERROR("unsupported FTDI chip type: 0x%04x", desc.bcdDevice);
285 /* Determine maximum packet size and endpoint addresses */
286 if (!(desc.bNumConfigurations > 0 && ctx->interface < config0->bNumInterfaces
287 && config0->interface[ctx->interface].num_altsetting > 0))
290 const struct libusb_interface_descriptor *descriptor;
291 descriptor = &config0->interface[ctx->interface].altsetting[0];
292 if (descriptor->bNumEndpoints != 2)
297 for (int i = 0; i < descriptor->bNumEndpoints; i++) {
298 if (descriptor->endpoint[i].bEndpointAddress & 0x80) {
299 ctx->in_ep = descriptor->endpoint[i].bEndpointAddress;
300 ctx->max_packet_size =
301 descriptor->endpoint[i].wMaxPacketSize;
303 ctx->out_ep = descriptor->endpoint[i].bEndpointAddress;
307 if (ctx->in_ep == 0 || ctx->out_ep == 0)
310 libusb_free_config_descriptor(config0);
314 LOG_ERROR("unrecognized USB device descriptor");
316 libusb_free_config_descriptor(config0);
317 libusb_close(ctx->usb_dev);
321 struct mpsse_ctx *mpsse_open(const uint16_t *vid, const uint16_t *pid, const char *description,
322 const char *serial, const char *location, int channel)
324 struct mpsse_ctx *ctx = calloc(1, sizeof(*ctx));
330 bit_copy_queue_init(&ctx->read_queue);
331 ctx->read_chunk_size = 16384;
332 ctx->read_size = 16384;
333 ctx->write_size = 16384;
334 ctx->read_chunk = malloc(ctx->read_chunk_size);
335 ctx->read_buffer = malloc(ctx->read_size);
337 /* Use calloc to make valgrind happy: buffer_write() sets payload
338 * on bit basis, so some bits can be left uninitialized in write_buffer.
339 * Although this is perfectly ok with MPSSE, valgrind reports
340 * Syscall param ioctl(USBDEVFS_SUBMITURB).buffer points to uninitialised byte(s) */
341 ctx->write_buffer = calloc(1, ctx->write_size);
343 if (!ctx->read_chunk || !ctx->read_buffer || !ctx->write_buffer)
346 ctx->interface = channel;
347 ctx->index = channel + 1;
348 ctx->usb_read_timeout = 5000;
349 ctx->usb_write_timeout = 5000;
351 err = libusb_init(&ctx->usb_ctx);
352 if (err != LIBUSB_SUCCESS) {
353 LOG_ERROR("libusb_init() failed with %s", libusb_error_name(err));
357 if (!open_matching_device(ctx, vid, pid, description, serial, location)) {
358 /* Four hex digits plus terminating zero each */
361 LOG_ERROR("unable to open ftdi device with vid %s, pid %s, description '%s', "
362 "serial '%s' at bus location '%s'",
363 vid ? sprintf(vidstr, "%04x", *vid), vidstr : "*",
364 pid ? sprintf(pidstr, "%04x", *pid), pidstr : "*",
365 description ? description : "*",
366 serial ? serial : "*",
367 location ? location : "*");
372 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
373 SIO_SET_LATENCY_TIMER_REQUEST, 255, ctx->index, NULL, 0,
374 ctx->usb_write_timeout);
376 LOG_ERROR("unable to set latency timer: %s", libusb_error_name(err));
380 err = libusb_control_transfer(ctx->usb_dev,
381 FTDI_DEVICE_OUT_REQTYPE,
382 SIO_SET_BITMODE_REQUEST,
383 0x0b | (BITMODE_MPSSE << 8),
387 ctx->usb_write_timeout);
389 LOG_ERROR("unable to set MPSSE bitmode: %s", libusb_error_name(err));
401 void mpsse_close(struct mpsse_ctx *ctx)
404 libusb_close(ctx->usb_dev);
406 libusb_exit(ctx->usb_ctx);
407 bit_copy_discard(&ctx->read_queue);
409 free(ctx->write_buffer);
410 free(ctx->read_buffer);
411 free(ctx->read_chunk);
415 bool mpsse_is_high_speed(struct mpsse_ctx *ctx)
417 return ctx->type != TYPE_FT2232C;
420 void mpsse_purge(struct mpsse_ctx *ctx)
424 ctx->write_count = 0;
426 ctx->retval = ERROR_OK;
427 bit_copy_discard(&ctx->read_queue);
428 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
429 SIO_RESET_PURGE_RX, ctx->index, NULL, 0, ctx->usb_write_timeout);
431 LOG_ERROR("unable to purge ftdi rx buffers: %s", libusb_error_name(err));
435 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
436 SIO_RESET_PURGE_TX, ctx->index, NULL, 0, ctx->usb_write_timeout);
438 LOG_ERROR("unable to purge ftdi tx buffers: %s", libusb_error_name(err));
443 static unsigned buffer_write_space(struct mpsse_ctx *ctx)
445 /* Reserve one byte for SEND_IMMEDIATE */
446 return ctx->write_size - ctx->write_count - 1;
449 static unsigned buffer_read_space(struct mpsse_ctx *ctx)
451 return ctx->read_size - ctx->read_count;
454 static void buffer_write_byte(struct mpsse_ctx *ctx, uint8_t data)
456 LOG_DEBUG_IO("%02x", data);
457 assert(ctx->write_count < ctx->write_size);
458 ctx->write_buffer[ctx->write_count++] = data;
461 static unsigned buffer_write(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
464 LOG_DEBUG_IO("%d bits", bit_count);
465 assert(ctx->write_count + DIV_ROUND_UP(bit_count, 8) <= ctx->write_size);
466 bit_copy(ctx->write_buffer + ctx->write_count, 0, out, out_offset, bit_count);
467 ctx->write_count += DIV_ROUND_UP(bit_count, 8);
471 static unsigned buffer_add_read(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset,
472 unsigned bit_count, unsigned offset)
474 LOG_DEBUG_IO("%d bits, offset %d", bit_count, offset);
475 assert(ctx->read_count + DIV_ROUND_UP(bit_count, 8) <= ctx->read_size);
476 bit_copy_queued(&ctx->read_queue, in, in_offset, ctx->read_buffer + ctx->read_count, offset,
478 ctx->read_count += DIV_ROUND_UP(bit_count, 8);
482 void mpsse_clock_data_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
483 unsigned length, uint8_t mode)
485 mpsse_clock_data(ctx, out, out_offset, 0, 0, length, mode);
488 void mpsse_clock_data_in(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset, unsigned length,
491 mpsse_clock_data(ctx, 0, 0, in, in_offset, length, mode);
494 void mpsse_clock_data(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset, uint8_t *in,
495 unsigned in_offset, unsigned length, uint8_t mode)
497 /* TODO: Fix MSB first modes */
498 LOG_DEBUG_IO("%s%s %d bits", in ? "in" : "", out ? "out" : "", length);
500 if (ctx->retval != ERROR_OK) {
501 LOG_DEBUG_IO("Ignoring command due to previous error");
505 /* TODO: On H chips, use command 0x8E/0x8F if in and out are both 0 */
506 if (out || (!out && !in))
512 /* Guarantee buffer space enough for a minimum size transfer */
513 if (buffer_write_space(ctx) + (length < 8) < (out || (!out && !in) ? 4 : 3)
514 || (in && buffer_read_space(ctx) < 1))
515 ctx->retval = mpsse_flush(ctx);
518 /* Transfer remaining bits in bit mode */
519 buffer_write_byte(ctx, 0x02 | mode);
520 buffer_write_byte(ctx, length - 1);
522 out_offset += buffer_write(ctx, out, out_offset, length);
524 in_offset += buffer_add_read(ctx, in, in_offset, length, 8 - length);
526 buffer_write_byte(ctx, 0x00);
530 unsigned this_bytes = length / 8;
531 /* MPSSE command limit */
532 if (this_bytes > 65536)
534 /* Buffer space limit. We already made sure there's space for the minimum
536 if ((out || (!out && !in)) && this_bytes + 3 > buffer_write_space(ctx))
537 this_bytes = buffer_write_space(ctx) - 3;
538 if (in && this_bytes > buffer_read_space(ctx))
539 this_bytes = buffer_read_space(ctx);
541 if (this_bytes > 0) {
542 buffer_write_byte(ctx, mode);
543 buffer_write_byte(ctx, (this_bytes - 1) & 0xff);
544 buffer_write_byte(ctx, (this_bytes - 1) >> 8);
546 out_offset += buffer_write(ctx,
551 in_offset += buffer_add_read(ctx,
557 for (unsigned n = 0; n < this_bytes; n++)
558 buffer_write_byte(ctx, 0x00);
559 length -= this_bytes * 8;
565 void mpsse_clock_tms_cs_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
566 unsigned length, bool tdi, uint8_t mode)
568 mpsse_clock_tms_cs(ctx, out, out_offset, 0, 0, length, tdi, mode);
571 void mpsse_clock_tms_cs(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset, uint8_t *in,
572 unsigned in_offset, unsigned length, bool tdi, uint8_t mode)
574 LOG_DEBUG_IO("%sout %d bits, tdi=%d", in ? "in" : "", length, tdi);
577 if (ctx->retval != ERROR_OK) {
578 LOG_DEBUG_IO("Ignoring command due to previous error");
587 /* Guarantee buffer space enough for a minimum size transfer */
588 if (buffer_write_space(ctx) < 3 || (in && buffer_read_space(ctx) < 1))
589 ctx->retval = mpsse_flush(ctx);
592 unsigned this_bits = length;
593 /* MPSSE command limit */
594 /* NOTE: there's a report of an FT2232 bug in this area, where shifting
595 * exactly 7 bits can make problems with TMS signaling for the last
598 * http://developer.intra2net.com/mailarchive/html/libftdi/2009/msg00292.html
604 buffer_write_byte(ctx, mode);
605 buffer_write_byte(ctx, this_bits - 1);
607 /* TODO: Fix MSB first, if allowed in MPSSE */
608 bit_copy(&data, 0, out, out_offset, this_bits);
609 out_offset += this_bits;
610 buffer_write_byte(ctx, data | (tdi ? 0x80 : 0x00));
612 in_offset += buffer_add_read(ctx,
622 void mpsse_set_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
626 if (ctx->retval != ERROR_OK) {
627 LOG_DEBUG_IO("Ignoring command due to previous error");
631 if (buffer_write_space(ctx) < 3)
632 ctx->retval = mpsse_flush(ctx);
634 buffer_write_byte(ctx, 0x80);
635 buffer_write_byte(ctx, data);
636 buffer_write_byte(ctx, dir);
639 void mpsse_set_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
643 if (ctx->retval != ERROR_OK) {
644 LOG_DEBUG_IO("Ignoring command due to previous error");
648 if (buffer_write_space(ctx) < 3)
649 ctx->retval = mpsse_flush(ctx);
651 buffer_write_byte(ctx, 0x82);
652 buffer_write_byte(ctx, data);
653 buffer_write_byte(ctx, dir);
656 void mpsse_read_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t *data)
660 if (ctx->retval != ERROR_OK) {
661 LOG_DEBUG_IO("Ignoring command due to previous error");
665 if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
666 ctx->retval = mpsse_flush(ctx);
668 buffer_write_byte(ctx, 0x81);
669 buffer_add_read(ctx, data, 0, 8, 0);
672 void mpsse_read_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t *data)
676 if (ctx->retval != ERROR_OK) {
677 LOG_DEBUG_IO("Ignoring command due to previous error");
681 if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
682 ctx->retval = mpsse_flush(ctx);
684 buffer_write_byte(ctx, 0x83);
685 buffer_add_read(ctx, data, 0, 8, 0);
688 static void single_byte_boolean_helper(struct mpsse_ctx *ctx, bool var, uint8_t val_if_true,
689 uint8_t val_if_false)
691 if (ctx->retval != ERROR_OK) {
692 LOG_DEBUG_IO("Ignoring command due to previous error");
696 if (buffer_write_space(ctx) < 1)
697 ctx->retval = mpsse_flush(ctx);
699 buffer_write_byte(ctx, var ? val_if_true : val_if_false);
702 void mpsse_loopback_config(struct mpsse_ctx *ctx, bool enable)
704 LOG_DEBUG("%s", enable ? "on" : "off");
705 single_byte_boolean_helper(ctx, enable, 0x84, 0x85);
708 void mpsse_set_divisor(struct mpsse_ctx *ctx, uint16_t divisor)
710 LOG_DEBUG("%d", divisor);
712 if (ctx->retval != ERROR_OK) {
713 LOG_DEBUG_IO("Ignoring command due to previous error");
717 if (buffer_write_space(ctx) < 3)
718 ctx->retval = mpsse_flush(ctx);
720 buffer_write_byte(ctx, 0x86);
721 buffer_write_byte(ctx, divisor & 0xff);
722 buffer_write_byte(ctx, divisor >> 8);
725 int mpsse_divide_by_5_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, 0x8b, 0x8a);
736 int mpsse_rtck_config(struct mpsse_ctx *ctx, bool enable)
738 if (!mpsse_is_high_speed(ctx))
741 LOG_DEBUG("%s", enable ? "on" : "off");
742 single_byte_boolean_helper(ctx, enable, 0x96, 0x97);
747 int mpsse_set_frequency(struct mpsse_ctx *ctx, int frequency)
749 LOG_DEBUG("target %d Hz", frequency);
750 assert(frequency >= 0);
754 return mpsse_rtck_config(ctx, true);
756 mpsse_rtck_config(ctx, false); /* just try */
758 if (frequency > 60000000 / 2 / 65536 && mpsse_divide_by_5_config(ctx, false) == ERROR_OK) {
759 base_clock = 60000000;
761 mpsse_divide_by_5_config(ctx, true); /* just try */
762 base_clock = 12000000;
765 int divisor = (base_clock / 2 + frequency - 1) / frequency - 1;
768 assert(divisor >= 0);
770 mpsse_set_divisor(ctx, divisor);
772 frequency = base_clock / 2 / (1 + divisor);
773 LOG_DEBUG("actually %d Hz", frequency);
778 /* Context needed by the callbacks */
779 struct transfer_result {
780 struct mpsse_ctx *ctx;
782 unsigned transferred;
785 static LIBUSB_CALL void read_cb(struct libusb_transfer *transfer)
787 struct transfer_result *res = transfer->user_data;
788 struct mpsse_ctx *ctx = res->ctx;
790 unsigned packet_size = ctx->max_packet_size;
792 DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
794 /* Strip the two status bytes sent at the beginning of each USB packet
795 * while copying the chunk buffer to the read buffer */
796 unsigned num_packets = DIV_ROUND_UP(transfer->actual_length, packet_size);
797 unsigned chunk_remains = transfer->actual_length;
798 for (unsigned i = 0; i < num_packets && chunk_remains > 2; i++) {
799 unsigned this_size = packet_size - 2;
800 if (this_size > chunk_remains - 2)
801 this_size = chunk_remains - 2;
802 if (this_size > ctx->read_count - res->transferred)
803 this_size = ctx->read_count - res->transferred;
804 memcpy(ctx->read_buffer + res->transferred,
805 ctx->read_chunk + packet_size * i + 2,
807 res->transferred += this_size;
808 chunk_remains -= this_size + 2;
809 if (res->transferred == ctx->read_count) {
815 LOG_DEBUG_IO("raw chunk %d, transferred %d of %d", transfer->actual_length, res->transferred,
819 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
823 static LIBUSB_CALL void write_cb(struct libusb_transfer *transfer)
825 struct transfer_result *res = transfer->user_data;
826 struct mpsse_ctx *ctx = res->ctx;
828 res->transferred += transfer->actual_length;
830 LOG_DEBUG_IO("transferred %d of %d", res->transferred, ctx->write_count);
832 DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
834 if (res->transferred == ctx->write_count)
837 transfer->length = ctx->write_count - res->transferred;
838 transfer->buffer = ctx->write_buffer + res->transferred;
839 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
844 int mpsse_flush(struct mpsse_ctx *ctx)
846 int retval = ctx->retval;
848 if (retval != ERROR_OK) {
849 LOG_DEBUG_IO("Ignoring flush due to previous error");
850 assert(ctx->write_count == 0 && ctx->read_count == 0);
851 ctx->retval = ERROR_OK;
855 LOG_DEBUG_IO("write %d%s, read %d", ctx->write_count, ctx->read_count ? "+1" : "",
857 assert(ctx->write_count > 0 || ctx->read_count == 0); /* No read data without write data */
859 if (ctx->write_count == 0)
862 struct libusb_transfer *read_transfer = 0;
863 struct transfer_result read_result = { .ctx = ctx, .done = true };
864 if (ctx->read_count) {
865 buffer_write_byte(ctx, 0x87); /* SEND_IMMEDIATE */
866 read_result.done = false;
867 /* delay read transaction to ensure the FTDI chip can support us with data
868 immediately after processing the MPSSE commands in the write transaction */
871 struct transfer_result write_result = { .ctx = ctx, .done = false };
872 struct libusb_transfer *write_transfer = libusb_alloc_transfer(0);
873 libusb_fill_bulk_transfer(write_transfer, ctx->usb_dev, ctx->out_ep, ctx->write_buffer,
874 ctx->write_count, write_cb, &write_result, ctx->usb_write_timeout);
875 retval = libusb_submit_transfer(write_transfer);
876 if (retval != LIBUSB_SUCCESS)
879 if (ctx->read_count) {
880 read_transfer = libusb_alloc_transfer(0);
881 libusb_fill_bulk_transfer(read_transfer, ctx->usb_dev, ctx->in_ep, ctx->read_chunk,
882 ctx->read_chunk_size, read_cb, &read_result,
883 ctx->usb_read_timeout);
884 retval = libusb_submit_transfer(read_transfer);
885 if (retval != LIBUSB_SUCCESS)
889 /* Polling loop, more or less taken from libftdi */
890 int64_t start = timeval_ms();
891 int64_t warn_after = 2000;
892 while (!write_result.done || !read_result.done) {
893 struct timeval timeout_usb;
895 timeout_usb.tv_sec = 1;
896 timeout_usb.tv_usec = 0;
898 retval = libusb_handle_events_timeout_completed(ctx->usb_ctx, &timeout_usb, NULL);
900 if (retval == LIBUSB_ERROR_NO_DEVICE || retval == LIBUSB_ERROR_INTERRUPTED)
903 if (retval != LIBUSB_SUCCESS) {
904 libusb_cancel_transfer(write_transfer);
906 libusb_cancel_transfer(read_transfer);
907 while (!write_result.done || !read_result.done) {
908 retval = libusb_handle_events_timeout_completed(ctx->usb_ctx,
910 if (retval != LIBUSB_SUCCESS)
915 int64_t now = timeval_ms();
916 if (now - start > warn_after) {
917 LOG_WARNING("Haven't made progress in mpsse_flush() for %" PRId64
924 if (retval != LIBUSB_SUCCESS) {
925 LOG_ERROR("libusb_handle_events() failed with %s", libusb_error_name(retval));
927 } else if (write_result.transferred < ctx->write_count) {
928 LOG_ERROR("ftdi device did not accept all data: %d, tried %d",
929 write_result.transferred,
932 } else if (read_result.transferred < ctx->read_count) {
933 LOG_ERROR("ftdi device did not return all data: %d, expected %d",
934 read_result.transferred,
937 } else if (ctx->read_count) {
938 ctx->write_count = 0;
940 bit_copy_execute(&ctx->read_queue);
943 ctx->write_count = 0;
944 bit_copy_discard(&ctx->read_queue);
948 if (retval != ERROR_OK)
951 libusb_free_transfer(write_transfer);
953 libusb_free_transfer(read_transfer);