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