You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

947 lines
26 KiB

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