2 * I/O functions for libusb
3 * Copyright (C) 2007 Daniel Drake <dsd@gentoo.org>
4 * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include <sys/select.h>
33 /* signalfd() support is present in glibc-2.7 onwards, but glibc-2.7 contains
34 * a bug where the header is neither installed or compilable. This will be
35 * fixed for glibc-2.8. */
36 #if __GLIBC_PREREQ(2, 8)
37 #include <sys/signalfd.h>
47 /* this is a list of in-flight fp_urb_handles, sorted by timeout expiration.
48 * URBs to timeout the soonest are placed at the beginning of the list, URBs
49 * that will time out later are placed after, and urbs with infinite timeout
50 * are always placed at the very end. */
51 static struct list_head flying_urbs;
53 static int setup_signalfd(int _signum)
58 fp_dbg("signal %d", _signum);
61 sigaddset(&sigset, _signum);
62 sigfd = signalfd(-1, &sigset, 0);
64 fp_err("signalfd failed, code=%d errno=%d", sigfd, errno);
67 fp_dbg("got signalfd %d", sigfd);
71 sigaddset(&sigset, _signum);
72 return sigprocmask(SIG_BLOCK, &sigset, NULL);
75 int usbi_io_init(int _signum)
77 list_init(&flying_urbs);
78 return setup_signalfd(signum);
81 void usbi_io_exit(void)
86 static int calculate_timeout(struct libusb_urb_handle *urbh,
90 struct timespec current_time;
91 struct sigevent sigevt = {
92 .sigev_notify = SIGEV_SIGNAL,
93 .sigev_signo = signum,
95 struct itimerspec itspec;
96 struct timespec *it_value = &itspec.it_value;
101 r = clock_gettime(CLOCK_MONOTONIC, ¤t_time);
103 fp_err("failed to read monotonic clock, errno=%d", errno);
107 r = timer_create(CLOCK_MONOTONIC, &sigevt, &urbh->timer);
109 fp_err("failed to create monotonic timer");
113 memset(&itspec, 0, sizeof(itspec));
114 it_value->tv_sec = current_time.tv_sec + (timeout / 1000);
115 it_value->tv_nsec = current_time.tv_nsec +
116 ((timeout % 1000) * 1000000);
118 if (it_value->tv_nsec > 1000000000) {
119 it_value->tv_nsec -= 1000000000;
123 r = timer_settime(&urbh->timer, TIMER_ABSTIME, &itspec, NULL);
125 fp_err("failed to arm monotonic timer");
129 urbh->timeout = itspec.it_value;
134 static void add_to_flying_list(struct libusb_urb_handle *urbh)
136 struct libusb_urb_handle *cur;
137 struct timespec *timeout = &urbh->timeout;
139 /* if we have no other flying urbs, start the list with this one */
140 if (list_empty(&flying_urbs)) {
141 list_add(&urbh->list, &flying_urbs);
145 /* if we have infinite timeout, append to end of list */
146 if (!TIMESPEC_IS_SET(timeout)) {
147 list_add_tail(&urbh->list, &flying_urbs);
151 /* otherwise, find appropriate place in list */
152 list_for_each_entry(cur, &flying_urbs, list) {
153 /* find first timeout that occurs after the urbh in question */
154 struct timespec *cur_ts = &cur->timeout;
156 if (!TIMESPEC_IS_SET(cur_ts) || (cur_ts->tv_sec > timeout->tv_sec) ||
157 (cur_ts->tv_sec == timeout->tv_sec &&
158 cur_ts->tv_nsec > timeout->tv_nsec)) {
159 list_add_tail(&urbh->list, &cur->list);
164 /* otherwise we need to be inserted at the end */
165 list_add_tail(&urbh->list, &flying_urbs);
168 static int submit_urb(struct libusb_dev_handle *devh,
169 struct libusb_urb_handle *urbh)
172 struct usb_urb *urb = &urbh->urb;
173 int to_be_transferred = urbh->transfer_len - urbh->transferred;
175 urb->type = urbh->urb_type;
176 urb->endpoint = urbh->endpoint;
177 urb->buffer = urbh->buffer + urbh->transferred;
178 urb->buffer_length = MIN(to_be_transferred, MAX_URB_BUFFER_LENGTH);
181 /* FIXME: for requests that we have to split into multiple URBs, we should
182 * submit all the URBs instantly: submit, submit, submit, reap, reap, reap
183 * rather than: submit, reap, submit, reap, submit, reap
184 * this will improve performance and fix bugs concerning behaviour when
185 * the user submits two similar multiple-urb requests */
186 fp_dbg("transferring %d from %d bytes", urb->buffer_length,
189 r = ioctl(devh->fd, IOCTL_USB_SUBMITURB, &urbh->urb);
191 fp_err("submiturb failed error %d errno=%d", r, errno);
195 add_to_flying_list(urbh);
199 API_EXPORTED struct libusb_urb_handle *libusb_submit_ctrl_msg(
200 struct libusb_dev_handle *devh, struct libusb_ctrl_msg *msg,
201 libusb_ctrl_cb_fn callback, void *user_data, unsigned int timeout)
203 struct libusb_urb_handle *urbh = malloc(sizeof(*urbh));
204 struct libusb_ctrl_setup *setup;
205 unsigned char *urbdata;
206 int urbdata_length = sizeof(struct libusb_ctrl_setup) + msg->length;
211 memset(urbh, 0, sizeof(*urbh));
213 urbh->callback = callback;
214 urbh->user_data = user_data;
215 r = calculate_timeout(urbh, timeout);
221 urbdata = malloc(urbdata_length);
227 fp_dbg("RQT=%02x RQ=%02x VAL=%04x IDX=%04x length=%d",
228 msg->requesttype, msg->request, msg->value, msg->index, msg->length);
230 setup = (struct libusb_ctrl_setup *) urbdata;
231 setup->bRequestType = msg->requesttype;
232 setup->bRequest = msg->request;
233 setup->wValue = cpu_to_le16(msg->value);
234 setup->wIndex = cpu_to_le16(msg->index);
235 setup->wLength = cpu_to_le16(msg->length);
237 if ((msg->requesttype & 0x80) == LIBUSB_ENDPOINT_OUT)
238 memcpy(urbdata + sizeof(struct libusb_ctrl_setup), msg->data, msg->length);
240 urbh->urb_type = USB_URB_TYPE_CONTROL;
241 urbh->buffer = urbdata;
242 urbh->transfer_len = urbdata_length;
244 r = submit_urb(devh, urbh);
254 static struct libusb_urb_handle *submit_bulk_msg(struct libusb_dev_handle *devh,
255 struct libusb_bulk_msg *msg, libusb_bulk_cb_fn callback, void *user_data,
256 unsigned int timeout, unsigned char urbtype)
258 struct libusb_urb_handle *urbh = malloc(sizeof(*urbh));
261 fp_dbg("length %d timeout %d", msg->length, timeout);
265 memset(urbh, 0, sizeof(*urbh));
266 r = calculate_timeout(urbh, timeout);
272 urbh->callback = callback;
273 urbh->user_data = user_data;
274 urbh->flags |= LIBUSB_URBH_DATA_BELONGS_TO_USER;
275 urbh->endpoint = msg->endpoint;
276 urbh->urb_type = urbtype;
277 urbh->buffer = msg->data;
278 urbh->transfer_len = msg->length;
280 r = submit_urb(devh, urbh);
289 API_EXPORTED struct libusb_urb_handle *libusb_submit_bulk_msg(
290 struct libusb_dev_handle *devh, struct libusb_bulk_msg *msg,
291 libusb_bulk_cb_fn callback, void *user_data, unsigned int timeout)
293 return submit_bulk_msg(devh, msg, callback, user_data, timeout,
297 API_EXPORTED struct libusb_urb_handle *libusb_submit_intr_msg(
298 struct libusb_dev_handle *devh, struct libusb_bulk_msg *msg,
299 libusb_bulk_cb_fn callback, void *user_data, unsigned int timeout)
301 return submit_bulk_msg(devh, msg, callback, user_data, timeout,
302 USB_URB_TYPE_INTERRUPT);
305 API_EXPORTED int libusb_urb_handle_cancel(struct libusb_dev_handle *devh,
306 struct libusb_urb_handle *urbh)
310 r = ioctl(devh->fd, IOCTL_USB_DISCARDURB, &urbh->urb);
312 fp_err("cancel urb failed error %d", r);
316 API_EXPORTED int libusb_urb_handle_cancel_sync(struct libusb_dev_handle *devh,
317 struct libusb_urb_handle *urbh)
321 r = ioctl(devh->fd, IOCTL_USB_DISCARDURB, &urbh->urb);
323 fp_err("cancel urb failed error %d", r);
327 urbh->flags |= LIBUSB_URBH_SYNC_CANCELLED;
328 while (urbh->flags & LIBUSB_URBH_SYNC_CANCELLED) {
337 int handle_transfer_completion(struct libusb_dev_handle *devh,
338 struct libusb_urb_handle *urbh, enum fp_urb_cb_status status)
340 struct usb_urb *urb = &urbh->urb;
342 if (TIMESPEC_IS_SET(&urbh->timeout))
343 timer_delete(urbh->timer);
345 if (status == FP_URB_SILENT_COMPLETION)
348 if (urb->type == USB_URB_TYPE_CONTROL) {
349 libusb_ctrl_cb_fn callback = urbh->callback;
351 callback(devh, urbh, status, urb->buffer,
352 urb->buffer + sizeof(struct libusb_ctrl_setup), urbh->transferred,
354 } else if (urb->type == USB_URB_TYPE_BULK ||
355 urb->type == USB_URB_TYPE_INTERRUPT) {
356 libusb_bulk_cb_fn callback = urbh->callback;
358 callback(devh, urbh, status, urbh->endpoint, urbh->transfer_len,
359 urbh->buffer, urbh->transferred, urbh->user_data);
364 static int handle_transfer_cancellation(struct libusb_dev_handle *devh,
365 struct libusb_urb_handle *urbh)
367 /* if the URB is being cancelled synchronously, raise cancellation
368 * completion event by unsetting flag, and ensure that user callback does
371 if (urbh->flags & LIBUSB_URBH_SYNC_CANCELLED) {
372 urbh->flags &= ~LIBUSB_URBH_SYNC_CANCELLED;
373 fp_dbg("detected sync. cancel");
374 return handle_transfer_completion(devh, urbh, FP_URB_SILENT_COMPLETION);
377 /* if the URB was cancelled due to timeout, report timeout to the user */
378 if (urbh->flags & LIBUSB_URBH_TIMED_OUT) {
379 fp_dbg("detected timeout cancellation");
380 return handle_transfer_completion(devh, urbh, FP_URB_TIMEOUT);
383 /* otherwise its a normal async cancel */
384 return handle_transfer_completion(devh, urbh, FP_URB_CANCELLED);
387 static int reap_for_devh(struct libusb_dev_handle *devh)
391 struct libusb_urb_handle *urbh;
394 r = ioctl(devh->fd, IOCTL_USB_REAPURBNDELAY, &urb);
395 if (r == -1 && errno == EAGAIN)
398 fp_err("reap failed error %d errno=%d", r, errno);
402 urbh = container_of(urb, struct libusb_urb_handle, urb);
404 fp_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
406 list_del(&urbh->list);
408 if (urb->status == -2)
409 return handle_transfer_cancellation(devh, urbh);
410 /* FIXME: research what other status codes may exist */
411 if (urb->status != 0)
412 fp_warn("unrecognised urb status %d", urb->status);
414 /* determine how much data was asked for */
415 trf_requested = MIN(urbh->transfer_len - urbh->transferred,
416 MAX_URB_BUFFER_LENGTH);
418 urbh->transferred += urb->actual_length;
420 /* if we were provided less data than requested, then our transfer is
422 if (urb->actual_length < trf_requested) {
423 fp_dbg("less data than requested (%d/%d) --> all done",
424 urb->actual_length, trf_requested);
425 return handle_transfer_completion(devh, urbh, FP_URB_COMPLETED);
428 /* if we've transferred all data, we're done */
429 if (urbh->transferred == urbh->transfer_len) {
430 fp_dbg("transfer complete --> all done");
431 return handle_transfer_completion(devh, urbh, FP_URB_COMPLETED);
434 /* otherwise, we have more data to transfer */
435 fp_dbg("more data to transfer...");
436 memset(urb, 0, sizeof(*urb));
437 return submit_urb(devh, urbh);
440 static void handle_timeout(struct libusb_urb_handle *urbh)
442 /* handling timeouts is tricky, as we may race with the kernel: we may
443 * detect a timeout racing with the condition that the urb has actually
444 * completed. we asynchronously cancel the URB and report timeout
445 * to the user when the URB cancellation completes (or not at all if the
446 * URB actually gets delivered as per this race) */
450 urbh->flags |= LIBUSB_URBH_TIMED_OUT;
451 r = libusb_urb_handle_cancel(urbh->devh, urbh);
453 fp_warn("async cancel failed %d errno=%d", r, errno);
456 static int handle_timeouts(void)
458 struct timespec systime;
459 struct libusb_urb_handle *urbh;
462 if (list_empty(&flying_urbs))
465 /* get current time */
466 r = clock_gettime(CLOCK_MONOTONIC, &systime);
470 /* iterate through flying urbs list, finding all urbs that have expired
472 list_for_each_entry(urbh, &flying_urbs, list) {
473 struct timespec *cur_ts = &urbh->timeout;
475 /* if we've reached urbs of infinite timeout, we're all done */
476 if (!TIMESPEC_IS_SET(cur_ts))
479 /* if urb has non-expired timeout, nothing more to do */
480 if ((cur_ts->tv_sec > systime.tv_sec) ||
481 (cur_ts->tv_sec == systime.tv_sec &&
482 cur_ts->tv_nsec > systime.tv_nsec))
485 /* otherwise, we've got an expired timeout to handle */
486 handle_timeout(urbh);
492 static int reap(void)
494 struct libusb_dev_handle *devh;
497 list_for_each_entry(devh, &open_devs, list) {
498 r = reap_for_devh(devh);
499 if (r == -1 && errno == EAGAIN)
505 r = handle_timeouts();
510 static int flush_sigfd(void)
513 struct signalfd_siginfo siginfo;
514 r = read(sigfd, &siginfo, sizeof(siginfo));
516 fp_err("sigfd read failed %d %d", r, errno);
519 if ((unsigned int) r < sizeof(siginfo)) {
520 fp_err("sigfd short read (%d/%d)", r, sizeof(siginfo));
526 static int poll_io(struct timeval *tv)
533 r = select(sigfd + 1, &fds, NULL, NULL, tv);
534 if (r == -1 && errno == EINTR)
537 fp_err("select failed %d err=%d\n", r, errno);
549 API_EXPORTED int libusb_poll_timeout(struct timeval *tv)
554 API_EXPORTED int libusb_poll(void)
562 struct sync_ctrl_handle {
563 enum fp_urb_cb_status status;
568 static void ctrl_msg_cb(struct libusb_dev_handle *devh,
569 struct libusb_urb_handle *urbh, enum fp_urb_cb_status status,
570 struct libusb_ctrl_setup *setup, unsigned char *data, int actual_length,
573 struct sync_ctrl_handle *ctrlh = (struct sync_ctrl_handle *) user_data;
574 fp_dbg("actual_length=%d", actual_length);
576 if (status == FP_URB_COMPLETED) {
577 /* copy results into user-defined buffer */
578 if (setup->bRequestType & LIBUSB_ENDPOINT_IN)
579 memcpy(ctrlh->data, data, actual_length);
582 ctrlh->status = status;
583 ctrlh->actual_length = actual_length;
584 /* caller frees urbh */
587 API_EXPORTED int libusb_ctrl_msg(struct libusb_dev_handle *devh,
588 struct libusb_ctrl_msg *msg, unsigned int timeout)
590 struct libusb_urb_handle *urbh;
591 struct sync_ctrl_handle ctrlh;
593 memset(&ctrlh, 0, sizeof(ctrlh));
594 ctrlh.data = msg->data;
596 urbh = libusb_submit_ctrl_msg(devh, msg, ctrl_msg_cb, &ctrlh, timeout);
600 while (!ctrlh.status) {
601 int r = libusb_poll();
603 libusb_urb_handle_cancel_sync(devh, urbh);
604 libusb_urb_handle_free(urbh);
609 libusb_urb_handle_free(urbh);
610 switch (ctrlh.status) {
611 case FP_URB_COMPLETED:
612 return ctrlh.actual_length;
616 fp_warn("unrecognised status code %d", ctrlh.status);
621 struct sync_bulk_handle {
622 enum fp_urb_cb_status status;
626 static void bulk_msg_cb(struct libusb_dev_handle *devh,
627 struct libusb_urb_handle *urbh, enum fp_urb_cb_status status,
628 unsigned char endpoint, int rqlength, unsigned char *data,
629 int actual_length, void *user_data)
631 struct sync_bulk_handle *bulkh = (struct sync_bulk_handle *) user_data;
633 bulkh->status = status;
634 bulkh->actual_length = actual_length;
635 /* caller frees urbh */
638 static int do_sync_bulk_msg(struct libusb_dev_handle *devh,
639 struct libusb_bulk_msg *msg, int *transferred, unsigned int timeout,
640 unsigned char urbtype)
642 struct libusb_urb_handle *urbh;
643 struct sync_bulk_handle bulkh;
645 memset(&bulkh, 0, sizeof(bulkh));
647 urbh = submit_bulk_msg(devh, msg, bulk_msg_cb, &bulkh, timeout, urbtype);
651 while (!bulkh.status) {
652 int r = libusb_poll();
654 libusb_urb_handle_cancel_sync(devh, urbh);
655 libusb_urb_handle_free(urbh);
660 *transferred = bulkh.actual_length;
661 libusb_urb_handle_free(urbh);
663 switch (bulkh.status) {
664 case FP_URB_COMPLETED:
669 fp_warn("unrecognised status code %d", bulkh.status);
674 API_EXPORTED int libusb_intr_msg(struct libusb_dev_handle *devh,
675 struct libusb_bulk_msg *msg, int *transferred, unsigned int timeout)
677 return do_sync_bulk_msg(devh, msg, transferred, timeout,
678 USB_URB_TYPE_INTERRUPT);
681 API_EXPORTED int libusb_bulk_msg(struct libusb_dev_handle *devh,
682 struct libusb_bulk_msg *msg, int *transferred, unsigned int timeout)
684 return do_sync_bulk_msg(devh, msg, transferred, timeout,
688 API_EXPORTED void libusb_urb_handle_free(struct libusb_urb_handle *urbh)
693 if (!(urbh->flags & LIBUSB_URBH_DATA_BELONGS_TO_USER))
694 free(urbh->urb.buffer);
698 API_EXPORTED int libusb_get_pollfd(void)