mpsse: Always perform a general reset of the MPSSE in mpsse_open()
[openocd.git] / src / jtag / drivers / mpsse.c
blob92f9331a543c39385eaa538eaa64889bab62e879
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, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
25 #include "mpsse.h"
26 #include "helper/log.h"
27 #include <libusb-1.0/libusb.h>
29 /* Compatibility define for older libusb-1.0 */
30 #ifndef LIBUSB_CALL
31 #define LIBUSB_CALL
32 #endif
34 #ifdef _DEBUG_JTAG_IO_
35 #define DEBUG_IO(expr...) LOG_DEBUG(expr)
36 #define DEBUG_PRINT_BUF(buf, len) \
37 do { \
38 char buf_string[32 * 3 + 1]; \
39 int buf_string_pos = 0; \
40 for (int i = 0; i < len; i++) { \
41 buf_string_pos += sprintf(buf_string + buf_string_pos, " %02x", buf[i]); \
42 if (i % 32 == 32 - 1) { \
43 LOG_DEBUG("%s", buf_string); \
44 buf_string_pos = 0; \
45 } \
46 } \
47 if (buf_string_pos > 0) \
48 LOG_DEBUG("%s", buf_string);\
49 } while (0)
50 #else
51 #define DEBUG_IO(expr...) do {} while (0)
52 #define DEBUG_PRINT_BUF(buf, len) do {} while (0)
53 #endif
55 #define FTDI_DEVICE_OUT_REQTYPE (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE)
56 #define FTDI_DEVICE_IN_REQTYPE (0x80 | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE)
58 #define BITMODE_RESET 0x00
59 #define BITMODE_MPSSE 0x02
61 #define SIO_RESET_REQUEST 0x00
62 #define SIO_SET_LATENCY_TIMER_REQUEST 0x09
63 #define SIO_GET_LATENCY_TIMER_REQUEST 0x0A
64 #define SIO_SET_BITMODE_REQUEST 0x0B
66 #define SIO_RESET_SIO 0
67 #define SIO_RESET_PURGE_RX 1
68 #define SIO_RESET_PURGE_TX 2
70 struct mpsse_ctx {
71 libusb_context *usb_ctx;
72 libusb_device_handle *usb_dev;
73 unsigned int usb_write_timeout;
74 unsigned int usb_read_timeout;
75 uint8_t in_ep;
76 uint8_t out_ep;
77 uint16_t max_packet_size;
78 uint16_t index;
79 uint8_t interface;
80 enum ftdi_chip_type type;
81 uint8_t *write_buffer;
82 unsigned write_size;
83 unsigned write_count;
84 uint8_t *read_buffer;
85 unsigned read_size;
86 unsigned read_count;
87 uint8_t *read_chunk;
88 unsigned read_chunk_size;
89 struct bit_copy_queue read_queue;
92 /* Returns true if the string descriptor indexed by str_index in device matches string */
93 static bool string_descriptor_equal(libusb_device_handle *device, uint8_t str_index,
94 const char *string)
96 int retval;
97 char desc_string[256]; /* Max size of string descriptor */
98 retval = libusb_get_string_descriptor_ascii(device, str_index, (unsigned char *)desc_string,
99 sizeof(desc_string));
100 if (retval < 0) {
101 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %d", retval);
102 return false;
104 return strncmp(string, desc_string, sizeof(desc_string)) == 0;
107 /* Helper to open a libusb device that matches vid, pid, product string and/or serial string.
108 * Set any field to 0 as a wildcard. If the device is found true is returned, with ctx containing
109 * the already opened handle. ctx->interface must be set to the desired interface (channel) number
110 * prior to calling this function. */
111 static bool open_matching_device(struct mpsse_ctx *ctx, const uint16_t *vid, const uint16_t *pid,
112 const char *product, const char *serial)
114 libusb_device **list;
115 struct libusb_device_descriptor desc;
116 struct libusb_config_descriptor *config0;
117 int err;
118 bool found = false;
119 ssize_t cnt = libusb_get_device_list(ctx->usb_ctx, &list);
120 if (cnt < 0)
121 LOG_ERROR("libusb_get_device_list() failed with %zi", cnt);
123 for (ssize_t i = 0; i < cnt; i++) {
124 libusb_device *device = list[i];
126 err = libusb_get_device_descriptor(device, &desc);
127 if (err != LIBUSB_SUCCESS) {
128 LOG_ERROR("libusb_get_device_descriptor() failed with %d", err);
129 continue;
132 if (vid && *vid != desc.idVendor)
133 continue;
134 if (pid && *pid != desc.idProduct)
135 continue;
137 err = libusb_open(device, &ctx->usb_dev);
138 if (err != LIBUSB_SUCCESS) {
139 LOG_ERROR("libusb_open() failed with %d", err);
140 continue;
143 if (product && !string_descriptor_equal(ctx->usb_dev, desc.iProduct, product)) {
144 libusb_close(ctx->usb_dev);
145 continue;
148 if (serial && !string_descriptor_equal(ctx->usb_dev, desc.iSerialNumber, serial)) {
149 libusb_close(ctx->usb_dev);
150 continue;
153 found = true;
154 break;
157 libusb_free_device_list(list, 1);
159 if (!found) {
160 LOG_ERROR("no device found");
161 return false;
164 err = libusb_get_config_descriptor(libusb_get_device(ctx->usb_dev), 0, &config0);
165 if (err != LIBUSB_SUCCESS) {
166 LOG_ERROR("libusb_get_config_descriptor() failed with %d", err);
167 libusb_close(ctx->usb_dev);
168 return false;
171 /* Make sure the first configuration is selected */
172 int cfg;
173 err = libusb_get_configuration(ctx->usb_dev, &cfg);
174 if (err != LIBUSB_SUCCESS) {
175 LOG_ERROR("libusb_get_configuration() failed with %d", err);
176 goto error;
179 if (desc.bNumConfigurations > 0 && cfg != config0->bConfigurationValue) {
180 err = libusb_set_configuration(ctx->usb_dev, config0->bConfigurationValue);
181 if (err != LIBUSB_SUCCESS) {
182 LOG_ERROR("libusb_set_configuration() failed with %d", err);
183 goto error;
187 /* Try to detach ftdi_sio kernel module */
188 err = libusb_detach_kernel_driver(ctx->usb_dev, ctx->interface);
189 if (err != LIBUSB_SUCCESS && err != LIBUSB_ERROR_NOT_FOUND
190 && err != LIBUSB_ERROR_NOT_SUPPORTED) {
191 LOG_ERROR("libusb_detach_kernel_driver() failed with %d", err);
192 goto error;
195 err = libusb_claim_interface(ctx->usb_dev, ctx->interface);
196 if (err != LIBUSB_SUCCESS) {
197 LOG_ERROR("libusb_claim_interface() failed with %d", err);
198 goto error;
201 /* Reset FTDI device */
202 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
203 SIO_RESET_REQUEST, SIO_RESET_SIO,
204 ctx->index, NULL, 0, ctx->usb_write_timeout);
205 if (err < 0) {
206 LOG_ERROR("failed to reset FTDI device: %d", err);
207 goto error;
210 switch (desc.bcdDevice) {
211 case 0x500:
212 ctx->type = TYPE_FT2232C;
213 break;
214 case 0x700:
215 ctx->type = TYPE_FT2232H;
216 break;
217 case 0x800:
218 ctx->type = TYPE_FT4232H;
219 break;
220 case 0x900:
221 ctx->type = TYPE_FT232H;
222 break;
223 default:
224 LOG_ERROR("unsupported FTDI chip type: 0x%04x", desc.bcdDevice);
225 goto error;
228 /* Determine maximum packet size and endpoint addresses */
229 if (!(desc.bNumConfigurations > 0 && ctx->interface < config0->bNumInterfaces
230 && config0->interface[ctx->interface].num_altsetting > 0))
231 goto desc_error;
233 const struct libusb_interface_descriptor *descriptor;
234 descriptor = &config0->interface[ctx->interface].altsetting[0];
235 if (descriptor->bNumEndpoints != 2)
236 goto desc_error;
238 ctx->in_ep = 0;
239 ctx->out_ep = 0;
240 for (int i = 0; i < descriptor->bNumEndpoints; i++) {
241 if (descriptor->endpoint[i].bEndpointAddress & 0x80) {
242 ctx->in_ep = descriptor->endpoint[i].bEndpointAddress;
243 ctx->max_packet_size =
244 descriptor->endpoint[i].wMaxPacketSize;
245 } else {
246 ctx->out_ep = descriptor->endpoint[i].bEndpointAddress;
250 if (ctx->in_ep == 0 || ctx->out_ep == 0)
251 goto desc_error;
253 libusb_free_config_descriptor(config0);
254 return true;
256 desc_error:
257 LOG_ERROR("unrecognized USB device descriptor");
258 error:
259 libusb_free_config_descriptor(config0);
260 libusb_close(ctx->usb_dev);
261 return false;
264 struct mpsse_ctx *mpsse_open(const uint16_t *vid, const uint16_t *pid, const char *description,
265 const char *serial, int channel)
267 struct mpsse_ctx *ctx = calloc(1, sizeof(*ctx));
268 int err;
270 if (!ctx)
271 return 0;
273 bit_copy_queue_init(&ctx->read_queue);
274 ctx->read_chunk_size = 16384;
275 ctx->read_size = 16384;
276 ctx->write_size = 16384;
277 ctx->read_chunk = malloc(ctx->read_chunk_size);
278 ctx->read_buffer = malloc(ctx->read_size);
279 ctx->write_buffer = malloc(ctx->write_size);
280 if (!ctx->read_chunk || !ctx->read_buffer || !ctx->write_buffer)
281 goto error;
283 ctx->interface = channel;
284 ctx->index = channel + 1;
285 ctx->usb_read_timeout = 5000;
286 ctx->usb_write_timeout = 5000;
288 err = libusb_init(&ctx->usb_ctx);
289 if (err != LIBUSB_SUCCESS) {
290 LOG_ERROR("libusb_init() failed with %d", err);
291 goto error;
294 if (!open_matching_device(ctx, vid, pid, description, serial)) {
295 /* Four hex digits plus terminating zero each */
296 char vidstr[5];
297 char pidstr[5];
298 LOG_ERROR("unable to open ftdi device with vid %s, pid %s, description '%s' and "
299 "serial '%s'",
300 vid ? sprintf(vidstr, "%04x", *vid), vidstr : "*",
301 pid ? sprintf(pidstr, "%04x", *pid), pidstr : "*",
302 description ? description : "*",
303 serial ? serial : "*");
304 ctx->usb_dev = 0;
305 goto error;
308 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
309 SIO_SET_LATENCY_TIMER_REQUEST, 255, ctx->index, NULL, 0,
310 ctx->usb_write_timeout);
311 if (err < 0) {
312 LOG_ERROR("unable to set latency timer: %d", err);
313 goto error;
316 err = libusb_control_transfer(ctx->usb_dev,
317 FTDI_DEVICE_OUT_REQTYPE,
318 SIO_SET_BITMODE_REQUEST,
319 0x0b | (BITMODE_RESET << 8),
320 ctx->index,
321 NULL,
323 ctx->usb_write_timeout);
324 if (err < 0) {
325 LOG_ERROR("unable to reset bitmode: %d", err);
326 goto error;
329 err = libusb_control_transfer(ctx->usb_dev,
330 FTDI_DEVICE_OUT_REQTYPE,
331 SIO_SET_BITMODE_REQUEST,
332 0x0b | (BITMODE_MPSSE << 8),
333 ctx->index,
334 NULL,
336 ctx->usb_write_timeout);
337 if (err < 0) {
338 LOG_ERROR("unable to set MPSSE bitmode: %d", err);
339 goto error;
342 mpsse_purge(ctx);
344 return ctx;
345 error:
346 mpsse_close(ctx);
347 return 0;
350 void mpsse_close(struct mpsse_ctx *ctx)
352 if (ctx->usb_dev)
353 libusb_close(ctx->usb_dev);
354 if (ctx->usb_ctx)
355 libusb_exit(ctx->usb_ctx);
356 bit_copy_discard(&ctx->read_queue);
357 if (ctx->write_buffer)
358 free(ctx->write_buffer);
359 if (ctx->read_buffer)
360 free(ctx->read_buffer);
361 if (ctx->read_chunk)
362 free(ctx->read_chunk);
364 free(ctx);
367 bool mpsse_is_high_speed(struct mpsse_ctx *ctx)
369 return ctx->type != TYPE_FT2232C;
372 void mpsse_purge(struct mpsse_ctx *ctx)
374 int err;
375 LOG_DEBUG("-");
376 ctx->write_count = 0;
377 ctx->read_count = 0;
378 bit_copy_discard(&ctx->read_queue);
379 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
380 SIO_RESET_PURGE_RX, ctx->index, NULL, 0, ctx->usb_write_timeout);
381 if (err < 0) {
382 LOG_ERROR("unable to purge ftdi rx buffers: %d", err);
383 return;
386 err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
387 SIO_RESET_PURGE_TX, ctx->index, NULL, 0, ctx->usb_write_timeout);
388 if (err < 0) {
389 LOG_ERROR("unable to purge ftdi tx buffers: %d", err);
390 return;
394 static unsigned buffer_write_space(struct mpsse_ctx *ctx)
396 /* Reserve one byte for SEND_IMMEDIATE */
397 return ctx->write_size - ctx->write_count - 1;
400 static unsigned buffer_read_space(struct mpsse_ctx *ctx)
402 return ctx->read_size - ctx->read_count;
405 static void buffer_write_byte(struct mpsse_ctx *ctx, uint8_t data)
407 DEBUG_IO("%02x", data);
408 assert(ctx->write_count < ctx->write_size);
409 ctx->write_buffer[ctx->write_count++] = data;
412 static unsigned buffer_write(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
413 unsigned bit_count)
415 DEBUG_IO("%d bits", bit_count);
416 assert(ctx->write_count + DIV_ROUND_UP(bit_count, 8) <= ctx->write_size);
417 bit_copy(ctx->write_buffer + ctx->write_count, 0, out, out_offset, bit_count);
418 ctx->write_count += DIV_ROUND_UP(bit_count, 8);
419 return bit_count;
422 static unsigned buffer_add_read(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset,
423 unsigned bit_count, unsigned offset)
425 DEBUG_IO("%d bits, offset %d", bit_count, offset);
426 assert(ctx->read_count + DIV_ROUND_UP(bit_count, 8) <= ctx->read_size);
427 bit_copy_queued(&ctx->read_queue, in, in_offset, ctx->read_buffer + ctx->read_count, offset,
428 bit_count);
429 ctx->read_count += DIV_ROUND_UP(bit_count, 8);
430 return bit_count;
433 int mpsse_clock_data_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
434 unsigned length, uint8_t mode)
436 return mpsse_clock_data(ctx, out, out_offset, 0, 0, length, mode);
439 int mpsse_clock_data_in(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset, unsigned length,
440 uint8_t mode)
442 return mpsse_clock_data(ctx, 0, 0, in, in_offset, length, mode);
445 int mpsse_clock_data(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset, uint8_t *in,
446 unsigned in_offset, unsigned length, uint8_t mode)
448 /* TODO: Fix MSB first modes */
449 DEBUG_IO("%s%s %d bits", in ? "in" : "", out ? "out" : "", length);
450 int retval = ERROR_OK;
452 /* TODO: On H chips, use command 0x8E/0x8F if in and out are both 0 */
453 if (out || (!out && !in))
454 mode |= 0x10;
455 if (in)
456 mode |= 0x20;
458 while (length > 0) {
459 /* Guarantee buffer space enough for a minimum size transfer */
460 if (buffer_write_space(ctx) + (length < 8) < (out || (!out && !in) ? 4 : 3)
461 || (in && buffer_read_space(ctx) < 1))
462 retval = mpsse_flush(ctx);
464 if (length < 8) {
465 /* Transfer remaining bits in bit mode */
466 buffer_write_byte(ctx, 0x02 | mode);
467 buffer_write_byte(ctx, length - 1);
468 if (out)
469 out_offset += buffer_write(ctx, out, out_offset, length);
470 if (in)
471 in_offset += buffer_add_read(ctx, in, in_offset, length, 8 - length);
472 if (!out && !in)
473 buffer_write_byte(ctx, 0x00);
474 length = 0;
475 } else {
476 /* Byte transfer */
477 unsigned this_bytes = length / 8;
478 /* MPSSE command limit */
479 if (this_bytes > 65536)
480 this_bytes = 65536;
481 /* Buffer space limit. We already made sure there's space for the minimum
482 * transfer. */
483 if ((out || (!out && !in)) && this_bytes + 3 > buffer_write_space(ctx))
484 this_bytes = buffer_write_space(ctx) - 3;
485 if (in && this_bytes > buffer_read_space(ctx))
486 this_bytes = buffer_read_space(ctx);
488 if (this_bytes > 0) {
489 buffer_write_byte(ctx, mode);
490 buffer_write_byte(ctx, (this_bytes - 1) & 0xff);
491 buffer_write_byte(ctx, (this_bytes - 1) >> 8);
492 if (out)
493 out_offset += buffer_write(ctx,
494 out,
495 out_offset,
496 this_bytes * 8);
497 if (in)
498 in_offset += buffer_add_read(ctx,
500 in_offset,
501 this_bytes * 8,
503 if (!out && !in)
504 for (unsigned n = 0; n < this_bytes; n++)
505 buffer_write_byte(ctx, 0x00);
506 length -= this_bytes * 8;
510 return retval;
513 int mpsse_clock_tms_cs_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
514 unsigned length, bool tdi, uint8_t mode)
516 return mpsse_clock_tms_cs(ctx, out, out_offset, 0, 0, length, tdi, mode);
519 int mpsse_clock_tms_cs(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset, uint8_t *in,
520 unsigned in_offset, unsigned length, bool tdi, uint8_t mode)
522 DEBUG_IO("%sout %d bits, tdi=%d", in ? "in" : "", length, tdi);
523 assert(out);
524 int retval = ERROR_OK;
526 mode |= 0x42;
527 if (in)
528 mode |= 0x20;
530 while (length > 0) {
531 /* Guarantee buffer space enough for a minimum size transfer */
532 if (buffer_write_space(ctx) < 3 || (in && buffer_read_space(ctx) < 1))
533 retval = mpsse_flush(ctx);
535 /* Byte transfer */
536 unsigned this_bits = length;
537 /* MPSSE command limit */
538 /* NOTE: there's a report of an FT2232 bug in this area, where shifting
539 * exactly 7 bits can make problems with TMS signaling for the last
540 * clock cycle:
542 * http://developer.intra2net.com/mailarchive/html/libftdi/2009/msg00292.html
544 if (this_bits > 7)
545 this_bits = 7;
547 if (this_bits > 0) {
548 buffer_write_byte(ctx, mode);
549 buffer_write_byte(ctx, this_bits - 1);
550 uint8_t data = 0;
551 /* TODO: Fix MSB first, if allowed in MPSSE */
552 bit_copy(&data, 0, out, out_offset, this_bits);
553 out_offset += this_bits;
554 buffer_write_byte(ctx, data | (tdi ? 0x80 : 0x00));
555 if (in)
556 in_offset += buffer_add_read(ctx,
558 in_offset,
559 this_bits,
560 8 - this_bits);
561 length -= this_bits;
564 return retval;
567 int mpsse_set_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
569 DEBUG_IO("-");
570 int retval = ERROR_OK;
572 if (buffer_write_space(ctx) < 3)
573 retval = mpsse_flush(ctx);
575 buffer_write_byte(ctx, 0x80);
576 buffer_write_byte(ctx, data);
577 buffer_write_byte(ctx, dir);
579 return retval;
582 int mpsse_set_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
584 DEBUG_IO("-");
585 int retval = ERROR_OK;
587 if (buffer_write_space(ctx) < 3)
588 retval = mpsse_flush(ctx);
590 buffer_write_byte(ctx, 0x82);
591 buffer_write_byte(ctx, data);
592 buffer_write_byte(ctx, dir);
594 return retval;
597 int mpsse_read_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t *data)
599 DEBUG_IO("-");
600 int retval = ERROR_OK;
602 if (buffer_write_space(ctx) < 1)
603 retval = mpsse_flush(ctx);
605 buffer_write_byte(ctx, 0x81);
606 buffer_add_read(ctx, data, 0, 8, 0);
608 return retval;
611 int mpsse_read_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t *data)
613 DEBUG_IO("-");
614 int retval = ERROR_OK;
616 if (buffer_write_space(ctx) < 1)
617 retval = mpsse_flush(ctx);
619 buffer_write_byte(ctx, 0x83);
620 buffer_add_read(ctx, data, 0, 8, 0);
622 return retval;
625 static int single_byte_boolean_helper(struct mpsse_ctx *ctx, bool var, uint8_t val_if_true,
626 uint8_t val_if_false)
628 int retval = ERROR_OK;
630 if (buffer_write_space(ctx) < 1)
631 retval = mpsse_flush(ctx);
633 buffer_write_byte(ctx, var ? val_if_true : val_if_false);
635 return retval;
638 int mpsse_loopback_config(struct mpsse_ctx *ctx, bool enable)
640 LOG_DEBUG("%s", enable ? "on" : "off");
641 return single_byte_boolean_helper(ctx, enable, 0x84, 0x85);
644 int mpsse_set_divisor(struct mpsse_ctx *ctx, uint16_t divisor)
646 LOG_DEBUG("%d", divisor);
647 int retval = ERROR_OK;
649 if (buffer_write_space(ctx) < 3)
650 retval = mpsse_flush(ctx);
652 buffer_write_byte(ctx, 0x86);
653 buffer_write_byte(ctx, divisor & 0xff);
654 buffer_write_byte(ctx, divisor >> 8);
656 return retval;
659 int mpsse_divide_by_5_config(struct mpsse_ctx *ctx, bool enable)
661 if (!mpsse_is_high_speed(ctx))
662 return ERROR_FAIL;
664 LOG_DEBUG("%s", enable ? "on" : "off");
666 return single_byte_boolean_helper(ctx, enable, 0x8b, 0x8a);
669 int mpsse_rtck_config(struct mpsse_ctx *ctx, bool enable)
671 if (!mpsse_is_high_speed(ctx))
672 return ERROR_FAIL;
674 LOG_DEBUG("%s", enable ? "on" : "off");
676 return single_byte_boolean_helper(ctx, enable, 0x96, 0x97);
679 int mpsse_set_frequency(struct mpsse_ctx *ctx, int frequency)
681 LOG_DEBUG("target %d Hz", frequency);
682 assert(frequency >= 0);
683 int base_clock;
685 if (frequency == 0)
686 return mpsse_rtck_config(ctx, true);
688 mpsse_rtck_config(ctx, false); /* just try */
690 if (frequency > 60000000 / 2 / 65536 && mpsse_is_high_speed(ctx)) {
691 int retval = mpsse_divide_by_5_config(ctx, false);
692 if (retval != ERROR_OK)
693 return retval;
694 base_clock = 60000000;
695 } else {
696 mpsse_divide_by_5_config(ctx, true); /* just try */
697 base_clock = 12000000;
700 int divisor = (base_clock / 2 + frequency - 1) / frequency - 1;
701 if (divisor > 65535)
702 divisor = 65535;
703 assert(divisor >= 0);
705 int retval = mpsse_set_divisor(ctx, divisor);
706 if (retval != ERROR_OK)
707 return retval;
709 frequency = base_clock / 2 / (1 + divisor);
710 LOG_DEBUG("actually %d Hz", frequency);
712 return frequency;
715 /* Context needed by the callbacks */
716 struct transfer_result {
717 struct mpsse_ctx *ctx;
718 bool done;
719 unsigned transferred;
722 static LIBUSB_CALL void read_cb(struct libusb_transfer *transfer)
724 struct transfer_result *res = (struct transfer_result *)transfer->user_data;
725 struct mpsse_ctx *ctx = res->ctx;
727 unsigned packet_size = ctx->max_packet_size;
729 DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
731 /* Strip the two status bytes sent at the beginning of each USB packet
732 * while copying the chunk buffer to the read buffer */
733 unsigned num_packets = DIV_ROUND_UP(transfer->actual_length, packet_size);
734 unsigned chunk_remains = transfer->actual_length;
735 for (unsigned i = 0; i < num_packets && chunk_remains > 2; i++) {
736 unsigned this_size = packet_size - 2;
737 if (this_size > chunk_remains - 2)
738 this_size = chunk_remains - 2;
739 if (this_size > ctx->read_count - res->transferred)
740 this_size = ctx->read_count - res->transferred;
741 memcpy(ctx->read_buffer + res->transferred,
742 ctx->read_chunk + packet_size * i + 2,
743 this_size);
744 res->transferred += this_size;
745 chunk_remains -= this_size + 2;
746 if (res->transferred == ctx->read_count) {
747 res->done = true;
748 break;
752 DEBUG_IO("raw chunk %d, transferred %d of %d", transfer->actual_length, res->transferred,
753 ctx->read_count);
755 if (!res->done)
756 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
757 res->done = true;
760 static LIBUSB_CALL void write_cb(struct libusb_transfer *transfer)
762 struct transfer_result *res = (struct transfer_result *)transfer->user_data;
763 struct mpsse_ctx *ctx = res->ctx;
765 res->transferred += transfer->actual_length;
767 DEBUG_IO("transferred %d of %d", res->transferred, ctx->write_count);
769 DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
771 if (res->transferred == ctx->write_count)
772 res->done = true;
773 else {
774 transfer->length = ctx->write_count - res->transferred;
775 transfer->buffer = ctx->write_buffer + res->transferred;
776 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
777 res->done = true;
781 int mpsse_flush(struct mpsse_ctx *ctx)
783 DEBUG_IO("write %d%s, read %d", ctx->write_count, ctx->read_count ? "+1" : "",
784 ctx->read_count);
785 assert(ctx->write_count > 0 || ctx->read_count == 0); /* No read data without write data */
786 int retval = ERROR_OK;
788 if (ctx->write_count == 0)
789 return retval;
791 struct libusb_transfer *read_transfer = 0;
792 struct transfer_result read_result = { .ctx = ctx, .done = true };
793 if (ctx->read_count) {
794 buffer_write_byte(ctx, 0x87); /* SEND_IMMEDIATE */
795 read_result.done = false;
796 read_transfer = libusb_alloc_transfer(0);
797 libusb_fill_bulk_transfer(read_transfer, ctx->usb_dev, ctx->in_ep, ctx->read_chunk,
798 ctx->read_chunk_size, read_cb, &read_result,
799 ctx->usb_read_timeout);
800 retval = libusb_submit_transfer(read_transfer);
803 struct transfer_result write_result = { .ctx = ctx, .done = false };
804 struct libusb_transfer *write_transfer = libusb_alloc_transfer(0);
805 libusb_fill_bulk_transfer(write_transfer, ctx->usb_dev, ctx->out_ep, ctx->write_buffer,
806 ctx->write_count, write_cb, &write_result, ctx->usb_write_timeout);
807 retval = libusb_submit_transfer(write_transfer);
809 /* Polling loop, more or less taken from libftdi */
810 while (!write_result.done || !read_result.done) {
811 retval = libusb_handle_events(ctx->usb_ctx);
812 keep_alive();
813 if (retval != LIBUSB_SUCCESS && retval != LIBUSB_ERROR_INTERRUPTED) {
814 libusb_cancel_transfer(write_transfer);
815 if (read_transfer)
816 libusb_cancel_transfer(read_transfer);
817 while (!write_result.done || !read_result.done)
818 if (libusb_handle_events(ctx->usb_ctx) != LIBUSB_SUCCESS)
819 break;
823 if (retval != LIBUSB_SUCCESS) {
824 LOG_ERROR("libusb_handle_events() failed with %d", retval);
825 retval = ERROR_FAIL;
826 } else if (write_result.transferred < ctx->write_count) {
827 LOG_ERROR("ftdi device did not accept all data: %d, tried %d",
828 write_result.transferred,
829 ctx->write_count);
830 retval = ERROR_FAIL;
831 } else if (read_result.transferred < ctx->read_count) {
832 LOG_ERROR("ftdi device did not return all data: %d, expected %d",
833 read_result.transferred,
834 ctx->read_count);
835 retval = ERROR_FAIL;
836 } else if (ctx->read_count) {
837 ctx->write_count = 0;
838 ctx->read_count = 0;
839 bit_copy_execute(&ctx->read_queue);
840 retval = ERROR_OK;
841 } else {
842 ctx->write_count = 0;
843 bit_copy_discard(&ctx->read_queue);
844 retval = ERROR_OK;
847 libusb_free_transfer(write_transfer);
848 if (read_transfer)
849 libusb_free_transfer(read_transfer);
851 if (retval != ERROR_OK)
852 mpsse_purge(ctx);
854 return retval;