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