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