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