Debian Codegraph @

src/linux/link_usb.cc

raw
1 /* Hey EMACS -*- linux-c -*- */
2 /* $Id$ */
3
4 /* libticables2 - link cable library, a part of the TiLP project
5 * Copyright (c) 1999-2006 Romain Lievin
6 * Copyright (c) 2001 Julien Blache (original author)
7 * Copyright (c) 2007 Romain Lievin (libusb-win32 support)
8 * Copyright (c) 2007 Kevin Kofler (libusb-win32 slv_check support)
9 *
10 * Portions lifted from libusb (LGPL):
11 * Copyright (c) 2000-2003 Johannes Erdfelt <[email protected]>
12 * Modifications for libticables Copyright (C) 2005 Kevin Kofler
13 *
14 * Portions lifted from libusb-win32 (LGPL):
15 * Copyright (c) 2002-2005 Stephan Meyer <[email protected]>
16 * Copyright (c) 2000-2005 Johannes Erdfelt <[email protected]>
17 * Modifications for libticables Copyright (C) 2007 Kevin Kofler
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software Foundation,
31 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
32 */
33
34 /* TI-GRAPH LINK USB and direct USB cable support (libusb 0.1.x) */
35
36 /*
37 Some important remarks... (http://lpg.ticalc.org/prj_usb/index.html)
38
39 This link cable use Bulk mode with packets. The max size of a packet is
40 32/64 bytes (MAX_PACKET_SIZE/BULKUSB_MAX_TRANSFER_SIZE).
41
42 This is transparent for the user because the libusb manages all these
43 things for us. Nethertheless, this fact has some consequences:
44
45 - it is better (for USB & OS performances) to read/write a set of bytes
46 rather than byte per byte.
47
48 - for reading, we have to read up to 32 bytes at a time (even if we need
49 only 1 byte) and to store them in a buffer for subsequent accesses.
50 In fact, if we try and get byte per byte, it will not work.
51
52 - [ for writing, we don't store bytes in a buffer. It seems better to send
53 data byte per byte (latency ?!). But, this make data-rate significantly
54 decrease (1KB/s instead of 5KB/s).
55 Another way is to use partially buffered write operations: send consecutive
56 blocks as a whole but partial block byte per byte. This is the best
57 compromise and it works fine ! ] => not needed any more
58
59 - another particular effect (quirk): sometimes (usually when calc need to
60 reply and takes a while), a read call can returns with neither data
61 nor timeout. Simply retry a read call and it works fine. The best example
62 is to get IDLIST.
63
64 Moreover,
65
66 - for checking, under Linux, we use a hack by Kevin Kofler (based on the
67 libusb source code, and inspired by Romain's Windows driver). This is for
68 Linux ONLY, not for other POSIX-like systems (it directly uses Linux kernel
69 interfaces). Under Windows, we use the asynchronous API provided by the
70 libusb-win32.
71 */
72
73 #ifdef HAVE_CONFIG_H
74 #include <config.h>
75 #endif
76
77 #include <stdio.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <fcntl.h>
81 #include <errno.h>
82
83 #ifndef __WIN32__
84 #include <unistd.h>
85 #include <sys/time.h>
86 #include <sys/types.h>
87 #include <sys/stat.h>
88 #include <sys/ioctl.h>
89 #endif
90
91 #include "../ticables.h"
92 #include "../internal.h"
93 #ifdef _MSC_VER
94 # include "../win32/usb.h"
95 #else
96 # include <usb.h>
97 #endif
98
99 /* --- */
100
101 #ifdef __WIN32__ // found in src/error.h of libusb-win32
102 #ifndef ETIMEDOUT
103 # define ETIMEDOUT 116
104 #endif
105
106 # define usb_busses usb_get_busses()
107
108 /* variables for slv_check and slv_bulk_read2 */
109 static int io_pending = 0;
110 static void *context = 0;
111 #endif
112
113 /* --- */
114
115 #ifdef __LINUX__
116 /* the libusb internal structure from usbi.h */
117 struct usb_dev_handle {
118 int fd;
119
120 struct usb_bus *bus;
121 struct usb_device *device;
122
123 int config;
124 int interface;
125 int altsetting;
126
127 void *impl_info;
128 };
129
130 /* another pair of libusb internal structures from linux.h */
131 struct usb_iso_packet_desc {
132 unsigned int length;
133 unsigned int actual_length;
134 unsigned int status;
135 };
136 struct usb_urb {
137 unsigned char type;
138 unsigned char endpoint;
139 int status;
140 unsigned int flags;
141 void *buffer;
142 int buffer_length;
143 int actual_length;
144 int start_frame;
145 int number_of_packets;
146 int error_count;
147 unsigned int signr;
148 void *usercontext;
149 struct usb_iso_packet_desc iso_frame_desc[];
150 };
151
152 /* definitions from the libusb linux.h */
153 #define USB_URB_TYPE_BULK 3
154 #define IOCTL_USB_CONTROL _IOWR('U', 0, struct usb_ctrltransfer)
155 #define IOCTL_USB_BULK _IOWR('U', 2, struct usb_bulktransfer)
156 #define IOCTL_USB_RESETEP _IOR('U', 3, unsigned int)
157 #define IOCTL_USB_SETINTF _IOR('U', 4, struct usb_setinterface)
158 #define IOCTL_USB_SETCONFIG _IOR('U', 5, unsigned int)
159 #define IOCTL_USB_GETDRIVER _IOW('U', 8, struct usb_getdriver)
160 #define IOCTL_USB_SUBMITURB _IOR('U', 10, struct usb_urb)
161 #define IOCTL_USB_DISCARDURB _IO('U', 11)
162 #define IOCTL_USB_REAPURB _IOW('U', 12, void *)
163 #define IOCTL_USB_REAPURBNDELAY _IOW('U', 13, void *)
164 #define IOCTL_USB_CLAIMINTF _IOR('U', 15, unsigned int)
165 #define IOCTL_USB_RELEASEINTF _IOR('U', 16, unsigned int)
166 #define IOCTL_USB_CONNECTINFO _IOW('U', 17, struct usb_connectinfo)
167 #define IOCTL_USB_IOCTL _IOWR('U', 18, struct usb_ioctl)
168 #define IOCTL_USB_HUB_PORTINFO _IOR('U', 19, struct usb_hub_portinfo)
169 #define IOCTL_USB_RESET _IO('U', 20)
170 #define IOCTL_USB_CLEAR_HALT _IOR('U', 21, unsigned int)
171 #define IOCTL_USB_DISCONNECT _IO('U', 22)
172 #define IOCTL_USB_CONNECT _IO('U', 23)
173
174 /* definitions to set the libusb error string from the libusb error.h */
175 typedef enum {
176 USB_ERROR_TYPE_NONE = 0,
177 USB_ERROR_TYPE_STRING,
178 USB_ERROR_TYPE_ERRNO,
179 } usb_error_type_t;
180
181 extern char usb_error_str[1024];
182 extern int usb_error_errno;
183 extern usb_error_type_t usb_error_type;
184 extern int usb_debug;
185
186 #define USB_ERROR(x) \
187 do { \
188 usb_error_type = USB_ERROR_TYPE_ERRNO; \
189 usb_error_errno = x; \
190 return x; \
191 } while (0)
192
193 #define USB_ERROR_STR(x, format, args...) \
194 do { \
195 usb_error_type = USB_ERROR_TYPE_STRING; \
196 snprintf(usb_error_str, sizeof(usb_error_str) - 1, format, ## args); \
197 if (usb_debug >= 2) \
198 { \
199 fprintf(stderr, "USB error: %s\n", usb_error_str); \
200 } \
201 return x; \
202 } while (0)
203
204 /* variables for slv_check and slv_bulk_read2 */
205 static int io_pending = 0;
206 static struct usb_urb urb;
207 #endif
208
209 /* --- */
210
211 #include "../ticables.h"
212 #include "../logging.h"
213 #include "../error.h"
214 #include "../gettext.h"
215 #if defined(__WIN32__)
216 #include "../win32/detect.h"
217 #elif defined(__MACOSX__)
218 #include "../macos/detect.h"
219 #elif defined(__BSD__)
220 #include "../bsd/detect.h"
221 #else
222 #include "detect.h"
223 #endif
224 #include "../timeout.h"
225 #include "../internal.h"
226
227 /* Constants */
228
229 #define MAX_CABLES 4
230
231 #define VID_TI 0x0451 /* Texas Instruments, Inc. */
232
233 #define to (100 * h->timeout) // in ms
234
235 /* Types */
236
237 // device infos
238 typedef struct
239 {
240 uint16_t vid;
241 uint16_t pid;
242 const char* str;
243
244 struct usb_device *dev;
245 } usb_infos;
246
247 // list of known devices
248 static const usb_infos tigl_infos[] =
249 {
250 {VID_TI, PID_TIGLUSB, "TI-GRAPH LINK USB", NULL},
251 {VID_TI, PID_TI84P, "TI-84 Plus Hand-Held", NULL},
252 {VID_TI, PID_TI89TM, "TI-89 Titanium Hand-Held", NULL},
253 {VID_TI, PID_TI84P_SE, "TI-84 Plus Silver Hand-Held", NULL},
254 {VID_TI, PID_NSPIRE, "TI-Nspire Hand-Held", NULL},
255 {0, 0, NULL, NULL}
256 };
257
258 // list of devices found
259 static USBCableInfo tigl_devices[MAX_CABLES+1];
260 static int tigl_n_devices;
261
262 // internal structure for holding data
263 typedef struct
264 {
265 struct usb_device *device;
266 usb_dev_handle *handle;
267
268 USBCableInfo cable_info;
269 int nBytesRead;
270 uint8_t rBuf[64];
271 uint8_t* rBufPtr;
272 int in_endpoint;
273 int out_endpoint;
274 int max_ps;
275 int was_max_size_packet;
276 } usb_struct;
277
278 // convenient macros
279 #define uDev (((usb_struct *)(h->priv2))->device)
280 #define uHdl (((usb_struct *)(h->priv2))->handle)
281 #define cable_info (((usb_struct *)(h->priv2))->cable_info)
282 #define max_ps (((usb_struct *)(h->priv2))->max_ps)
283 #define was_max_size_packet (((usb_struct *)(h->priv2))->was_max_size_packet)
284 #define nBytesRead (((usb_struct *)(h->priv2))->nBytesRead)
285 #define rBuf (((usb_struct *)(h->priv2))->rBuf)
286 #define rBufPtr (((usb_struct *)(h->priv2))->rBufPtr)
287 #define uInEnd (((usb_struct *)(h->priv2))->in_endpoint)
288 #define uOutEnd (((usb_struct *)(h->priv2))->out_endpoint)
289
290 /* Helpers (=driver API) */
291
292 static void tigl_get_product(char * string, size_t maxlen, struct usb_device *dev)
293 {
294 /* The code below causes problems on FreeBSD (libusb bug?). */
295 #ifndef __BSD__
296 struct usb_dev_handle *han;
297 int ret;
298
299 string[0] = 0;
300
301 if (dev->descriptor.iProduct)
302 {
303 han = usb_open(dev);
304 ret = usb_get_string_simple(han, dev->descriptor.iProduct, string, maxlen);
305 usb_close(han);
306 }
307 #endif
308 }
309
310 static int tigl_find(void)
311 {
312 struct usb_bus *bus;
313 struct usb_device *dev;
314 int i, j;
315
316 memset(tigl_devices, 0, sizeof(tigl_devices));
317 j = tigl_n_devices = 0;
318
319 /* loop taken from testlibusb.c */
320 for (bus = usb_busses; bus; bus = bus->next)
321 {
322 for (dev = bus->devices; dev; dev = dev->next)
323 {
324 if (dev->descriptor.idVendor == VID_TI)
325 {
326 for(i = 0; i < (int)(sizeof(tigl_infos) / sizeof(tigl_infos[0])); i++)
327 {
328 if (dev->descriptor.idProduct == tigl_infos[i].pid)
329 {
330 tigl_devices[j].vid = dev->descriptor.idVendor;
331 tigl_devices[j].pid = dev->descriptor.idProduct;
332 tigl_devices[j].version = dev->descriptor.bcdDevice;
333
334 tigl_get_product(tigl_devices[j].product_str, sizeof(tigl_devices[j].product_str), dev);
335 ticables_info(" found %s on #%i, version <%x.%02x>",
336 tigl_devices[j].product_str, j+1,
337 dev->descriptor.bcdDevice >> 8,
338 dev->descriptor.bcdDevice & 0xff);
339
340 tigl_devices[j++].dev = dev;
341 tigl_n_devices = j;
342
343 if (j >= MAX_CABLES)
344 {
345 return j;
346 }
347 }
348 }
349 }
350 }
351 }
352
353 return j;
354 }
355
356 static int tigl_enum(void)
357 {
358 int ret = 0;
359
360 /* find all usb busses on the system */
361 ret = usb_find_busses();
362 if (ret < 0)
363 {
364 ticables_warning(_("usb_find_busses (%s).\n"), usb_strerror());
365 return ERR_LIBUSB_OPEN;
366 }
367
368 /* find all usb devices on all discovered busses */
369 ret = usb_find_devices();
370 if (ret < 0)
371 {
372 ticables_warning(_("usb_find_devices (%s).\n"), usb_strerror());
373 return ERR_LIBUSB_OPEN;
374 }
375
376 /* find all TI products on all discovered busses/devices */
377 ret = tigl_find();
378 if (ret == 0)
379 {
380 ticables_warning("%s", _("no devices found!\n"));
381 return ERR_LIBUSB_OPEN;
382 }
383
384 return 0;
385 }
386
387 static int tigl_open(int id, usb_dev_handle **udh)
388 {
389 int ret;
390
391 ret = tigl_enum();
392 if (ret)
393 {
394 return ret;
395 }
396
397 if (tigl_devices[id].dev == NULL)
398 {
399 return ERR_LIBUSB_OPEN;
400 }
401
402 *udh = usb_open((struct usb_device *)(tigl_devices[id].dev));
403 if (*udh != NULL)
404 {
405 /* only one configuration: #1 */
406 ret = usb_set_configuration(*udh, 1);
407 if (ret < 0)
408 {
409 ticables_warning("usb_set_configuration (%s).\n", usb_strerror());
410 }
411
412 /* configuration #1, interface #0 */
413 ret = usb_claim_interface(*udh, 0);
414 if (ret < 0)
415 {
416 ticables_warning("usb_claim_interface (%s).\n", usb_strerror());
417 return ERR_LIBUSB_CLAIM;
418 }
419
420 return 0;
421 }
422 else
423 {
424 return ERR_LIBUSB_OPEN;
425 }
426
427 return 0;
428 }
429
430 static int tigl_close(usb_dev_handle **udh)
431 {
432 // NOTE: slv_close() has already checked for *udh != NULL .
433 usb_release_interface(*udh, 0);
434 usb_close(*udh);
435 *udh = NULL;
436
437 return 0;
438 }
439
440 static int tigl_reset(CableHandle *h)
441 {
442 // Reset out pipe
443 if (NULL != uHdl)
444 {
445 int ret = usb_clear_halt(uHdl, uOutEnd);
446 if (ret < 0)
447 {
448 ticables_warning("usb_clear_halt of out pipe (%s).\n", usb_strerror());
449 }
450
451 // Reset in pipe
452 ret = usb_clear_halt(uHdl, uInEnd);
453 if (ret < 0)
454 {
455 ticables_warning("usb_clear_halt of in pipe (%s).\n", usb_strerror());
456 }
457
458 return 0;
459 }
460 else
461 {
462 return ERR_LIBUSB_RESET;
463 }
464 }
465
466 /* API */
467 static int slv_prepare(CableHandle *h)
468 {
469 int ret;
470 char str[64];
471
472 #if defined(__WIN32__)
473 ret = win32_check_libusb();
474 #elif defined(__MACOSX__)
475 ret = macosx_check_libusb();
476 #elif defined(__BSD__)
477 ret = bsd_check_libusb();
478 #else
479 ret = linux_check_libusb();
480 #endif
481 if (!ret)
482 {
483 if (h->port >= MAX_CABLES)
484 {
485 return ERR_ILLEGAL_ARG;
486 }
487
488 h->address = h->port-1;
489 sprintf(str, "TiglUsb #%i", h->port);
490 h->device = strdup(str);
491 h->priv2 = (usb_struct *)calloc(1, sizeof(usb_struct));
492 }
493
494 return ret;
495 }
496
497 static int slv_open(CableHandle *h)
498 {
499 int ret;
500 int i;
501 struct usb_config_descriptor *config;
502 struct usb_interface *interface_;
503 struct usb_interface_descriptor *interface;
504 struct usb_endpoint_descriptor *endpoint;
505
506 // open device
507 ret = tigl_open(h->address, &uHdl);
508 if (ret)
509 {
510 return ret;
511 }
512 cable_info = tigl_devices[h->address];
513 uDev = (struct usb_device *)(tigl_devices[h->address].dev);
514 uInEnd = 0x81;
515 uOutEnd = 0x02;
516
517 // get max packet size
518 config = &(uDev->config[0]);
519 interface_ = &(config->interface[0]);
520 interface = &(interface_->altsetting[0]);
521 endpoint = &(interface->endpoint[0]);
522 max_ps = endpoint->wMaxPacketSize;
523 // Enumerate endpoints.
524 for (i = 0; i < interface->bNumEndpoints; i++)
525 {
526 if ((endpoint->bmAttributes & USB_ENDPOINT_TYPE_MASK) == USB_ENDPOINT_TYPE_BULK)
527 {
528 if (endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
529 {
530 if (endpoint->bEndpointAddress != 0x83) // Some Nspire OS use that seemingly bogus endpoint.
531 {
532 uInEnd = endpoint->bEndpointAddress;
533 ticables_info("found bulk in endpoint 0x%02X\n", uInEnd);
534 }
535 else
536 {
537 ticables_info("XXX: swallowing bulk in endpoint 0x83, advertised by Nspire (CAS and non-CAS) 1.x but seemingly not working\n");
538 }
539 }
540 else
541 {
542 uOutEnd = endpoint->bEndpointAddress;
543 ticables_info("found bulk out endpoint 0x%02X\n", uOutEnd);
544 }
545 }
546 endpoint++;
547 }
548 nBytesRead = 0;
549 was_max_size_packet = 0;
550
551 return 0;
552 }
553
554 static int slv_close(CableHandle *h)
555 {
556 if (uHdl != NULL)
557 {
558 tigl_close(&uHdl);
559 }
560 uDev = NULL;
561
562 free(h->priv2);
563 h->priv2 = NULL;
564
565 return 0;
566 }
567
568 static int slv_get_device_info(CableHandle *h, CableDeviceInfo *info)
569 {
570 translate_usb_device_info(info, &cable_info);
571 return 0;
572 }
573
574 static int slv_reset(CableHandle *h)
575 {
576 int ret = 0;
577
578 #if !defined(__BSD__)
579 /* Reset both endpoints (send an URB_FUNCTION_RESET_PIPE) */
580 ret = tigl_reset(h);
581 if (!ret)
582 {
583 /* NOTE: tigl_reset() has already checked for uHdl != NULL */
584 #ifdef __WIN32__
585 /* Reset USB port (send an IOCTL_INTERNAL_USB_RESET_PORT) */
586 ret = usb_reset_ex(uHdl, USB_RESET_TYPE_RESET_PORT);
587 #else
588 ret = usb_reset(uHdl);
589 #endif
590
591 if (ret < 0)
592 {
593 ticables_warning("usb_reset (%s).\n", usb_strerror());
594 /* On Mac OS X, reenumeration isn't automatic, so let's not return here. */
595 #ifndef __MACOSX__
596 ret = ERR_LIBUSB_RESET;
597 #else
598 ret = 0;
599 #endif
600 }
601
602 if (!ret)
603 {
604 // lib-usb doc: after calling usb_reset, the device will need to re-enumerate
605 // and therefore, requires you to find the new device and open a new handle.
606 // The handle used to call usb_reset will no longer work.
607 #ifdef __WIN32__
608 Sleep(500);
609 #else
610 usleep(500000);
611 #endif
612 ret = slv_close(h);
613 if (!ret)
614 {
615 h->priv2 = (usb_struct *)calloc(1, sizeof(usb_struct));
616 ret = slv_open(h);
617 }
618 }
619 }
620 #endif
621
622 return ret;
623 }
624
625 // convenient function which send one or more bytes
626 static int send_block(CableHandle *h, uint8_t *data, int length)
627 {
628 int ret;
629
630 if (NULL == uHdl)
631 {
632 return ERR_WRITE_ERROR;
633 }
634
635 ret = usb_bulk_write(uHdl, uOutEnd, (char*)data, length, to);
636
637 if (ret == -ETIMEDOUT)
638 {
639 ticables_warning("usb_bulk_write (%s).\n", usb_strerror());
640 return ERR_WRITE_TIMEOUT;
641 }
642 else if (ret == -EPIPE)
643 {
644 ticables_warning("usb_bulk_write (%s).\n", usb_strerror());
645 return ERR_WRITE_ERROR;
646 }
647 else if (ret < 0)
648 {
649 ticables_warning("usb_bulk_write (%s).\n", usb_strerror());
650 return ERR_WRITE_ERROR;
651 }
652
653 if (tigl_devices[h->address].pid == PID_NSPIRE && length % max_ps == 0)
654 {
655 ticables_info("XXX triggering an extra bulk write");
656 ret = usb_bulk_write(uHdl, uOutEnd, (char*)data, 0, to);
657 if (ret < 0)
658 {
659 ticables_warning("usb_bulk_write (%s).\n", usb_strerror());
660 return ERR_WRITE_ERROR;
661 }
662 }
663
664 return 0;
665 }
666
667 static int slv_put(CableHandle* h, uint8_t *data, uint32_t len)
668 {
669 return send_block(h, data, len);
670 }
671
672 #ifdef __LINUX__
673 #define MAX_READ_WRITE (16 * 1024)
674 static int slv_bulk_read2(usb_dev_handle *dev, int ep, char *bytes, int size,
675 int timeout)
676 {
677 // This is a variant of usb_bulk_read in libusb, edited to take the
678 // io_pending variable set in slv_check into account.
679 unsigned int bytesdone = 0, requested;
680 struct timeval tv, tv_ref, tv_now;
681 void *context;
682 int ret, waiting;
683
684 /*
685 * FIXME: The use of the URB interface is incorrect here if there are
686 * multiple callers at the same time. We assume we're the only caller
687 * and if we get completions from another caller, this code will fail
688 * in interesting ways.
689 */
690
691 /*
692 * Get actual time, and add the timeout value. The result is the absolute
693 * time where we have to quit waiting for an message.
694 */
695 gettimeofday(&tv_ref, NULL);
696 tv_ref.tv_sec = tv_ref.tv_sec + timeout / 1000;
697 tv_ref.tv_usec = tv_ref.tv_usec + (timeout % 1000) * 1000;
698
699 if (tv_ref.tv_usec > 1000000) {
700 tv_ref.tv_usec -= 1000000;
701 tv_ref.tv_sec++;
702 }
703
704 do {
705 fd_set writefds;
706
707 requested = size - bytesdone;
708 if (requested > MAX_READ_WRITE)
709 {
710 requested = MAX_READ_WRITE;
711 }
712
713 if (io_pending)
714 {
715 io_pending = FALSE;
716 }
717 else
718 {
719 urb.type = USB_URB_TYPE_BULK;
720 urb.endpoint = ep;
721 urb.flags = 0;
722 urb.buffer = bytes + bytesdone;
723 urb.buffer_length = requested;
724 urb.usercontext = (void *)(intptr_t)ep;
725 urb.signr = 0;
726 urb.actual_length = 0;
727 urb.number_of_packets = 0; /* don't do isochronous yet */
728
729 ret = ioctl(dev->fd, IOCTL_USB_SUBMITURB, &urb);
730 if (ret < 0) {
731 USB_ERROR_STR(-errno, "error submitting URB: %s", strerror(errno));
732 return ret;
733 }
734 }
735
736 FD_ZERO(&writefds);
737 FD_SET(dev->fd, &writefds);
738
739 waiting = 1;
740 while (((ret = ioctl(dev->fd, IOCTL_USB_REAPURBNDELAY, &context)) == -1) && waiting) {
741 tv.tv_sec = 0;
742 tv.tv_usec = 1000; // 1 msec
743 select(dev->fd + 1, NULL, &writefds, NULL, &tv); //sub second wait
744
745 /* compare with actual time, as the select timeout is not that precise */
746 gettimeofday(&tv_now, NULL);
747
748 if ((tv_now.tv_sec > tv_ref.tv_sec) ||
749 ((tv_now.tv_sec == tv_ref.tv_sec) && (tv_now.tv_usec >= tv_ref.tv_usec)))
750 {
751 waiting = 0;
752 }
753 }
754
755 /*
756 * If there was an error, that wasn't EAGAIN (no completion), then
757 * something happened during the reaping and we should return that
758 * error now
759 */
760 if (ret < 0 && errno != EAGAIN)
761 {
762 USB_ERROR_STR(-errno, "error reaping URB: %s", strerror(errno));
763 }
764
765 bytesdone += urb.actual_length;
766 } while (ret == 0 && bytesdone < size && urb.actual_length == requested);
767
768 /* If the URB didn't complete in success or error, then let's unlink it */
769 if (ret < 0) {
770 int rc;
771
772 if (!waiting)
773 {
774 rc = -ETIMEDOUT;
775 }
776 else
777 {
778 rc = urb.status;
779 }
780
781 ret = ioctl(dev->fd, IOCTL_USB_DISCARDURB, &urb);
782 if (ret < 0 && errno != EINVAL && usb_debug >= 1)
783 {
784 fprintf(stderr, "error discarding URB: %s", strerror(errno));
785 }
786
787 /*
788 * When the URB is unlinked, it gets moved to the completed list and
789 * then we need to reap it or else the next time we call this function,
790 * we'll get the previous completion and exit early
791 */
792 ioctl(dev->fd, IOCTL_USB_REAPURB, &context);
793
794 return rc;
795 }
796
797 return bytesdone;
798 }
799 #endif
800
801 #ifdef _WIN32
802 #define LIBUSB_MAX_READ_WRITE 0x10000
803 static int slv_bulk_read2(usb_dev_handle *dev, int ep, char *bytes, int size,
804 int timeout)
805 {
806 // This is a variant of usb_bulk_read in libusb-win32, edited to take the
807 // io_pending variable set in slv_check into account and to use the public
808 // async API instead of the private one.
809
810 int transmitted = 0;
811 int ret;
812 int requested;
813
814 if (!io_pending)
815 {
816 ret = usb_bulk_setup_async(dev, &context, (unsigned char)ep);
817
818 if (ret < 0)
819 {
820 return ret;
821 }
822 }
823
824 do
825 {
826 requested = size > LIBUSB_MAX_READ_WRITE ? LIBUSB_MAX_READ_WRITE : size;
827
828 if (io_pending)
829 {
830 io_pending = FALSE;
831 }
832 else
833 {
834 ret = usb_submit_async(context, bytes, requested);
835
836 if (ret < 0)
837 {
838 transmitted = ret;
839 break;
840 }
841 }
842
843 ret = usb_reap_async(context, timeout);
844
845 if (ret < 0)
846 {
847 transmitted = ret;
848 break;
849 }
850
851 transmitted += ret;
852 bytes += ret;
853 size -= ret;
854 } while(size > 0 && ret == requested);
855
856 usb_free_async(&context);
857
858 return transmitted;
859 }
860 #endif
861
862 static int slv_get_(CableHandle *h, uint8_t *data)
863 {
864 int ret = 0;
865 tiTIME clk;
866
867 /* Read up to 32/64 bytes and store them in a buffer for subsequent accesses */
868 if (nBytesRead <= 0)
869 {
870 TO_START(clk);
871 do
872 {
873 // NOTE: slv_get() has already checked for uHdl != NULL .
874 #if defined(__LINUX__) || defined(__WIN32__)
875 ret = slv_bulk_read2(uHdl, uInEnd, (char*)rBuf, max_ps, to);
876 #else
877 ret = usb_bulk_read(uHdl, uInEnd, (char*)rBuf, max_ps, to);
878 #endif
879
880 if (ret == max_ps)
881 {
882 was_max_size_packet = 1;
883 }
884 else
885 {
886 was_max_size_packet = 0;
887 }
888
889 if (TO_ELAPSED(clk, h->timeout))
890 {
891 nBytesRead = 0;
892 return ERR_READ_TIMEOUT;
893 }
894 /*
895 if (ret == 0)
896 {
897 ticables_warning("\nweird, usb_bulk_read returns without any data & error; retrying...\n");
898 }
899 */
900 }
901 while(!ret);
902
903 if (ret == -ETIMEDOUT)
904 {
905 ticables_warning("usb_bulk_read (%s).\n", usb_strerror());
906 nBytesRead = 0;
907 return ERR_READ_TIMEOUT;
908 }
909 else if (ret == -EPIPE)
910 {
911 ticables_warning("usb_bulk_read (%s).\n", usb_strerror());
912 nBytesRead = 0;
913 return ERR_READ_ERROR;
914 }
915 else if (ret < 0)
916 {
917 ticables_warning("usb_bulk_read (%s).\n", usb_strerror());
918 nBytesRead = 0;
919 return ERR_READ_ERROR;
920 }
921
922 nBytesRead = ret;
923 rBufPtr = rBuf;
924 }
925
926 *data = *rBufPtr++;
927 nBytesRead--;
928
929 return 0;
930 }
931
932 static int slv_get(CableHandle* h, uint8_t *data, uint32_t len)
933 {
934 int i, ret;
935
936 if (NULL == uHdl)
937 {
938 return ERR_READ_ERROR;
939 }
940
941 // we can't do that in any other way because slv_get_ can returns
942 // 1, 2, ..., len bytes.
943 for (i = 0; i < (int)len; i++)
944 {
945 ret = slv_get_(h, data+i);
946 if (ret)
947 {
948 break;
949 }
950 }
951
952 if (!ret && (tigl_devices[h->address].pid == PID_NSPIRE && was_max_size_packet != 0 && nBytesRead == 0)
953 || (len == 0 && ( (tigl_devices[h->address].pid == PID_TI89TM && was_max_size_packet != 0 && nBytesRead == 0)
954 || (tigl_devices[h->address].pid == PID_TI84P && was_max_size_packet != 0 && nBytesRead == 0)
955 || (tigl_devices[h->address].pid == PID_TI84P_SE && was_max_size_packet != 0 && nBytesRead == 0)
956 )
957 )
958 )
959 {
960 ticables_info("XXX triggering an extra bulk read");
961 #if defined(__LINUX__) || defined(__WIN32__)
962 ret = slv_bulk_read2(uHdl, uInEnd, (char*)rBuf, max_ps, to);
963 #else
964 ret = usb_bulk_read(uHdl, uInEnd, (char*)rBuf, max_ps, to);
965 #endif
966 if (ret < 0) {
967 ticables_warning("usb_bulk_read (%s).\n", usb_strerror());
968 return ERR_READ_ERROR;
969 }
970 }
971
972 return ret;
973 }
974
975 static int slv_probe(CableHandle *h)
976 {
977 int ret;
978 int i;
979
980 ret = tigl_enum();
981 if (ret)
982 {
983 return ret;
984 }
985
986 for(i = 0; i < MAX_CABLES; i++)
987 {
988 if (tigl_devices[h->address].pid == PID_TIGLUSB)
989 {
990 return 0;
991 }
992 }
993
994 return ERR_PROBE_FAILED;
995 }
996
997 static int raw_probe(CableHandle *h)
998 {
999 int ret;
1000 int i;
1001
1002 ret = tigl_enum();
1003 if (ret)
1004 {
1005 return ret;
1006 }
1007
1008 for(i = 0; i < MAX_CABLES; i++)
1009 {
1010 if (tigl_devices[h->address].pid == PID_TI89TM ||
1011 tigl_devices[h->address].pid == PID_TI84P ||
1012 tigl_devices[h->address].pid == PID_TI84P_SE ||
1013 tigl_devices[h->address].pid == PID_NSPIRE)
1014 {
1015 return 0;
1016 }
1017 }
1018
1019 return ERR_PROBE_FAILED;
1020 }
1021
1022 static int slv_check(CableHandle *h, int *status)
1023 {
1024 #if defined(__LINUX__)
1025 // This really should be in libusb, but alas it isn't, so their code was
1026 // adapted by Kevin Kofler for use here. It's required to get TiEmu 3 to
1027 // work with the SilverLink.
1028
1029 void *context;
1030 int ret;
1031
1032 if (nBytesRead > 0)
1033 {
1034 *status = !0;
1035 return 0;
1036 }
1037
1038 if (NULL == uHdl)
1039 {
1040 return ERR_READ_ERROR;
1041 }
1042
1043 if (!io_pending)
1044 {
1045 urb.type = USB_URB_TYPE_BULK;
1046 urb.endpoint = uInEnd;
1047 urb.flags = 0;
1048 urb.buffer = (char*)rBuf;
1049 urb.buffer_length = max_ps;
1050 urb.usercontext = (void *)(intptr_t)uInEnd;
1051 urb.signr = 0;
1052 urb.actual_length = 0;
1053 urb.number_of_packets = 0;
1054
1055 ret = ioctl(uHdl->fd, IOCTL_USB_SUBMITURB, &urb);
1056 if (ret < 0)
1057 {
1058 return ERR_READ_ERROR;
1059 }
1060 io_pending = TRUE;
1061 }
1062
1063 ret = ioctl(uHdl->fd, IOCTL_USB_REAPURBNDELAY, &context);
1064 if (ret < 0 && errno != EAGAIN)
1065 {
1066 // Error, unlink URB and return failure.
1067 ioctl(uHdl->fd, IOCTL_USB_DISCARDURB, &urb);
1068
1069 /*
1070 * When the URB is unlinked, it gets moved to the completed list and
1071 * then we need to reap it or else the next time we call this function,
1072 * we'll get the previous completion and exit early
1073 */
1074 ioctl(uHdl->fd, IOCTL_USB_REAPURB, &context);
1075
1076 io_pending = FALSE;
1077 return ERR_READ_ERROR;
1078 }
1079
1080 if (ret >= 0)
1081 {
1082 io_pending = FALSE;
1083 if (urb.actual_length > 0)
1084 {
1085 nBytesRead = urb.actual_length;
1086 rBufPtr = rBuf;
1087 *status = STATUS_RX; // data available
1088 }
1089 }
1090 return 0;
1091 #elif defined(__WIN32__)
1092 int ret;
1093
1094 if (nBytesRead > 0)
1095 {
1096 *status = !0;
1097 return 0;
1098 }
1099
1100 if (!io_pending)
1101 {
1102 ret = usb_bulk_setup_async(uHdl, &context, uInEnd);
1103 if (ret < 0)
1104 {
1105 return ERR_READ_ERROR;
1106 }
1107 ret = usb_submit_async(context, (char*)rBuf, max_ps);
1108 if (ret < 0)
1109 {
1110 usb_free_async(&context);
1111 return ERR_READ_ERROR;
1112 }
1113 io_pending = TRUE;
1114 }
1115
1116 ret = usb_reap_async_nocancel(context, 0);
1117 if (ret < 0 && ret != -ETIMEDOUT)
1118 {
1119 // Error, unlink URB and return failure.
1120 usb_cancel_async(context);
1121 usb_free_async(&context);
1122 io_pending = FALSE;
1123 return ERR_READ_ERROR;
1124 }
1125
1126 if (ret >= 0)
1127 {
1128 usb_free_async(&context);
1129 io_pending = FALSE;
1130 if (ret > 0)
1131 {
1132 nBytesRead = ret;
1133 rBufPtr = rBuf;
1134 *status = STATUS_RX; // data available
1135 }
1136 }
1137 return 0;
1138 #else
1139 // no way to check yet
1140 return 0;
1141 #endif
1142 }
1143
1144 extern const CableFncts cable_slv =
1145 {
1146 CABLE_SLV,
1147 "SLV",
1148 N_("SilverLink"),
1149 N_("SilverLink (TI-GRAPH LINK USB) cable"),
1150 0,
1151 &slv_prepare,
1152 &slv_open, &slv_close, &slv_reset, &slv_probe, NULL,
1153 &slv_put, &slv_get, &slv_check,
1154 &noop_set_red_wire, &noop_set_white_wire,
1155 &noop_get_red_wire, &noop_get_white_wire,
1156 NULL, NULL,
1157 &noop_set_device,
1158 &slv_get_device_info
1159 };
1160
1161 extern const CableFncts cable_raw =
1162 {
1163 CABLE_USB,
1164 "USB",
1165 N_("DirectLink"),
1166 N_("DirectLink (DIRECT USB) cable"),
1167 0,
1168 &slv_prepare,
1169 &slv_open, &slv_close, &slv_reset, &raw_probe, NULL,
1170 &slv_put, &slv_get, &slv_check,
1171 &noop_set_red_wire, &noop_set_white_wire,
1172 &noop_get_red_wire, &noop_get_white_wire,
1173 NULL, NULL,
1174 &noop_set_device,
1175 &slv_get_device_info
1176 };
1177
1178 //=======================
1179
1180 // returns list of detected devices
1181 int usb_probe_device_info(const USBCableInfo **list, int *count)
1182 {
1183 int ret;
1184 if (!(ret = tigl_enum()))
1185 {
1186 *list = tigl_devices;
1187 *count = tigl_n_devices;
1188 }
1189 else
1190 {
1191 *list = NULL;
1192 *count = 0;
1193 }
1194 return ret;
1195 }