1db8af91960ad71e730989acfbf3e428cad5f0fd
[fw/openocd] / src / jtag / drivers / mpsse.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 /**************************************************************************
4  *   Copyright (C) 2012 by Andreas Fritiofson                              *
5  *   andreas.fritiofson@gmail.com                                          *
6  ***************************************************************************/
7
8 #ifdef HAVE_CONFIG_H
9 #include "config.h"
10 #endif
11
12 #include "mpsse.h"
13 #include "helper/log.h"
14 #include "helper/replacements.h"
15 #include "helper/time_support.h"
16 #include <libusb.h>
17
18 /* Compatibility define for older libusb-1.0 */
19 #ifndef LIBUSB_CALL
20 #define LIBUSB_CALL
21 #endif
22
23 #define DEBUG_PRINT_BUF(buf, len) \
24         do { \
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); \
32                                         buf_string_pos = 0; \
33                                 } \
34                         } \
35                         if (buf_string_pos > 0) \
36                                 LOG_DEBUG_IO("%s", buf_string);\
37                 } \
38         } while (0)
39
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)
42
43 #define BITMODE_MPSSE 0x02
44
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
49
50 #define SIO_RESET_SIO 0
51 #define SIO_RESET_PURGE_RX 1
52 #define SIO_RESET_PURGE_TX 2
53
54 struct mpsse_ctx {
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;
59         uint8_t in_ep;
60         uint8_t out_ep;
61         uint16_t max_packet_size;
62         uint16_t index;
63         uint8_t interface;
64         enum ftdi_chip_type type;
65         uint8_t *write_buffer;
66         unsigned write_size;
67         unsigned write_count;
68         uint8_t *read_buffer;
69         unsigned read_size;
70         unsigned read_count;
71         uint8_t *read_chunk;
72         unsigned read_chunk_size;
73         struct bit_copy_queue read_queue;
74         int retval;
75 };
76
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,
79         const char *string)
80 {
81         int retval;
82         char desc_string[256]; /* Max size of string descriptor */
83         retval = libusb_get_string_descriptor_ascii(device, str_index, (unsigned char *)desc_string,
84                         sizeof(desc_string));
85         if (retval < 0) {
86                 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %s", libusb_error_name(retval));
87                 return false;
88         }
89         return strncmp(string, desc_string, sizeof(desc_string)) == 0;
90 }
91
92 static bool device_location_equal(struct libusb_device *device, const char *location)
93 {
94         bool result = false;
95 #ifdef HAVE_LIBUSB_GET_PORT_NUMBERS
96         char *loc = strdup(location);
97         uint8_t port_path[7];
98         int path_step, path_len;
99         uint8_t dev_bus = libusb_get_bus_number(device);
100         char *ptr;
101
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)");
105                 goto done;
106         }
107
108         LOG_DEBUG("device path has %i steps", path_len);
109
110         ptr = strtok(loc, "-:");
111         if (!ptr) {
112                 LOG_DEBUG("no ':' in path");
113                 goto done;
114         }
115         if (atoi(ptr) != dev_bus) {
116                 LOG_DEBUG("bus mismatch");
117                 goto done;
118         }
119
120         path_step = 0;
121         while (path_step < 7) {
122                 ptr = strtok(NULL, ".,");
123                 if (!ptr) {
124                         LOG_DEBUG("no more tokens in path at step %i", path_step);
125                         break;
126                 }
127
128                 if (path_step < path_len
129                         && atoi(ptr) != port_path[path_step]) {
130                         LOG_DEBUG("path mismatch at step %i", path_step);
131                         break;
132                 }
133
134                 path_step++;
135         };
136
137         /* walked the full path, all elements match */
138         if (path_step == path_len)
139                 result = true;
140
141  done:
142         free(loc);
143 #endif
144         return result;
145 }
146
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)
153 {
154         struct libusb_device **list;
155         struct libusb_device_descriptor desc;
156         struct libusb_config_descriptor *config0;
157         int err;
158         bool found = false;
159         ssize_t cnt = libusb_get_device_list(ctx->usb_ctx, &list);
160         if (cnt < 0)
161                 LOG_ERROR("libusb_get_device_list() failed with %s", libusb_error_name(cnt));
162
163         for (ssize_t i = 0; i < cnt; i++) {
164                 struct libusb_device *device = list[i];
165
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));
169                         continue;
170                 }
171
172                 if (vid && *vid != desc.idVendor)
173                         continue;
174                 if (pid && *pid != desc.idProduct)
175                         continue;
176
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));
181                         continue;
182                 }
183
184                 if (location && !device_location_equal(device, location)) {
185                         libusb_close(ctx->usb_dev);
186                         continue;
187                 }
188
189                 if (product && !string_descriptor_equal(ctx->usb_dev, desc.iProduct, product)) {
190                         libusb_close(ctx->usb_dev);
191                         continue;
192                 }
193
194                 if (serial && !string_descriptor_equal(ctx->usb_dev, desc.iSerialNumber, serial)) {
195                         libusb_close(ctx->usb_dev);
196                         continue;
197                 }
198
199                 found = true;
200                 break;
201         }
202
203         libusb_free_device_list(list, 1);
204
205         if (!found) {
206                 LOG_ERROR("no device found");
207                 return false;
208         }
209
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);
214                 return false;
215         }
216
217         /* Make sure the first configuration is selected */
218         int cfg;
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));
222                 goto error;
223         }
224
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));
229                         goto error;
230                 }
231         }
232
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));
239         }
240
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));
244                 goto error;
245         }
246
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);
251         if (err < 0) {
252                 LOG_ERROR("failed to reset FTDI device: %s", libusb_error_name(err));
253                 goto error;
254         }
255
256         switch (desc.bcdDevice) {
257         case 0x500:
258                 ctx->type = TYPE_FT2232C;
259                 break;
260         case 0x700:
261                 ctx->type = TYPE_FT2232H;
262                 break;
263         case 0x800:
264                 ctx->type = TYPE_FT4232H;
265                 break;
266         case 0x900:
267                 ctx->type = TYPE_FT232H;
268                 break;
269         default:
270                 LOG_ERROR("unsupported FTDI chip type: 0x%04x", desc.bcdDevice);
271                 goto error;
272         }
273
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))
277                 goto desc_error;
278
279         const struct libusb_interface_descriptor *descriptor;
280         descriptor = &config0->interface[ctx->interface].altsetting[0];
281         if (descriptor->bNumEndpoints != 2)
282                 goto desc_error;
283
284         ctx->in_ep = 0;
285         ctx->out_ep = 0;
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;
291                 } else {
292                         ctx->out_ep = descriptor->endpoint[i].bEndpointAddress;
293                 }
294         }
295
296         if (ctx->in_ep == 0 || ctx->out_ep == 0)
297                 goto desc_error;
298
299         libusb_free_config_descriptor(config0);
300         return true;
301
302 desc_error:
303         LOG_ERROR("unrecognized USB device descriptor");
304 error:
305         libusb_free_config_descriptor(config0);
306         libusb_close(ctx->usb_dev);
307         return false;
308 }
309
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)
312 {
313         struct mpsse_ctx *ctx = calloc(1, sizeof(*ctx));
314         int err;
315
316         if (!ctx)
317                 return 0;
318
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);
325
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);
331
332         if (!ctx->read_chunk || !ctx->read_buffer || !ctx->write_buffer)
333                 goto error;
334
335         ctx->interface = channel;
336         ctx->index = channel + 1;
337         ctx->usb_read_timeout = 5000;
338         ctx->usb_write_timeout = 5000;
339
340         err = libusb_init(&ctx->usb_ctx);
341         if (err != LIBUSB_SUCCESS) {
342                 LOG_ERROR("libusb_init() failed with %s", libusb_error_name(err));
343                 goto error;
344         }
345
346         if (!open_matching_device(ctx, vid, pid, description, serial, location)) {
347                 /* Four hex digits plus terminating zero each */
348                 char vidstr[5];
349                 char pidstr[5];
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 : "*");
357                 ctx->usb_dev = 0;
358                 goto error;
359         }
360
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);
364         if (err < 0) {
365                 LOG_ERROR("unable to set latency timer: %s", libusb_error_name(err));
366                 goto error;
367         }
368
369         err = libusb_control_transfer(ctx->usb_dev,
370                         FTDI_DEVICE_OUT_REQTYPE,
371                         SIO_SET_BITMODE_REQUEST,
372                         0x0b | (BITMODE_MPSSE << 8),
373                         ctx->index,
374                         NULL,
375                         0,
376                         ctx->usb_write_timeout);
377         if (err < 0) {
378                 LOG_ERROR("unable to set MPSSE bitmode: %s", libusb_error_name(err));
379                 goto error;
380         }
381
382         mpsse_purge(ctx);
383
384         return ctx;
385 error:
386         mpsse_close(ctx);
387         return 0;
388 }
389
390 void mpsse_close(struct mpsse_ctx *ctx)
391 {
392         if (ctx->usb_dev)
393                 libusb_close(ctx->usb_dev);
394         if (ctx->usb_ctx)
395                 libusb_exit(ctx->usb_ctx);
396         bit_copy_discard(&ctx->read_queue);
397
398         free(ctx->write_buffer);
399         free(ctx->read_buffer);
400         free(ctx->read_chunk);
401         free(ctx);
402 }
403
404 bool mpsse_is_high_speed(struct mpsse_ctx *ctx)
405 {
406         return ctx->type != TYPE_FT2232C;
407 }
408
409 void mpsse_purge(struct mpsse_ctx *ctx)
410 {
411         int err;
412         LOG_DEBUG("-");
413         ctx->write_count = 0;
414         ctx->read_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);
419         if (err < 0) {
420                 LOG_ERROR("unable to purge ftdi rx buffers: %s", libusb_error_name(err));
421                 return;
422         }
423
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);
426         if (err < 0) {
427                 LOG_ERROR("unable to purge ftdi tx buffers: %s", libusb_error_name(err));
428                 return;
429         }
430 }
431
432 static unsigned buffer_write_space(struct mpsse_ctx *ctx)
433 {
434         /* Reserve one byte for SEND_IMMEDIATE */
435         return ctx->write_size - ctx->write_count - 1;
436 }
437
438 static unsigned buffer_read_space(struct mpsse_ctx *ctx)
439 {
440         return ctx->read_size - ctx->read_count;
441 }
442
443 static void buffer_write_byte(struct mpsse_ctx *ctx, uint8_t data)
444 {
445         LOG_DEBUG_IO("%02x", data);
446         assert(ctx->write_count < ctx->write_size);
447         ctx->write_buffer[ctx->write_count++] = data;
448 }
449
450 static unsigned buffer_write(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
451         unsigned bit_count)
452 {
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);
457         return bit_count;
458 }
459
460 static unsigned buffer_add_read(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset,
461         unsigned bit_count, unsigned offset)
462 {
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,
466                 bit_count);
467         ctx->read_count += DIV_ROUND_UP(bit_count, 8);
468         return bit_count;
469 }
470
471 void mpsse_clock_data_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
472         unsigned length, uint8_t mode)
473 {
474         mpsse_clock_data(ctx, out, out_offset, 0, 0, length, mode);
475 }
476
477 void mpsse_clock_data_in(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset, unsigned length,
478         uint8_t mode)
479 {
480         mpsse_clock_data(ctx, 0, 0, in, in_offset, length, mode);
481 }
482
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)
485 {
486         /* TODO: Fix MSB first modes */
487         LOG_DEBUG_IO("%s%s %d bits", in ? "in" : "", out ? "out" : "", length);
488
489         if (ctx->retval != ERROR_OK) {
490                 LOG_DEBUG_IO("Ignoring command due to previous error");
491                 return;
492         }
493
494         /* TODO: On H chips, use command 0x8E/0x8F if in and out are both 0 */
495         if (out || (!out && !in))
496                 mode |= 0x10;
497         if (in)
498                 mode |= 0x20;
499
500         while (length > 0) {
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);
505
506                 if (length < 8) {
507                         /* Transfer remaining bits in bit mode */
508                         buffer_write_byte(ctx, 0x02 | mode);
509                         buffer_write_byte(ctx, length - 1);
510                         if (out)
511                                 out_offset += buffer_write(ctx, out, out_offset, length);
512                         if (in)
513                                 in_offset += buffer_add_read(ctx, in, in_offset, length, 8 - length);
514                         if (!out && !in)
515                                 buffer_write_byte(ctx, 0x00);
516                         length = 0;
517                 } else {
518                         /* Byte transfer */
519                         unsigned this_bytes = length / 8;
520                         /* MPSSE command limit */
521                         if (this_bytes > 65536)
522                                 this_bytes = 65536;
523                         /* Buffer space limit. We already made sure there's space for the minimum
524                          * transfer. */
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);
529
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);
534                                 if (out)
535                                         out_offset += buffer_write(ctx,
536                                                         out,
537                                                         out_offset,
538                                                         this_bytes * 8);
539                                 if (in)
540                                         in_offset += buffer_add_read(ctx,
541                                                         in,
542                                                         in_offset,
543                                                         this_bytes * 8,
544                                                         0);
545                                 if (!out && !in)
546                                         for (unsigned n = 0; n < this_bytes; n++)
547                                                 buffer_write_byte(ctx, 0x00);
548                                 length -= this_bytes * 8;
549                         }
550                 }
551         }
552 }
553
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)
556 {
557         mpsse_clock_tms_cs(ctx, out, out_offset, 0, 0, length, tdi, mode);
558 }
559
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)
562 {
563         LOG_DEBUG_IO("%sout %d bits, tdi=%d", in ? "in" : "", length, tdi);
564         assert(out);
565
566         if (ctx->retval != ERROR_OK) {
567                 LOG_DEBUG_IO("Ignoring command due to previous error");
568                 return;
569         }
570
571         mode |= 0x42;
572         if (in)
573                 mode |= 0x20;
574
575         while (length > 0) {
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);
579
580                 /* Byte transfer */
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
585                  * clock cycle:
586                  *
587                  * http://developer.intra2net.com/mailarchive/html/libftdi/2009/msg00292.html
588                  */
589                 if (this_bits > 7)
590                         this_bits = 7;
591
592                 if (this_bits > 0) {
593                         buffer_write_byte(ctx, mode);
594                         buffer_write_byte(ctx, this_bits - 1);
595                         uint8_t data = 0;
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));
600                         if (in)
601                                 in_offset += buffer_add_read(ctx,
602                                                 in,
603                                                 in_offset,
604                                                 this_bits,
605                                                 8 - this_bits);
606                         length -= this_bits;
607                 }
608         }
609 }
610
611 void mpsse_set_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
612 {
613         LOG_DEBUG_IO("-");
614
615         if (ctx->retval != ERROR_OK) {
616                 LOG_DEBUG_IO("Ignoring command due to previous error");
617                 return;
618         }
619
620         if (buffer_write_space(ctx) < 3)
621                 ctx->retval = mpsse_flush(ctx);
622
623         buffer_write_byte(ctx, 0x80);
624         buffer_write_byte(ctx, data);
625         buffer_write_byte(ctx, dir);
626 }
627
628 void mpsse_set_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
629 {
630         LOG_DEBUG_IO("-");
631
632         if (ctx->retval != ERROR_OK) {
633                 LOG_DEBUG_IO("Ignoring command due to previous error");
634                 return;
635         }
636
637         if (buffer_write_space(ctx) < 3)
638                 ctx->retval = mpsse_flush(ctx);
639
640         buffer_write_byte(ctx, 0x82);
641         buffer_write_byte(ctx, data);
642         buffer_write_byte(ctx, dir);
643 }
644
645 void mpsse_read_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t *data)
646 {
647         LOG_DEBUG_IO("-");
648
649         if (ctx->retval != ERROR_OK) {
650                 LOG_DEBUG_IO("Ignoring command due to previous error");
651                 return;
652         }
653
654         if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
655                 ctx->retval = mpsse_flush(ctx);
656
657         buffer_write_byte(ctx, 0x81);
658         buffer_add_read(ctx, data, 0, 8, 0);
659 }
660
661 void mpsse_read_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t *data)
662 {
663         LOG_DEBUG_IO("-");
664
665         if (ctx->retval != ERROR_OK) {
666                 LOG_DEBUG_IO("Ignoring command due to previous error");
667                 return;
668         }
669
670         if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
671                 ctx->retval = mpsse_flush(ctx);
672
673         buffer_write_byte(ctx, 0x83);
674         buffer_add_read(ctx, data, 0, 8, 0);
675 }
676
677 static void single_byte_boolean_helper(struct mpsse_ctx *ctx, bool var, uint8_t val_if_true,
678         uint8_t val_if_false)
679 {
680         if (ctx->retval != ERROR_OK) {
681                 LOG_DEBUG_IO("Ignoring command due to previous error");
682                 return;
683         }
684
685         if (buffer_write_space(ctx) < 1)
686                 ctx->retval = mpsse_flush(ctx);
687
688         buffer_write_byte(ctx, var ? val_if_true : val_if_false);
689 }
690
691 void mpsse_loopback_config(struct mpsse_ctx *ctx, bool enable)
692 {
693         LOG_DEBUG("%s", enable ? "on" : "off");
694         single_byte_boolean_helper(ctx, enable, 0x84, 0x85);
695 }
696
697 void mpsse_set_divisor(struct mpsse_ctx *ctx, uint16_t divisor)
698 {
699         LOG_DEBUG("%d", divisor);
700
701         if (ctx->retval != ERROR_OK) {
702                 LOG_DEBUG_IO("Ignoring command due to previous error");
703                 return;
704         }
705
706         if (buffer_write_space(ctx) < 3)
707                 ctx->retval = mpsse_flush(ctx);
708
709         buffer_write_byte(ctx, 0x86);
710         buffer_write_byte(ctx, divisor & 0xff);
711         buffer_write_byte(ctx, divisor >> 8);
712 }
713
714 int mpsse_divide_by_5_config(struct mpsse_ctx *ctx, bool enable)
715 {
716         if (!mpsse_is_high_speed(ctx))
717                 return ERROR_FAIL;
718
719         LOG_DEBUG("%s", enable ? "on" : "off");
720         single_byte_boolean_helper(ctx, enable, 0x8b, 0x8a);
721
722         return ERROR_OK;
723 }
724
725 int mpsse_rtck_config(struct mpsse_ctx *ctx, bool enable)
726 {
727         if (!mpsse_is_high_speed(ctx))
728                 return ERROR_FAIL;
729
730         LOG_DEBUG("%s", enable ? "on" : "off");
731         single_byte_boolean_helper(ctx, enable, 0x96, 0x97);
732
733         return ERROR_OK;
734 }
735
736 int mpsse_set_frequency(struct mpsse_ctx *ctx, int frequency)
737 {
738         LOG_DEBUG("target %d Hz", frequency);
739         assert(frequency >= 0);
740         int base_clock;
741
742         if (frequency == 0)
743                 return mpsse_rtck_config(ctx, true);
744
745         mpsse_rtck_config(ctx, false); /* just try */
746
747         if (frequency > 60000000 / 2 / 65536 && mpsse_divide_by_5_config(ctx, false) == ERROR_OK) {
748                 base_clock = 60000000;
749         } else {
750                 mpsse_divide_by_5_config(ctx, true); /* just try */
751                 base_clock = 12000000;
752         }
753
754         int divisor = (base_clock / 2 + frequency - 1) / frequency - 1;
755         if (divisor > 65535)
756                 divisor = 65535;
757         assert(divisor >= 0);
758
759         mpsse_set_divisor(ctx, divisor);
760
761         frequency = base_clock / 2 / (1 + divisor);
762         LOG_DEBUG("actually %d Hz", frequency);
763
764         return frequency;
765 }
766
767 /* Context needed by the callbacks */
768 struct transfer_result {
769         struct mpsse_ctx *ctx;
770         bool done;
771         unsigned transferred;
772 };
773
774 static LIBUSB_CALL void read_cb(struct libusb_transfer *transfer)
775 {
776         struct transfer_result *res = transfer->user_data;
777         struct mpsse_ctx *ctx = res->ctx;
778
779         unsigned packet_size = ctx->max_packet_size;
780
781         DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
782
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,
795                         this_size);
796                 res->transferred += this_size;
797                 chunk_remains -= this_size + 2;
798                 if (res->transferred == ctx->read_count) {
799                         res->done = true;
800                         break;
801                 }
802         }
803
804         LOG_DEBUG_IO("raw chunk %d, transferred %d of %d", transfer->actual_length, res->transferred,
805                 ctx->read_count);
806
807         if (!res->done)
808                 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
809                         res->done = true;
810 }
811
812 static LIBUSB_CALL void write_cb(struct libusb_transfer *transfer)
813 {
814         struct transfer_result *res = transfer->user_data;
815         struct mpsse_ctx *ctx = res->ctx;
816
817         res->transferred += transfer->actual_length;
818
819         LOG_DEBUG_IO("transferred %d of %d", res->transferred, ctx->write_count);
820
821         DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
822
823         if (res->transferred == ctx->write_count)
824                 res->done = true;
825         else {
826                 transfer->length = ctx->write_count - res->transferred;
827                 transfer->buffer = ctx->write_buffer + res->transferred;
828                 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
829                         res->done = true;
830         }
831 }
832
833 int mpsse_flush(struct mpsse_ctx *ctx)
834 {
835         int retval = ctx->retval;
836
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;
841                 return retval;
842         }
843
844         LOG_DEBUG_IO("write %d%s, read %d", ctx->write_count, ctx->read_count ? "+1" : "",
845                         ctx->read_count);
846         assert(ctx->write_count > 0 || ctx->read_count == 0); /* No read data without write data */
847
848         if (ctx->write_count == 0)
849                 return retval;
850
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 */
858         }
859
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)
866                 goto error_check;
867
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)
875                         goto error_check;
876         }
877
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;
883
884                 timeout_usb.tv_sec = 1;
885                 timeout_usb.tv_usec = 0;
886
887                 retval = libusb_handle_events_timeout_completed(ctx->usb_ctx, &timeout_usb, NULL);
888                 keep_alive();
889                 if (retval == LIBUSB_ERROR_NO_DEVICE || retval == LIBUSB_ERROR_INTERRUPTED)
890                         break;
891
892                 if (retval != LIBUSB_SUCCESS) {
893                         libusb_cancel_transfer(write_transfer);
894                         if (read_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,
898                                                                 &timeout_usb, NULL);
899                                 if (retval != LIBUSB_SUCCESS)
900                                         break;
901                         }
902                 }
903
904                 int64_t now = timeval_ms();
905                 if (now - start > warn_after) {
906                         LOG_WARNING("Haven't made progress in mpsse_flush() for %" PRId64
907                                         "ms.", now - start);
908                         warn_after *= 2;
909                 }
910         }
911
912 error_check:
913         if (retval != LIBUSB_SUCCESS) {
914                 LOG_ERROR("libusb_handle_events() failed with %s", libusb_error_name(retval));
915                 retval = ERROR_FAIL;
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,
919                         ctx->write_count);
920                 retval = ERROR_FAIL;
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,
924                         ctx->read_count);
925                 retval = ERROR_FAIL;
926         } else if (ctx->read_count) {
927                 ctx->write_count = 0;
928                 ctx->read_count = 0;
929                 bit_copy_execute(&ctx->read_queue);
930                 retval = ERROR_OK;
931         } else {
932                 ctx->write_count = 0;
933                 bit_copy_discard(&ctx->read_queue);
934                 retval = ERROR_OK;
935         }
936
937         if (retval != ERROR_OK)
938                 mpsse_purge(ctx);
939
940         libusb_free_transfer(write_transfer);
941         if (read_transfer)
942                 libusb_free_transfer(read_transfer);
943
944         return retval;
945 }