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.
 
 
 
 
 
 

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