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