0e3d2be0e0d778b1d06af6320a9fe6039bda5113
[fw/openocd] / 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, see <http://www.gnu.org/licenses/>. *
17  ***************************************************************************/
18
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
22
23 #include "mpsse.h"
24 #include "helper/log.h"
25 #include "helper/replacements.h"
26 #include "helper/time_support.h"
27 #include <libusb.h>
28
29 /* Compatibility define for older libusb-1.0 */
30 #ifndef LIBUSB_CALL
31 #define LIBUSB_CALL
32 #endif
33
34 #define DEBUG_PRINT_BUF(buf, len) \
35         do { \
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); \
43                                         buf_string_pos = 0; \
44                                 } \
45                         } \
46                         if (buf_string_pos > 0) \
47                                 LOG_DEBUG_IO("%s", buf_string);\
48                 } \
49         } while (0)
50
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)
53
54 #define BITMODE_MPSSE 0x02
55
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
60
61 #define SIO_RESET_SIO 0
62 #define SIO_RESET_PURGE_RX 1
63 #define SIO_RESET_PURGE_TX 2
64
65 struct mpsse_ctx {
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;
70         uint8_t in_ep;
71         uint8_t out_ep;
72         uint16_t max_packet_size;
73         uint16_t index;
74         uint8_t interface;
75         enum ftdi_chip_type type;
76         uint8_t *write_buffer;
77         unsigned write_size;
78         unsigned write_count;
79         uint8_t *read_buffer;
80         unsigned read_size;
81         unsigned read_count;
82         uint8_t *read_chunk;
83         unsigned read_chunk_size;
84         struct bit_copy_queue read_queue;
85         int retval;
86 };
87
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,
90         const char *string)
91 {
92         int retval;
93         char desc_string[256]; /* Max size of string descriptor */
94         retval = libusb_get_string_descriptor_ascii(device, str_index, (unsigned char *)desc_string,
95                         sizeof(desc_string));
96         if (retval < 0) {
97                 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %s", libusb_error_name(retval));
98                 return false;
99         }
100         return strncmp(string, desc_string, sizeof(desc_string)) == 0;
101 }
102
103 static bool device_location_equal(struct libusb_device *device, const char *location)
104 {
105         bool result = false;
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);
111         char *ptr;
112
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)");
116                 goto done;
117         }
118
119         LOG_DEBUG("device path has %i steps", path_len);
120
121         ptr = strtok(loc, "-:");
122         if (!ptr) {
123                 LOG_DEBUG("no ':' in path");
124                 goto done;
125         }
126         if (atoi(ptr) != dev_bus) {
127                 LOG_DEBUG("bus mismatch");
128                 goto done;
129         }
130
131         path_step = 0;
132         while (path_step < 7) {
133                 ptr = strtok(NULL, ".,");
134                 if (!ptr) {
135                         LOG_DEBUG("no more tokens in path at step %i", path_step);
136                         break;
137                 }
138
139                 if (path_step < path_len
140                         && atoi(ptr) != port_path[path_step]) {
141                         LOG_DEBUG("path mismatch at step %i", path_step);
142                         break;
143                 }
144
145                 path_step++;
146         };
147
148         /* walked the full path, all elements match */
149         if (path_step == path_len)
150                 result = true;
151
152  done:
153         free(loc);
154 #endif
155         return result;
156 }
157
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)
164 {
165         struct libusb_device **list;
166         struct libusb_device_descriptor desc;
167         struct libusb_config_descriptor *config0;
168         int err;
169         bool found = false;
170         ssize_t cnt = libusb_get_device_list(ctx->usb_ctx, &list);
171         if (cnt < 0)
172                 LOG_ERROR("libusb_get_device_list() failed with %s", libusb_error_name(cnt));
173
174         for (ssize_t i = 0; i < cnt; i++) {
175                 struct libusb_device *device = list[i];
176
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));
180                         continue;
181                 }
182
183                 if (vid && *vid != desc.idVendor)
184                         continue;
185                 if (pid && *pid != desc.idProduct)
186                         continue;
187
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));
192                         continue;
193                 }
194
195                 if (location && !device_location_equal(device, location)) {
196                         libusb_close(ctx->usb_dev);
197                         continue;
198                 }
199
200                 if (product && !string_descriptor_equal(ctx->usb_dev, desc.iProduct, product)) {
201                         libusb_close(ctx->usb_dev);
202                         continue;
203                 }
204
205                 if (serial && !string_descriptor_equal(ctx->usb_dev, desc.iSerialNumber, serial)) {
206                         libusb_close(ctx->usb_dev);
207                         continue;
208                 }
209
210                 found = true;
211                 break;
212         }
213
214         libusb_free_device_list(list, 1);
215
216         if (!found) {
217                 LOG_ERROR("no device found");
218                 return false;
219         }
220
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);
225                 return false;
226         }
227
228         /* Make sure the first configuration is selected */
229         int cfg;
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));
233                 goto error;
234         }
235
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));
240                         goto error;
241                 }
242         }
243
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));
250         }
251
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));
255                 goto error;
256         }
257
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);
262         if (err < 0) {
263                 LOG_ERROR("failed to reset FTDI device: %s", libusb_error_name(err));
264                 goto error;
265         }
266
267         switch (desc.bcdDevice) {
268         case 0x500:
269                 ctx->type = TYPE_FT2232C;
270                 break;
271         case 0x700:
272                 ctx->type = TYPE_FT2232H;
273                 break;
274         case 0x800:
275                 ctx->type = TYPE_FT4232H;
276                 break;
277         case 0x900:
278                 ctx->type = TYPE_FT232H;
279                 break;
280         default:
281                 LOG_ERROR("unsupported FTDI chip type: 0x%04x", desc.bcdDevice);
282                 goto error;
283         }
284
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))
288                 goto desc_error;
289
290         const struct libusb_interface_descriptor *descriptor;
291         descriptor = &config0->interface[ctx->interface].altsetting[0];
292         if (descriptor->bNumEndpoints != 2)
293                 goto desc_error;
294
295         ctx->in_ep = 0;
296         ctx->out_ep = 0;
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;
302                 } else {
303                         ctx->out_ep = descriptor->endpoint[i].bEndpointAddress;
304                 }
305         }
306
307         if (ctx->in_ep == 0 || ctx->out_ep == 0)
308                 goto desc_error;
309
310         libusb_free_config_descriptor(config0);
311         return true;
312
313 desc_error:
314         LOG_ERROR("unrecognized USB device descriptor");
315 error:
316         libusb_free_config_descriptor(config0);
317         libusb_close(ctx->usb_dev);
318         return false;
319 }
320
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)
323 {
324         struct mpsse_ctx *ctx = calloc(1, sizeof(*ctx));
325         int err;
326
327         if (!ctx)
328                 return 0;
329
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);
336
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);
342
343         if (!ctx->read_chunk || !ctx->read_buffer || !ctx->write_buffer)
344                 goto error;
345
346         ctx->interface = channel;
347         ctx->index = channel + 1;
348         ctx->usb_read_timeout = 5000;
349         ctx->usb_write_timeout = 5000;
350
351         err = libusb_init(&ctx->usb_ctx);
352         if (err != LIBUSB_SUCCESS) {
353                 LOG_ERROR("libusb_init() failed with %s", libusb_error_name(err));
354                 goto error;
355         }
356
357         if (!open_matching_device(ctx, vid, pid, description, serial, location)) {
358                 /* Four hex digits plus terminating zero each */
359                 char vidstr[5];
360                 char pidstr[5];
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 : "*");
368                 ctx->usb_dev = 0;
369                 goto error;
370         }
371
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);
375         if (err < 0) {
376                 LOG_ERROR("unable to set latency timer: %s", libusb_error_name(err));
377                 goto error;
378         }
379
380         err = libusb_control_transfer(ctx->usb_dev,
381                         FTDI_DEVICE_OUT_REQTYPE,
382                         SIO_SET_BITMODE_REQUEST,
383                         0x0b | (BITMODE_MPSSE << 8),
384                         ctx->index,
385                         NULL,
386                         0,
387                         ctx->usb_write_timeout);
388         if (err < 0) {
389                 LOG_ERROR("unable to set MPSSE bitmode: %s", libusb_error_name(err));
390                 goto error;
391         }
392
393         mpsse_purge(ctx);
394
395         return ctx;
396 error:
397         mpsse_close(ctx);
398         return 0;
399 }
400
401 void mpsse_close(struct mpsse_ctx *ctx)
402 {
403         if (ctx->usb_dev)
404                 libusb_close(ctx->usb_dev);
405         if (ctx->usb_ctx)
406                 libusb_exit(ctx->usb_ctx);
407         bit_copy_discard(&ctx->read_queue);
408
409         free(ctx->write_buffer);
410         free(ctx->read_buffer);
411         free(ctx->read_chunk);
412         free(ctx);
413 }
414
415 bool mpsse_is_high_speed(struct mpsse_ctx *ctx)
416 {
417         return ctx->type != TYPE_FT2232C;
418 }
419
420 void mpsse_purge(struct mpsse_ctx *ctx)
421 {
422         int err;
423         LOG_DEBUG("-");
424         ctx->write_count = 0;
425         ctx->read_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);
430         if (err < 0) {
431                 LOG_ERROR("unable to purge ftdi rx buffers: %s", libusb_error_name(err));
432                 return;
433         }
434
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);
437         if (err < 0) {
438                 LOG_ERROR("unable to purge ftdi tx buffers: %s", libusb_error_name(err));
439                 return;
440         }
441 }
442
443 static unsigned buffer_write_space(struct mpsse_ctx *ctx)
444 {
445         /* Reserve one byte for SEND_IMMEDIATE */
446         return ctx->write_size - ctx->write_count - 1;
447 }
448
449 static unsigned buffer_read_space(struct mpsse_ctx *ctx)
450 {
451         return ctx->read_size - ctx->read_count;
452 }
453
454 static void buffer_write_byte(struct mpsse_ctx *ctx, uint8_t data)
455 {
456         LOG_DEBUG_IO("%02x", data);
457         assert(ctx->write_count < ctx->write_size);
458         ctx->write_buffer[ctx->write_count++] = data;
459 }
460
461 static unsigned buffer_write(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
462         unsigned bit_count)
463 {
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);
468         return bit_count;
469 }
470
471 static unsigned buffer_add_read(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset,
472         unsigned bit_count, unsigned offset)
473 {
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,
477                 bit_count);
478         ctx->read_count += DIV_ROUND_UP(bit_count, 8);
479         return bit_count;
480 }
481
482 void mpsse_clock_data_out(struct mpsse_ctx *ctx, const uint8_t *out, unsigned out_offset,
483         unsigned length, uint8_t mode)
484 {
485         mpsse_clock_data(ctx, out, out_offset, 0, 0, length, mode);
486 }
487
488 void mpsse_clock_data_in(struct mpsse_ctx *ctx, uint8_t *in, unsigned in_offset, unsigned length,
489         uint8_t mode)
490 {
491         mpsse_clock_data(ctx, 0, 0, in, in_offset, length, mode);
492 }
493
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)
496 {
497         /* TODO: Fix MSB first modes */
498         LOG_DEBUG_IO("%s%s %d bits", in ? "in" : "", out ? "out" : "", length);
499
500         if (ctx->retval != ERROR_OK) {
501                 LOG_DEBUG_IO("Ignoring command due to previous error");
502                 return;
503         }
504
505         /* TODO: On H chips, use command 0x8E/0x8F if in and out are both 0 */
506         if (out || (!out && !in))
507                 mode |= 0x10;
508         if (in)
509                 mode |= 0x20;
510
511         while (length > 0) {
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);
516
517                 if (length < 8) {
518                         /* Transfer remaining bits in bit mode */
519                         buffer_write_byte(ctx, 0x02 | mode);
520                         buffer_write_byte(ctx, length - 1);
521                         if (out)
522                                 out_offset += buffer_write(ctx, out, out_offset, length);
523                         if (in)
524                                 in_offset += buffer_add_read(ctx, in, in_offset, length, 8 - length);
525                         if (!out && !in)
526                                 buffer_write_byte(ctx, 0x00);
527                         length = 0;
528                 } else {
529                         /* Byte transfer */
530                         unsigned this_bytes = length / 8;
531                         /* MPSSE command limit */
532                         if (this_bytes > 65536)
533                                 this_bytes = 65536;
534                         /* Buffer space limit. We already made sure there's space for the minimum
535                          * transfer. */
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);
540
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);
545                                 if (out)
546                                         out_offset += buffer_write(ctx,
547                                                         out,
548                                                         out_offset,
549                                                         this_bytes * 8);
550                                 if (in)
551                                         in_offset += buffer_add_read(ctx,
552                                                         in,
553                                                         in_offset,
554                                                         this_bytes * 8,
555                                                         0);
556                                 if (!out && !in)
557                                         for (unsigned n = 0; n < this_bytes; n++)
558                                                 buffer_write_byte(ctx, 0x00);
559                                 length -= this_bytes * 8;
560                         }
561                 }
562         }
563 }
564
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)
567 {
568         mpsse_clock_tms_cs(ctx, out, out_offset, 0, 0, length, tdi, mode);
569 }
570
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)
573 {
574         LOG_DEBUG_IO("%sout %d bits, tdi=%d", in ? "in" : "", length, tdi);
575         assert(out);
576
577         if (ctx->retval != ERROR_OK) {
578                 LOG_DEBUG_IO("Ignoring command due to previous error");
579                 return;
580         }
581
582         mode |= 0x42;
583         if (in)
584                 mode |= 0x20;
585
586         while (length > 0) {
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);
590
591                 /* Byte transfer */
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
596                  * clock cycle:
597                  *
598                  * http://developer.intra2net.com/mailarchive/html/libftdi/2009/msg00292.html
599                  */
600                 if (this_bits > 7)
601                         this_bits = 7;
602
603                 if (this_bits > 0) {
604                         buffer_write_byte(ctx, mode);
605                         buffer_write_byte(ctx, this_bits - 1);
606                         uint8_t data = 0;
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));
611                         if (in)
612                                 in_offset += buffer_add_read(ctx,
613                                                 in,
614                                                 in_offset,
615                                                 this_bits,
616                                                 8 - this_bits);
617                         length -= this_bits;
618                 }
619         }
620 }
621
622 void mpsse_set_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
623 {
624         LOG_DEBUG_IO("-");
625
626         if (ctx->retval != ERROR_OK) {
627                 LOG_DEBUG_IO("Ignoring command due to previous error");
628                 return;
629         }
630
631         if (buffer_write_space(ctx) < 3)
632                 ctx->retval = mpsse_flush(ctx);
633
634         buffer_write_byte(ctx, 0x80);
635         buffer_write_byte(ctx, data);
636         buffer_write_byte(ctx, dir);
637 }
638
639 void mpsse_set_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t data, uint8_t dir)
640 {
641         LOG_DEBUG_IO("-");
642
643         if (ctx->retval != ERROR_OK) {
644                 LOG_DEBUG_IO("Ignoring command due to previous error");
645                 return;
646         }
647
648         if (buffer_write_space(ctx) < 3)
649                 ctx->retval = mpsse_flush(ctx);
650
651         buffer_write_byte(ctx, 0x82);
652         buffer_write_byte(ctx, data);
653         buffer_write_byte(ctx, dir);
654 }
655
656 void mpsse_read_data_bits_low_byte(struct mpsse_ctx *ctx, uint8_t *data)
657 {
658         LOG_DEBUG_IO("-");
659
660         if (ctx->retval != ERROR_OK) {
661                 LOG_DEBUG_IO("Ignoring command due to previous error");
662                 return;
663         }
664
665         if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
666                 ctx->retval = mpsse_flush(ctx);
667
668         buffer_write_byte(ctx, 0x81);
669         buffer_add_read(ctx, data, 0, 8, 0);
670 }
671
672 void mpsse_read_data_bits_high_byte(struct mpsse_ctx *ctx, uint8_t *data)
673 {
674         LOG_DEBUG_IO("-");
675
676         if (ctx->retval != ERROR_OK) {
677                 LOG_DEBUG_IO("Ignoring command due to previous error");
678                 return;
679         }
680
681         if (buffer_write_space(ctx) < 1 || buffer_read_space(ctx) < 1)
682                 ctx->retval = mpsse_flush(ctx);
683
684         buffer_write_byte(ctx, 0x83);
685         buffer_add_read(ctx, data, 0, 8, 0);
686 }
687
688 static void single_byte_boolean_helper(struct mpsse_ctx *ctx, bool var, uint8_t val_if_true,
689         uint8_t val_if_false)
690 {
691         if (ctx->retval != ERROR_OK) {
692                 LOG_DEBUG_IO("Ignoring command due to previous error");
693                 return;
694         }
695
696         if (buffer_write_space(ctx) < 1)
697                 ctx->retval = mpsse_flush(ctx);
698
699         buffer_write_byte(ctx, var ? val_if_true : val_if_false);
700 }
701
702 void mpsse_loopback_config(struct mpsse_ctx *ctx, bool enable)
703 {
704         LOG_DEBUG("%s", enable ? "on" : "off");
705         single_byte_boolean_helper(ctx, enable, 0x84, 0x85);
706 }
707
708 void mpsse_set_divisor(struct mpsse_ctx *ctx, uint16_t divisor)
709 {
710         LOG_DEBUG("%d", divisor);
711
712         if (ctx->retval != ERROR_OK) {
713                 LOG_DEBUG_IO("Ignoring command due to previous error");
714                 return;
715         }
716
717         if (buffer_write_space(ctx) < 3)
718                 ctx->retval = mpsse_flush(ctx);
719
720         buffer_write_byte(ctx, 0x86);
721         buffer_write_byte(ctx, divisor & 0xff);
722         buffer_write_byte(ctx, divisor >> 8);
723 }
724
725 int mpsse_divide_by_5_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, 0x8b, 0x8a);
732
733         return ERROR_OK;
734 }
735
736 int mpsse_rtck_config(struct mpsse_ctx *ctx, bool enable)
737 {
738         if (!mpsse_is_high_speed(ctx))
739                 return ERROR_FAIL;
740
741         LOG_DEBUG("%s", enable ? "on" : "off");
742         single_byte_boolean_helper(ctx, enable, 0x96, 0x97);
743
744         return ERROR_OK;
745 }
746
747 int mpsse_set_frequency(struct mpsse_ctx *ctx, int frequency)
748 {
749         LOG_DEBUG("target %d Hz", frequency);
750         assert(frequency >= 0);
751         int base_clock;
752
753         if (frequency == 0)
754                 return mpsse_rtck_config(ctx, true);
755
756         mpsse_rtck_config(ctx, false); /* just try */
757
758         if (frequency > 60000000 / 2 / 65536 && mpsse_divide_by_5_config(ctx, false) == ERROR_OK) {
759                 base_clock = 60000000;
760         } else {
761                 mpsse_divide_by_5_config(ctx, true); /* just try */
762                 base_clock = 12000000;
763         }
764
765         int divisor = (base_clock / 2 + frequency - 1) / frequency - 1;
766         if (divisor > 65535)
767                 divisor = 65535;
768         assert(divisor >= 0);
769
770         mpsse_set_divisor(ctx, divisor);
771
772         frequency = base_clock / 2 / (1 + divisor);
773         LOG_DEBUG("actually %d Hz", frequency);
774
775         return frequency;
776 }
777
778 /* Context needed by the callbacks */
779 struct transfer_result {
780         struct mpsse_ctx *ctx;
781         bool done;
782         unsigned transferred;
783 };
784
785 static LIBUSB_CALL void read_cb(struct libusb_transfer *transfer)
786 {
787         struct transfer_result *res = transfer->user_data;
788         struct mpsse_ctx *ctx = res->ctx;
789
790         unsigned packet_size = ctx->max_packet_size;
791
792         DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
793
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,
806                         this_size);
807                 res->transferred += this_size;
808                 chunk_remains -= this_size + 2;
809                 if (res->transferred == ctx->read_count) {
810                         res->done = true;
811                         break;
812                 }
813         }
814
815         LOG_DEBUG_IO("raw chunk %d, transferred %d of %d", transfer->actual_length, res->transferred,
816                 ctx->read_count);
817
818         if (!res->done)
819                 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
820                         res->done = true;
821 }
822
823 static LIBUSB_CALL void write_cb(struct libusb_transfer *transfer)
824 {
825         struct transfer_result *res = transfer->user_data;
826         struct mpsse_ctx *ctx = res->ctx;
827
828         res->transferred += transfer->actual_length;
829
830         LOG_DEBUG_IO("transferred %d of %d", res->transferred, ctx->write_count);
831
832         DEBUG_PRINT_BUF(transfer->buffer, transfer->actual_length);
833
834         if (res->transferred == ctx->write_count)
835                 res->done = true;
836         else {
837                 transfer->length = ctx->write_count - res->transferred;
838                 transfer->buffer = ctx->write_buffer + res->transferred;
839                 if (libusb_submit_transfer(transfer) != LIBUSB_SUCCESS)
840                         res->done = true;
841         }
842 }
843
844 int mpsse_flush(struct mpsse_ctx *ctx)
845 {
846         int retval = ctx->retval;
847
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;
852                 return retval;
853         }
854
855         LOG_DEBUG_IO("write %d%s, read %d", ctx->write_count, ctx->read_count ? "+1" : "",
856                         ctx->read_count);
857         assert(ctx->write_count > 0 || ctx->read_count == 0); /* No read data without write data */
858
859         if (ctx->write_count == 0)
860                 return retval;
861
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 */
869         }
870
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)
877                 goto error_check;
878
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)
886                         goto error_check;
887         }
888
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;
894
895                 timeout_usb.tv_sec = 1;
896                 timeout_usb.tv_usec = 0;
897
898                 retval = libusb_handle_events_timeout_completed(ctx->usb_ctx, &timeout_usb, NULL);
899                 keep_alive();
900                 if (retval == LIBUSB_ERROR_NO_DEVICE || retval == LIBUSB_ERROR_INTERRUPTED)
901                         break;
902
903                 if (retval != LIBUSB_SUCCESS) {
904                         libusb_cancel_transfer(write_transfer);
905                         if (read_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,
909                                                                 &timeout_usb, NULL);
910                                 if (retval != LIBUSB_SUCCESS)
911                                         break;
912                         }
913                 }
914
915                 int64_t now = timeval_ms();
916                 if (now - start > warn_after) {
917                         LOG_WARNING("Haven't made progress in mpsse_flush() for %" PRId64
918                                         "ms.", now - start);
919                         warn_after *= 2;
920                 }
921         }
922
923 error_check:
924         if (retval != LIBUSB_SUCCESS) {
925                 LOG_ERROR("libusb_handle_events() failed with %s", libusb_error_name(retval));
926                 retval = ERROR_FAIL;
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,
930                         ctx->write_count);
931                 retval = ERROR_FAIL;
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,
935                         ctx->read_count);
936                 retval = ERROR_FAIL;
937         } else if (ctx->read_count) {
938                 ctx->write_count = 0;
939                 ctx->read_count = 0;
940                 bit_copy_execute(&ctx->read_queue);
941                 retval = ERROR_OK;
942         } else {
943                 ctx->write_count = 0;
944                 bit_copy_discard(&ctx->read_queue);
945                 retval = ERROR_OK;
946         }
947
948         if (retval != ERROR_OK)
949                 mpsse_purge(ctx);
950
951         libusb_free_transfer(write_transfer);
952         if (read_transfer)
953                 libusb_free_transfer(read_transfer);
954
955         return retval;
956 }