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