libusb 1.0.20-rc3
[platform/upstream/libusb.git] / libusb / io.c
index 58bdcdf..279288c 100644 (file)
@@ -1,7 +1,8 @@
+/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
 /*
  * I/O functions for libusb
- * Copyright (C) 2007-2009 Daniel Drake <dsd@gentoo.org>
- * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
+ * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
+ * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  */
 
 #include <config.h>
+
+#include <assert.h>
 #include <errno.h>
-#include <signal.h>
 #include <stdint.h>
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
-
+#ifdef HAVE_SIGNAL_H
+#include <signal.h>
+#endif
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-
 #ifdef USBI_TIMERFD_AVAILABLE
 #include <sys/timerfd.h>
 #endif
 
 #include "libusbi.h"
+#include "hotplug.h"
 
 /**
  * \page io Synchronous and asynchronous device I/O
  *
- * \section intro Introduction
+ * \section io_intro Introduction
  *
  * If you're using libusb in your application, you're probably wanting to
  * perform I/O with devices - you want to perform USB data transfers.
@@ -462,6 +466,14 @@ if (r == 0 && actual_length == sizeof(data)) {
  * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple()
  * functions may help you here.
  *
+ * <b>Note</b>: Some operating systems (e.g. Linux) may impose limits on the
+ * length of individual isochronous packets and/or the total length of the
+ * isochronous transfer. Such limits can be difficult for libusb to detect,
+ * so the library will simply try and submit the transfer as set up by you.
+ * If the transfer fails to submit because it is too large,
+ * libusb_submit_transfer() will return
+ * \ref libusb_error::LIBUSB_ERROR_INVALID_PARAM "LIBUSB_ERROR_INVALID_PARAM".
+ *
  * \section asyncmem Memory caveats
  *
  * In most circumstances, it is not safe to use stack memory for transfer
@@ -494,10 +506,7 @@ if (r == 0 && actual_length == sizeof(data)) {
  *
  * \section asyncevent Event handling
  *
- * In accordance of the aim of being a lightweight library, libusb does not
- * create threads internally. This means that libusb code does not execute
- * at any time other than when your application is calling a libusb function.
- * However, an asynchronous model requires that libusb perform work at various
+ * An asynchronous model requires that libusb perform work at various
  * points in time - namely processing the results of previously-submitted
  * transfers and invoking the user-supplied callback function.
  *
@@ -505,39 +514,79 @@ if (r == 0 && actual_length == sizeof(data)) {
  * application must call into when libusb has work do to. This gives libusb
  * the opportunity to reap pending transfers, invoke callbacks, etc.
  *
- * The first issue to discuss here is how your application can figure out
- * when libusb has work to do. In fact, there are two naive options which
- * do not actually require your application to know this:
- * -# Periodically call libusb_handle_events() in non-blocking mode at fixed
- *    short intervals from your main loop
+ * There are 2 different approaches to dealing with libusb_handle_events:
+ *
  * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated
  *    thread.
+ * -# Integrate libusb with your application's main event loop. libusb
+ *    exposes a set of file descriptors which allow you to do this.
  *
- * The first option is plainly not very nice, and will cause unnecessary
- * CPU wakeups leading to increased power usage and decreased battery life.
- * The second option is not very nice either, but may be the nicest option
- * available to you if the "proper" approach can not be applied to your
- * application (read on...).
+ * The first approach has the big advantage that it will also work on Windows
+ * were libusb' poll API for select / poll integration is not available. So
+ * if you want to support Windows and use the async API, you must use this
+ * approach, see the \ref eventthread "Using an event handling thread" section
+ * below for details.
  *
- * The recommended option is to integrate libusb with your application main
- * event loop. libusb exposes a set of file descriptors which allow you to do
- * this. Your main loop is probably already calling poll() or select() or a
- * variant on a set of file descriptors for other event sources (e.g. keyboard
- * button presses, mouse movements, network sockets, etc). You then add
- * libusb's file descriptors to your poll()/select() calls, and when activity
- * is detected on such descriptors you know it is time to call
- * libusb_handle_events().
+ * If you prefer a single threaded approach with a single central event loop,
+ * see the \ref poll "polling and timing" section for how to integrate libusb
+ * into your application's main event loop.
  *
- * There is one final event handling complication. libusb supports
- * asynchronous transfers which time out after a specified time period, and
- * this requires that libusb is called into at or after the timeout so that
- * the timeout can be handled. So, in addition to considering libusb's file
- * descriptors in your main event loop, you must also consider that libusb
- * sometimes needs to be called into at fixed points in time even when there
- * is no file descriptor activity.
+ * \section eventthread Using an event handling thread
+ *
+ * Lets begin with stating the obvious: If you're going to use a separate
+ * thread for libusb event handling, your callback functions MUST be
+ * threadsafe.
+ *
+ * Other then that doing event handling from a separate thread, is mostly
+ * simple. You can use an event thread function as follows:
+\code
+void *event_thread_func(void *ctx)
+{
+    while (event_thread_run)
+        libusb_handle_events(ctx);
+
+    return NULL;
+}
+\endcode
+ *
+ * There is one caveat though, stopping this thread requires setting the
+ * event_thread_run variable to 0, and after that libusb_handle_events() needs
+ * to return control to event_thread_func. But unless some event happens,
+ * libusb_handle_events() will not return.
+ *
+ * There are 2 different ways of dealing with this, depending on if your
+ * application uses libusb' \ref hotplug "hotplug" support or not.
  *
- * For the details on retrieving the set of file descriptors and determining
- * the next timeout, see the \ref poll "polling and timing" API documentation.
+ * Applications which do not use hotplug support, should not start the event
+ * thread until after their first call to libusb_open(), and should stop the
+ * thread when closing the last open device as follows:
+\code
+void my_close_handle(libusb_device_handle *handle)
+{
+    if (open_devs == 1)
+        event_thread_run = 0;
+
+    libusb_close(handle); // This wakes up libusb_handle_events()
+
+    if (open_devs == 1)
+        pthread_join(event_thread);
+
+    open_devs--;
+}
+\endcode
+ *
+ * Applications using hotplug support should start the thread at program init,
+ * after having successfully called libusb_hotplug_register_callback(), and
+ * should stop the thread at program exit as follows:
+\code
+void my_libusb_exit(void)
+{ 
+    event_thread_run = 0;
+    libusb_hotplug_deregister_callback(ctx, hotplug_cb_handle); // This wakes up libusb_handle_events()
+    pthread_join(event_thread);
+    libusb_exit(ctx);
+}
+\endcode
  */
 
 /**
@@ -554,6 +603,24 @@ if (r == 0 && actual_length == sizeof(data)) {
  * asynchronous API documentation. In summary, libusb does not create internal
  * threads for event processing and hence relies on your application calling
  * into libusb at certain points in time so that pending events can be handled.
+ *
+ * Your main loop is probably already calling poll() or select() or a
+ * variant on a set of file descriptors for other event sources (e.g. keyboard
+ * button presses, mouse movements, network sockets, etc). You then add
+ * libusb's file descriptors to your poll()/select() calls, and when activity
+ * is detected on such descriptors you know it is time to call
+ * libusb_handle_events().
+ *
+ * There is one final event handling complication. libusb supports
+ * asynchronous transfers which time out after a specified time period.
+ *
+ * On some platforms a timerfd is used, so the timeout handling is just another
+ * fd, on other platforms this requires that libusb is called into at or after
+ * the timeout to handle it. So, in addition to considering libusb's file
+ * descriptors in your main event loop, you must also consider that libusb
+ * sometimes needs to be called into at fixed points in time even when there
+ * is no file descriptor activity, see \ref polltime details.
+ * 
  * In order to know precisely when libusb needs to be called into, libusb
  * offers you a set of pollable file descriptors and information about when
  * the next timeout expires.
@@ -583,8 +650,9 @@ while (user_has_not_requested_exit)
  * \section pollmain The more advanced option
  *
  * \note This functionality is currently only available on Unix-like platforms.
- * On Windows, libusb_get_pollfds() simply returns NULL. Exposing event sources
- * on Windows will require some further thought and design.
+ * On Windows, libusb_get_pollfds() simply returns NULL. Applications which
+ * want to support Windows are advised to use an \ref eventthread
+ * "event handling thread" instead.
  *
  * In more advanced applications, you will already have a main loop which
  * is monitoring other event sources: network sockets, X11 events, mouse
@@ -729,7 +797,7 @@ void cb(struct libusb_transfer *transfer)
 
 void myfunc() {
        struct libusb_transfer *transfer;
-       unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE];
+       unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE] __attribute__ ((aligned (2)));
        int completed = 0;
 
        transfer = libusb_alloc_transfer(0);
@@ -972,7 +1040,7 @@ printf("completed!\n");
  *
  * -# During initialization, libusb opens an internal pipe, and it adds the read
  *    end of this pipe to the set of file descriptors to be polled.
- * -# During libusb_close(), libusb writes some dummy data on this control pipe.
+ * -# During libusb_close(), libusb writes some dummy data on this event pipe.
  *    This immediately interrupts the event handler. libusb also records
  *    internally that it is trying to interrupt event handlers for this
  *    high-priority event.
@@ -1005,7 +1073,7 @@ printf("completed!\n");
  * call to libusb_open():
  *
  * -# The device is opened and a file descriptor is added to the poll set.
- * -# libusb sends some dummy data on the control pipe, and records that it
+ * -# libusb sends some dummy data on the event pipe, and records that it
  *    is trying to modify the poll descriptor set.
  * -# The event handler is interrupted, and the same behaviour change as for
  *    libusb_close() takes effect, causing all event handling threads to become
@@ -1051,22 +1119,23 @@ int usbi_io_init(struct libusb_context *ctx)
        int r;
 
        usbi_mutex_init(&ctx->flying_transfers_lock, NULL);
-       usbi_mutex_init(&ctx->pollfds_lock, NULL);
-       usbi_mutex_init(&ctx->pollfd_modify_lock, NULL);
        usbi_mutex_init_recursive(&ctx->events_lock, NULL);
        usbi_mutex_init(&ctx->event_waiters_lock, NULL);
        usbi_cond_init(&ctx->event_waiters_cond, NULL);
+       usbi_mutex_init(&ctx->event_data_lock, NULL);
        list_init(&ctx->flying_transfers);
-       list_init(&ctx->pollfds);
+       list_init(&ctx->ipollfds);
+       list_init(&ctx->hotplug_msgs);
+       list_init(&ctx->completed_transfers);
 
        /* FIXME should use an eventfd on kernels that support it */
-       r = usbi_pipe(ctx->ctrl_pipe);
+       r = usbi_pipe(ctx->event_pipe);
        if (r < 0) {
                r = LIBUSB_ERROR_OTHER;
                goto err;
        }
 
-       r = usbi_add_pollfd(ctx, ctx->ctrl_pipe[0], POLLIN);
+       r = usbi_add_pollfd(ctx, ctx->event_pipe[0], POLLIN);
        if (r < 0)
                goto err_close_pipe;
 
@@ -1076,11 +1145,8 @@ int usbi_io_init(struct libusb_context *ctx)
        if (ctx->timerfd >= 0) {
                usbi_dbg("using timerfd for timeouts");
                r = usbi_add_pollfd(ctx, ctx->timerfd, POLLIN);
-               if (r < 0) {
-                       usbi_remove_pollfd(ctx, ctx->ctrl_pipe[0]);
-                       close(ctx->timerfd);
-                       goto err_close_pipe;
-               }
+               if (r < 0)
+                       goto err_close_timerfd;
        } else {
                usbi_dbg("timerfd not available (code %d error %d)", ctx->timerfd, errno);
                ctx->timerfd = -1;
@@ -1089,24 +1155,28 @@ int usbi_io_init(struct libusb_context *ctx)
 
        return 0;
 
+#ifdef USBI_TIMERFD_AVAILABLE
+err_close_timerfd:
+       close(ctx->timerfd);
+       usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
+#endif
 err_close_pipe:
-       usbi_close(ctx->ctrl_pipe[0]);
-       usbi_close(ctx->ctrl_pipe[1]);
+       usbi_close(ctx->event_pipe[0]);
+       usbi_close(ctx->event_pipe[1]);
 err:
        usbi_mutex_destroy(&ctx->flying_transfers_lock);
-       usbi_mutex_destroy(&ctx->pollfds_lock);
-       usbi_mutex_destroy(&ctx->pollfd_modify_lock);
        usbi_mutex_destroy(&ctx->events_lock);
        usbi_mutex_destroy(&ctx->event_waiters_lock);
        usbi_cond_destroy(&ctx->event_waiters_cond);
+       usbi_mutex_destroy(&ctx->event_data_lock);
        return r;
 }
 
 void usbi_io_exit(struct libusb_context *ctx)
 {
-       usbi_remove_pollfd(ctx, ctx->ctrl_pipe[0]);
-       usbi_close(ctx->ctrl_pipe[0]);
-       usbi_close(ctx->ctrl_pipe[1]);
+       usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
+       usbi_close(ctx->event_pipe[0]);
+       usbi_close(ctx->event_pipe[1]);
 #ifdef USBI_TIMERFD_AVAILABLE
        if (usbi_using_timerfd(ctx)) {
                usbi_remove_pollfd(ctx, ctx->timerfd);
@@ -1114,11 +1184,12 @@ void usbi_io_exit(struct libusb_context *ctx)
        }
 #endif
        usbi_mutex_destroy(&ctx->flying_transfers_lock);
-       usbi_mutex_destroy(&ctx->pollfds_lock);
-       usbi_mutex_destroy(&ctx->pollfd_modify_lock);
        usbi_mutex_destroy(&ctx->events_lock);
        usbi_mutex_destroy(&ctx->event_waiters_lock);
        usbi_cond_destroy(&ctx->event_waiters_cond);
+       usbi_mutex_destroy(&ctx->event_data_lock);
+       if (ctx->pollfds)
+               free(ctx->pollfds);
 }
 
 static int calculate_timeout(struct usbi_transfer *transfer)
@@ -1141,7 +1212,7 @@ static int calculate_timeout(struct usbi_transfer *transfer)
        current_time.tv_sec += timeout / 1000;
        current_time.tv_nsec += (timeout % 1000) * 1000000;
 
-       if (current_time.tv_nsec > 1000000000) {
+       while (current_time.tv_nsec >= 1000000000) {
                current_time.tv_nsec -= 1000000000;
                current_time.tv_sec++;
        }
@@ -1150,55 +1221,6 @@ static int calculate_timeout(struct usbi_transfer *transfer)
        return 0;
 }
 
-/* add a transfer to the (timeout-sorted) active transfers list.
- * returns 1 if the transfer has a timeout and it is the timeout next to
- * expire */
-static int add_to_flying_list(struct usbi_transfer *transfer)
-{
-       struct usbi_transfer *cur;
-       struct timeval *timeout = &transfer->timeout;
-       struct libusb_context *ctx = ITRANSFER_CTX(transfer);
-       int r = 0;
-       int first = 1;
-
-       usbi_mutex_lock(&ctx->flying_transfers_lock);
-
-       /* if we have no other flying transfers, start the list with this one */
-       if (list_empty(&ctx->flying_transfers)) {
-               list_add(&transfer->list, &ctx->flying_transfers);
-               if (timerisset(timeout))
-                       r = 1;
-               goto out;
-       }
-
-       /* if we have infinite timeout, append to end of list */
-       if (!timerisset(timeout)) {
-               list_add_tail(&transfer->list, &ctx->flying_transfers);
-               goto out;
-       }
-
-       /* otherwise, find appropriate place in list */
-       list_for_each_entry(cur, &ctx->flying_transfers, list, struct usbi_transfer) {
-               /* find first timeout that occurs after the transfer in question */
-               struct timeval *cur_tv = &cur->timeout;
-
-               if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
-                               (cur_tv->tv_sec == timeout->tv_sec &&
-                                       cur_tv->tv_usec > timeout->tv_usec)) {
-                       list_add_tail(&transfer->list, &cur->list);
-                       r = first;
-                       goto out;
-               }
-               first = 0;
-       }
-
-       /* otherwise we need to be inserted at the end */
-       list_add_tail(&transfer->list, &ctx->flying_transfers);
-out:
-       usbi_mutex_unlock(&ctx->flying_transfers_lock);
-       return r;
-}
-
 /** \ingroup asyncio
  * Allocate a libusb transfer with a specified number of isochronous packet
  * descriptors. The returned transfer is pre-initialized for you. When the new
@@ -1226,20 +1248,22 @@ DEFAULT_VISIBILITY
 struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(
        int iso_packets)
 {
-       size_t os_alloc_size = usbi_backend->transfer_priv_size
-               + (usbi_backend->add_iso_packet_size * iso_packets);
+       struct libusb_transfer *transfer;
+       size_t os_alloc_size = usbi_backend->transfer_priv_size;
        size_t alloc_size = sizeof(struct usbi_transfer)
                + sizeof(struct libusb_transfer)
                + (sizeof(struct libusb_iso_packet_descriptor) * iso_packets)
                + os_alloc_size;
-       struct usbi_transfer *itransfer = malloc(alloc_size);
+       struct usbi_transfer *itransfer = calloc(1, alloc_size);
        if (!itransfer)
                return NULL;
 
-       memset(itransfer, 0, alloc_size);
        itransfer->num_iso_packets = iso_packets;
        usbi_mutex_init(&itransfer->lock, NULL);
-       return USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
+       usbi_mutex_init(&itransfer->flags_lock, NULL);
+       transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
+       usbi_dbg("transfer %p", transfer);
+       return transfer;
 }
 
 /** \ingroup asyncio
@@ -1265,14 +1289,161 @@ void API_EXPORTED libusb_free_transfer(struct libusb_transfer *transfer)
        if (!transfer)
                return;
 
+       usbi_dbg("transfer %p", transfer);
        if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)
                free(transfer->buffer);
 
        itransfer = LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
        usbi_mutex_destroy(&itransfer->lock);
+       usbi_mutex_destroy(&itransfer->flags_lock);
        free(itransfer);
 }
 
+#ifdef USBI_TIMERFD_AVAILABLE
+static int disarm_timerfd(struct libusb_context *ctx)
+{
+       const struct itimerspec disarm_timer = { { 0, 0 }, { 0, 0 } };
+       int r;
+
+       usbi_dbg("");
+       r = timerfd_settime(ctx->timerfd, 0, &disarm_timer, NULL);
+       if (r < 0)
+               return LIBUSB_ERROR_OTHER;
+       else
+               return 0;
+}
+
+/* iterates through the flying transfers, and rearms the timerfd based on the
+ * next upcoming timeout.
+ * must be called with flying_list locked.
+ * returns 0 on success or a LIBUSB_ERROR code on failure.
+ */
+static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
+{
+       struct usbi_transfer *transfer;
+
+       list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
+               struct timeval *cur_tv = &transfer->timeout;
+
+               /* if we've reached transfers of infinite timeout, then we have no
+                * arming to do */
+               if (!timerisset(cur_tv))
+                       goto disarm;
+
+               /* act on first transfer that is not already cancelled */
+               if (!(transfer->flags & USBI_TRANSFER_TIMEOUT_HANDLED)) {
+                       int r;
+                       const struct itimerspec it = { {0, 0},
+                               { cur_tv->tv_sec, cur_tv->tv_usec * 1000 } };
+                       usbi_dbg("next timeout originally %dms", USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
+                       r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
+                       if (r < 0)
+                               return LIBUSB_ERROR_OTHER;
+                       return 0;
+               }
+       }
+
+disarm:
+       return disarm_timerfd(ctx);
+}
+#else
+static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
+{
+       (void)ctx;
+       return 0;
+}
+#endif
+
+/* add a transfer to the (timeout-sorted) active transfers list.
+ * This function will return non 0 if fails to update the timer,
+ * in which case the transfer is *not* on the flying_transfers list. */
+static int add_to_flying_list(struct usbi_transfer *transfer)
+{
+       struct usbi_transfer *cur;
+       struct timeval *timeout = &transfer->timeout;
+       struct libusb_context *ctx = ITRANSFER_CTX(transfer);
+       int r = 0;
+       int first = 1;
+
+       usbi_mutex_lock(&ctx->flying_transfers_lock);
+
+       /* if we have no other flying transfers, start the list with this one */
+       if (list_empty(&ctx->flying_transfers)) {
+               list_add(&transfer->list, &ctx->flying_transfers);
+               goto out;
+       }
+
+       /* if we have infinite timeout, append to end of list */
+       if (!timerisset(timeout)) {
+               list_add_tail(&transfer->list, &ctx->flying_transfers);
+               /* first is irrelevant in this case */
+               goto out;
+       }
+
+       /* otherwise, find appropriate place in list */
+       list_for_each_entry(cur, &ctx->flying_transfers, list, struct usbi_transfer) {
+               /* find first timeout that occurs after the transfer in question */
+               struct timeval *cur_tv = &cur->timeout;
+
+               if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
+                               (cur_tv->tv_sec == timeout->tv_sec &&
+                                       cur_tv->tv_usec > timeout->tv_usec)) {
+                       list_add_tail(&transfer->list, &cur->list);
+                       goto out;
+               }
+               first = 0;
+       }
+       /* first is 0 at this stage (list not empty) */
+
+       /* otherwise we need to be inserted at the end */
+       list_add_tail(&transfer->list, &ctx->flying_transfers);
+out:
+#ifdef USBI_TIMERFD_AVAILABLE
+       if (first && usbi_using_timerfd(ctx) && timerisset(timeout)) {
+               /* if this transfer has the lowest timeout of all active transfers,
+                * rearm the timerfd with this transfer's timeout */
+               const struct itimerspec it = { {0, 0},
+                       { timeout->tv_sec, timeout->tv_usec * 1000 } };
+               usbi_dbg("arm timerfd for timeout in %dms (first in line)",
+                       USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
+               r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
+               if (r < 0) {
+                       usbi_warn(ctx, "failed to arm first timerfd (errno %d)", errno);
+                       r = LIBUSB_ERROR_OTHER;
+               }
+       }
+#else
+       UNUSED(first);
+#endif
+
+       if (r)
+               list_del(&transfer->list);
+
+       usbi_mutex_unlock(&ctx->flying_transfers_lock);
+       return r;
+}
+
+/* remove a transfer from the active transfers list.
+ * This function will *always* remove the transfer from the
+ * flying_transfers list. It will return a LIBUSB_ERROR code
+ * if it fails to update the timer for the next timeout. */
+static int remove_from_flying_list(struct usbi_transfer *transfer)
+{
+       struct libusb_context *ctx = ITRANSFER_CTX(transfer);
+       int rearm_timerfd;
+       int r = 0;
+
+       usbi_mutex_lock(&ctx->flying_transfers_lock);
+       rearm_timerfd = (timerisset(&transfer->timeout) &&
+               list_first_entry(&ctx->flying_transfers, struct usbi_transfer, list) == transfer);
+       list_del(&transfer->list);
+       if (usbi_using_timerfd(ctx) && rearm_timerfd)
+               r = arm_timerfd_for_next_timeout(ctx);
+       usbi_mutex_unlock(&ctx->flying_transfers_lock);
+
+       return r;
+}
+
 /** \ingroup asyncio
  * Submit a transfer. This function will fire off the USB transfer and then
  * return immediately.
@@ -1281,17 +1452,24 @@ void API_EXPORTED libusb_free_transfer(struct libusb_transfer *transfer)
  * \returns 0 on success
  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  * \returns LIBUSB_ERROR_BUSY if the transfer has already been submitted.
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED if the transfer flags are not supported
+ * by the operating system.
  * \returns another LIBUSB_ERROR code on other failure
  */
 int API_EXPORTED libusb_submit_transfer(struct libusb_transfer *transfer)
 {
-       struct libusb_context *ctx = TRANSFER_CTX(transfer);
        struct usbi_transfer *itransfer =
                LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
+       int remove = 0;
        int r;
-       int first;
 
+       usbi_dbg("transfer %p", transfer);
        usbi_mutex_lock(&itransfer->lock);
+       usbi_mutex_lock(&itransfer->flags_lock);
+       if (itransfer->flags & USBI_TRANSFER_IN_FLIGHT) {
+               r = LIBUSB_ERROR_BUSY;
+               goto out;
+       }
        itransfer->transferred = 0;
        itransfer->flags = 0;
        r = calculate_timeout(itransfer);
@@ -1299,30 +1477,44 @@ int API_EXPORTED libusb_submit_transfer(struct libusb_transfer *transfer)
                r = LIBUSB_ERROR_OTHER;
                goto out;
        }
+       itransfer->flags |= USBI_TRANSFER_SUBMITTING;
+       usbi_mutex_unlock(&itransfer->flags_lock);
 
-       first = add_to_flying_list(itransfer);
-       r = usbi_backend->submit_transfer(itransfer);
+       r = add_to_flying_list(itransfer);
        if (r) {
-               usbi_mutex_lock(&ctx->flying_transfers_lock);
-               list_del(&itransfer->list);
-               usbi_mutex_unlock(&ctx->flying_transfers_lock);
-       }
-#ifdef USBI_TIMERFD_AVAILABLE
-       else if (first && usbi_using_timerfd(ctx)) {
-               /* if this transfer has the lowest timeout of all active transfers,
-                * rearm the timerfd with this transfer's timeout */
-               const struct itimerspec it = { {0, 0},
-                       { itransfer->timeout.tv_sec, itransfer->timeout.tv_usec * 1000 } };
-               usbi_dbg("arm timerfd for timeout in %dms (first in line)", transfer->timeout);
-               r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
-               if (r < 0)
-                       r = LIBUSB_ERROR_OTHER;
+               usbi_mutex_lock(&itransfer->flags_lock);
+               itransfer->flags = 0;
+               goto out;
        }
-#else
-       (void)first;
-#endif
 
+       /* keep a reference to this device */
+       libusb_ref_device(transfer->dev_handle->dev);
+       r = usbi_backend->submit_transfer(itransfer);
+
+       usbi_mutex_lock(&itransfer->flags_lock);
+       itransfer->flags &= ~USBI_TRANSFER_SUBMITTING;
+       if (r == LIBUSB_SUCCESS) {
+               /* check for two possible special conditions:
+                *   1) device disconnect occurred immediately after submission
+                *   2) transfer completed before we got here to update the flags
+                */
+               if (itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED) {
+                       usbi_backend->clear_transfer_priv(itransfer);
+                       remove = 1;
+                       r = LIBUSB_ERROR_NO_DEVICE;
+               }
+               else if (!(itransfer->flags & USBI_TRANSFER_COMPLETED)) {
+                       itransfer->flags |= USBI_TRANSFER_IN_FLIGHT;
+               }
+       } else {
+               remove = 1;
+       }
 out:
+       usbi_mutex_unlock(&itransfer->flags_lock);
+       if (remove) {
+               libusb_unref_device(transfer->dev_handle->dev);
+               remove_from_flying_list(itransfer);
+       }
        usbi_mutex_unlock(&itransfer->lock);
        return r;
 }
@@ -1337,8 +1529,8 @@ out:
  *
  * \param transfer the transfer to cancel
  * \returns 0 on success
- * \returns LIBUSB_ERROR_NOT_FOUND if the transfer is already complete or
- * cancelled.
+ * \returns LIBUSB_ERROR_NOT_FOUND if the transfer is not in progress,
+ * already complete, or already cancelled.
  * \returns a LIBUSB_ERROR code on failure
  */
 int API_EXPORTED libusb_cancel_transfer(struct libusb_transfer *transfer)
@@ -1347,12 +1539,22 @@ int API_EXPORTED libusb_cancel_transfer(struct libusb_transfer *transfer)
                LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
        int r;
 
-       usbi_dbg("");
+       usbi_dbg("transfer %p", transfer );
        usbi_mutex_lock(&itransfer->lock);
+       usbi_mutex_lock(&itransfer->flags_lock);
+       if (!(itransfer->flags & USBI_TRANSFER_IN_FLIGHT)
+                       || (itransfer->flags & USBI_TRANSFER_CANCELLING)) {
+               r = LIBUSB_ERROR_NOT_FOUND;
+               goto out;
+       }
        r = usbi_backend->cancel_transfer(itransfer);
        if (r < 0) {
-               usbi_err(TRANSFER_CTX(transfer),
-                       "cancel transfer failed error %d", r);
+               if (r != LIBUSB_ERROR_NOT_FOUND &&
+                   r != LIBUSB_ERROR_NO_DEVICE)
+                       usbi_err(TRANSFER_CTX(transfer),
+                               "cancel transfer failed error %d", r);
+               else
+                       usbi_dbg("cancel transfer failed error %d", r);
 
                if (r == LIBUSB_ERROR_NO_DEVICE)
                        itransfer->flags |= USBI_TRANSFER_DEVICE_DISAPPEARED;
@@ -1360,69 +1562,48 @@ int API_EXPORTED libusb_cancel_transfer(struct libusb_transfer *transfer)
 
        itransfer->flags |= USBI_TRANSFER_CANCELLING;
 
+out:
+       usbi_mutex_unlock(&itransfer->flags_lock);
        usbi_mutex_unlock(&itransfer->lock);
        return r;
 }
 
-#ifdef USBI_TIMERFD_AVAILABLE
-static int disarm_timerfd(struct libusb_context *ctx)
+/** \ingroup asyncio
+ * Set a transfers bulk stream id. Note users are advised to use
+ * libusb_fill_bulk_stream_transfer() instead of calling this function
+ * directly.
+ *
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
+ *
+ * \param transfer the transfer to set the stream id for
+ * \param stream_id the stream id to set
+ * \see libusb_alloc_streams()
+ */
+void API_EXPORTED libusb_transfer_set_stream_id(
+       struct libusb_transfer *transfer, uint32_t stream_id)
 {
-       const struct itimerspec disarm_timer = { { 0, 0 }, { 0, 0 } };
-       int r;
+       struct usbi_transfer *itransfer =
+               LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
 
-       usbi_dbg("");
-       r = timerfd_settime(ctx->timerfd, 0, &disarm_timer, NULL);
-       if (r < 0)
-               return LIBUSB_ERROR_OTHER;
-       else
-               return 0;
+       itransfer->stream_id = stream_id;
 }
 
-/* iterates through the flying transfers, and rearms the timerfd based on the
- * next upcoming timeout.
- * must be called with flying_list locked.
- * returns 0 if there was no timeout to arm, 1 if the next timeout was armed,
- * or a LIBUSB_ERROR code on failure.
+/** \ingroup asyncio
+ * Get a transfers bulk stream id.
+ *
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
+ *
+ * \param transfer the transfer to get the stream id for
+ * \returns the stream id for the transfer
  */
-static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
+uint32_t API_EXPORTED libusb_transfer_get_stream_id(
+       struct libusb_transfer *transfer)
 {
-       struct usbi_transfer *transfer;
-
-       list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
-               struct timeval *cur_tv = &transfer->timeout;
-
-               /* if we've reached transfers of infinite timeout, then we have no
-                * arming to do */
-               if (!timerisset(cur_tv))
-                       return 0;
-
-               /* act on first transfer that is not already cancelled */
-               if (!(transfer->flags & USBI_TRANSFER_TIMED_OUT)) {
-                       int r;
-                       const struct itimerspec it = { {0, 0},
-                               { cur_tv->tv_sec, cur_tv->tv_usec * 1000 } };
-                       usbi_dbg("next timeout originally %dms", USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
-                       r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
-                       if (r < 0)
-                               return LIBUSB_ERROR_OTHER;
-                       return 1;
-               }
-       }
+       struct usbi_transfer *itransfer =
+               LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
 
-       return 0;
-}
-#else
-static int disarm_timerfd(struct libusb_context *ctx)
-{
-       (void)ctx;
-       return 0;
+       return itransfer->stream_id;
 }
-static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
-{
-       (void)ctx;
-       return 0;
-}
-#endif
 
 /* Handle completion of a transfer (completion might be an error condition).
  * This will invoke the user-supplied callback function, which may end up
@@ -1437,27 +1618,18 @@ int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
 {
        struct libusb_transfer *transfer =
                USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
-       struct libusb_context *ctx = TRANSFER_CTX(transfer);
+       struct libusb_device_handle *handle = transfer->dev_handle;
        uint8_t flags;
        int r;
 
-       /* FIXME: could be more intelligent with the timerfd here. we don't need
-        * to disarm the timerfd if there was no timer running, and we only need
-        * to rearm the timerfd if the transfer that expired was the one with
-        * the shortest timeout. */
+       r = remove_from_flying_list(itransfer);
+       if (r < 0)
+               usbi_err(ITRANSFER_CTX(itransfer), "failed to set timer for next timeout, errno=%d", errno);
 
-       usbi_mutex_lock(&ctx->flying_transfers_lock);
-       list_del(&itransfer->list);
-       r = arm_timerfd_for_next_timeout(ctx);
-       usbi_mutex_unlock(&ctx->flying_transfers_lock);
-
-       if (r < 0) {
-               return r;
-       } else if (r == 0) {
-               r = disarm_timerfd(ctx);
-               if (r < 0)
-                       return r;
-       }
+       usbi_mutex_lock(&itransfer->flags_lock);
+       itransfer->flags &= ~USBI_TRANSFER_IN_FLIGHT;
+       itransfer->flags |= USBI_TRANSFER_COMPLETED;
+       usbi_mutex_unlock(&itransfer->flags_lock);
 
        if (status == LIBUSB_TRANSFER_COMPLETED
                        && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
@@ -1473,16 +1645,15 @@ int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
        flags = transfer->flags;
        transfer->status = status;
        transfer->actual_length = itransfer->transferred;
+       usbi_dbg("transfer %p has callback %p", transfer, transfer->callback);
        if (transfer->callback)
                transfer->callback(transfer);
        /* transfer might have been freed by the above call, do not use from
         * this point. */
        if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
                libusb_free_transfer(transfer);
-       usbi_mutex_lock(&ctx->event_waiters_lock);
-       usbi_cond_broadcast(&ctx->event_waiters_cond);
-       usbi_mutex_unlock(&ctx->event_waiters_lock);
-       return 0;
+       libusb_unref_device(handle->dev);
+       return r;
 }
 
 /* Similar to usbi_handle_transfer_completion() but exclusively for transfers
@@ -1503,6 +1674,22 @@ int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
        return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
 }
 
+/* Add a completed transfer to the completed_transfers list of the
+ * context and signal the event. The backend's handle_transfer_completion()
+ * function will be called the next time an event handler runs. */
+void usbi_signal_transfer_completion(struct usbi_transfer *transfer)
+{
+       struct libusb_context *ctx = ITRANSFER_CTX(transfer);
+       int pending_events;
+
+       usbi_mutex_lock(&ctx->event_data_lock);
+       pending_events = usbi_pending_events(ctx);
+       list_add_tail(&transfer->completed_list, &ctx->completed_transfers);
+       if (!pending_events)
+               usbi_signal_event(ctx);
+       usbi_mutex_unlock(&ctx->event_data_lock);
+}
+
 /** \ingroup poll
  * Attempt to acquire the event handling lock. This lock is used to ensure that
  * only one thread is monitoring libusb event sources at any one time.
@@ -1520,20 +1707,21 @@ int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
  * \param ctx the context to operate on, or NULL for the default context
  * \returns 0 if the lock was obtained successfully
  * \returns 1 if the lock was not obtained (i.e. another thread holds the lock)
- * \see \ref mtasync
+ * \ref mtasync
  */
 int API_EXPORTED libusb_try_lock_events(libusb_context *ctx)
 {
        int r;
+       unsigned int ru;
        USBI_GET_CONTEXT(ctx);
 
-       /* is someone else waiting to modify poll fds? if so, don't let this thread
+       /* is someone else waiting to close a device? if so, don't let this thread
         * start event handling */
-       usbi_mutex_lock(&ctx->pollfd_modify_lock);
-       r = ctx->pollfd_modify;
-       usbi_mutex_unlock(&ctx->pollfd_modify_lock);
-       if (r) {
-               usbi_dbg("someone else is modifying poll fds");
+       usbi_mutex_lock(&ctx->event_data_lock);
+       ru = ctx->device_close;
+       usbi_mutex_unlock(&ctx->event_data_lock);
+       if (ru) {
+               usbi_dbg("someone else is closing a device");
                return 1;
        }
 
@@ -1561,7 +1749,7 @@ int API_EXPORTED libusb_try_lock_events(libusb_context *ctx)
  * as soon as possible.
  *
  * \param ctx the context to operate on, or NULL for the default context
- * \see \ref mtasync
+ * \ref mtasync
  */
 void API_EXPORTED libusb_lock_events(libusb_context *ctx)
 {
@@ -1576,7 +1764,7 @@ void API_EXPORTED libusb_lock_events(libusb_context *ctx)
  * on libusb_wait_for_event().
  *
  * \param ctx the context to operate on, or NULL for the default context
- * \see \ref mtasync
+ * \ref mtasync
  */
 void API_EXPORTED libusb_unlock_events(libusb_context *ctx)
 {
@@ -1586,7 +1774,7 @@ void API_EXPORTED libusb_unlock_events(libusb_context *ctx)
 
        /* FIXME: perhaps we should be a bit more efficient by not broadcasting
         * the availability of the events lock when we are modifying pollfds
-        * (check ctx->pollfd_modify)? */
+        * (check ctx->device_close)? */
        usbi_mutex_lock(&ctx->event_waiters_lock);
        usbi_cond_broadcast(&ctx->event_waiters_cond);
        usbi_mutex_unlock(&ctx->event_waiters_lock);
@@ -1611,20 +1799,20 @@ void API_EXPORTED libusb_unlock_events(libusb_context *ctx)
  * \param ctx the context to operate on, or NULL for the default context
  * \returns 1 if event handling can start or continue
  * \returns 0 if this thread must give up the events lock
- * \see \ref fullstory "Multi-threaded I/O: the full story"
+ * \ref fullstory "Multi-threaded I/O: the full story"
  */
 int API_EXPORTED libusb_event_handling_ok(libusb_context *ctx)
 {
-       int r;
+       unsigned int r;
        USBI_GET_CONTEXT(ctx);
 
-       /* is someone else waiting to modify poll fds? if so, don't let this thread
+       /* is someone else waiting to close a device? if so, don't let this thread
         * continue event handling */
-       usbi_mutex_lock(&ctx->pollfd_modify_lock);
-       r = ctx->pollfd_modify;
-       usbi_mutex_unlock(&ctx->pollfd_modify_lock);
+       usbi_mutex_lock(&ctx->event_data_lock);
+       r = ctx->device_close;
+       usbi_mutex_unlock(&ctx->event_data_lock);
        if (r) {
-               usbi_dbg("someone else is modifying poll fds");
+               usbi_dbg("someone else is closing a device");
                return 0;
        }
 
@@ -1639,20 +1827,20 @@ int API_EXPORTED libusb_event_handling_ok(libusb_context *ctx)
  * \param ctx the context to operate on, or NULL for the default context
  * \returns 1 if a thread is handling events
  * \returns 0 if there are no threads currently handling events
- * \see \ref mtasync
+ * \ref mtasync
  */
 int API_EXPORTED libusb_event_handler_active(libusb_context *ctx)
 {
-       int r;
+       unsigned int r;
        USBI_GET_CONTEXT(ctx);
 
-       /* is someone else waiting to modify poll fds? if so, don't let this thread
+       /* is someone else waiting to close a device? if so, don't let this thread
         * start event handling -- indicate that event handling is happening */
-       usbi_mutex_lock(&ctx->pollfd_modify_lock);
-       r = ctx->pollfd_modify;
-       usbi_mutex_unlock(&ctx->pollfd_modify_lock);
+       usbi_mutex_lock(&ctx->event_data_lock);
+       r = ctx->device_close;
+       usbi_mutex_unlock(&ctx->event_data_lock);
        if (r) {
-               usbi_dbg("someone else is modifying poll fds");
+               usbi_dbg("someone else is closing a device");
                return 1;
        }
 
@@ -1676,7 +1864,7 @@ int API_EXPORTED libusb_event_handler_active(libusb_context *ctx)
  * locking.
  *
  * \param ctx the context to operate on, or NULL for the default context
- * \see \ref mtasync
+ * \ref mtasync
  */
 void API_EXPORTED libusb_lock_event_waiters(libusb_context *ctx)
 {
@@ -1687,7 +1875,7 @@ void API_EXPORTED libusb_lock_event_waiters(libusb_context *ctx)
 /** \ingroup poll
  * Release the event waiters lock.
  * \param ctx the context to operate on, or NULL for the default context
- * \see \ref mtasync
+ * \ref mtasync
  */
 void API_EXPORTED libusb_unlock_event_waiters(libusb_context *ctx)
 {
@@ -1718,7 +1906,7 @@ void API_EXPORTED libusb_unlock_event_waiters(libusb_context *ctx)
  * indicates unlimited timeout.
  * \returns 0 after a transfer completes or another thread stops event handling
  * \returns 1 if the timeout expired
- * \see \ref mtasync
+ * \ref mtasync
  */
 int API_EXPORTED libusb_wait_for_event(libusb_context *ctx, struct timeval *tv)
 {
@@ -1739,7 +1927,7 @@ int API_EXPORTED libusb_wait_for_event(libusb_context *ctx, struct timeval *tv)
 
        timeout.tv_sec += tv->tv_sec;
        timeout.tv_nsec += tv->tv_usec * 1000;
-       if (timeout.tv_nsec > 1000000000) {
+       while (timeout.tv_nsec >= 1000000000) {
                timeout.tv_nsec -= 1000000000;
                timeout.tv_sec++;
        }
@@ -1755,9 +1943,11 @@ static void handle_timeout(struct usbi_transfer *itransfer)
                USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
        int r;
 
-       itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
+       itransfer->flags |= USBI_TRANSFER_TIMEOUT_HANDLED;
        r = libusb_cancel_transfer(transfer);
-       if (r < 0)
+       if (r == 0)
+               itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
+       else
                usbi_warn(TRANSFER_CTX(transfer),
                        "async cancel failed %d errno=%d", r, errno);
 }
@@ -1789,7 +1979,7 @@ static int handle_timeouts_locked(struct libusb_context *ctx)
                        return 0;
 
                /* ignore timeouts we've already handled */
-               if (transfer->flags & (USBI_TRANSFER_TIMED_OUT | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
+               if (transfer->flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
                        continue;
 
                /* if transfer has non-expired timeout, nothing more to do */
@@ -1819,10 +2009,6 @@ static int handle_timerfd_trigger(struct libusb_context *ctx)
 {
        int r;
 
-       r = disarm_timerfd(ctx);
-       if (r < 0)
-               return r;
-
        usbi_mutex_lock(&ctx->flying_transfers_lock);
 
        /* process the timeout that just happened */
@@ -1846,67 +2032,150 @@ static int handle_events(struct libusb_context *ctx, struct timeval *tv)
        int r;
        struct usbi_pollfd *ipollfd;
        POLL_NFDS_TYPE nfds = 0;
-       struct pollfd *fds;
+       POLL_NFDS_TYPE internal_nfds;
+       struct pollfd *fds = NULL;
        int i = -1;
        int timeout_ms;
+       int special_event;
+
+       /* there are certain fds that libusb uses internally, currently:
+        *
+        *   1) event pipe
+        *   2) timerfd
+        *
+        * the backend will never need to attempt to handle events on these fds, so
+        * we determine how many fds are in use internally for this context and when
+        * handle_events() is called in the backend, the pollfd list and count will
+        * be adjusted to skip over these internal fds */
+       if (usbi_using_timerfd(ctx))
+               internal_nfds = 2;
+       else
+               internal_nfds = 1;
 
-       usbi_mutex_lock(&ctx->pollfds_lock);
-       list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd)
-               nfds++;
+       /* only reallocate the poll fds when the list of poll fds has been modified
+        * since the last poll, otherwise reuse them to save the additional overhead */
+       usbi_mutex_lock(&ctx->event_data_lock);
+       if (ctx->pollfds_modified) {
+               usbi_dbg("poll fds modified, reallocating");
 
-       /* TODO: malloc when number of fd's changes, not on every poll */
-       fds = malloc(sizeof(*fds) * nfds);
-       if (!fds) {
-               usbi_mutex_unlock(&ctx->pollfds_lock);
-               return LIBUSB_ERROR_NO_MEM;
-       }
+               if (ctx->pollfds) {
+                       free(ctx->pollfds);
+                       ctx->pollfds = NULL;
+               }
+
+               /* sanity check - it is invalid for a context to have fewer than the
+                * required internal fds (memory corruption?) */
+               assert(ctx->pollfds_cnt >= internal_nfds);
+
+               ctx->pollfds = calloc(ctx->pollfds_cnt, sizeof(*ctx->pollfds));
+               if (!ctx->pollfds) {
+                       usbi_mutex_unlock(&ctx->event_data_lock);
+                       return LIBUSB_ERROR_NO_MEM;
+               }
+
+               list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd) {
+                       struct libusb_pollfd *pollfd = &ipollfd->pollfd;
+                       i++;
+                       ctx->pollfds[i].fd = pollfd->fd;
+                       ctx->pollfds[i].events = pollfd->events;
+               }
 
-       list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd) {
-               struct libusb_pollfd *pollfd = &ipollfd->pollfd;
-               int fd = pollfd->fd;
-               i++;
-               fds[i].fd = fd;
-               fds[i].events = pollfd->events;
-               fds[i].revents = 0;
+               /* reset the flag now that we have the updated list */
+               ctx->pollfds_modified = 0;
+
+               /* if no further pending events, clear the event pipe so that we do
+                * not immediately return from poll */
+               if (!usbi_pending_events(ctx))
+                       usbi_clear_event(ctx);
        }
-       usbi_mutex_unlock(&ctx->pollfds_lock);
+       fds = ctx->pollfds;
+       nfds = ctx->pollfds_cnt;
+       usbi_mutex_unlock(&ctx->event_data_lock);
 
-       timeout_ms = (tv->tv_sec * 1000) + (tv->tv_usec / 1000);
+       timeout_ms = (int)(tv->tv_sec * 1000) + (tv->tv_usec / 1000);
 
        /* round up to next millisecond */
        if (tv->tv_usec % 1000)
                timeout_ms++;
 
+redo_poll:
        usbi_dbg("poll() %d fds with timeout in %dms", nfds, timeout_ms);
        r = usbi_poll(fds, nfds, timeout_ms);
        usbi_dbg("poll() returned %d", r);
-       if (r == 0) {
-               free(fds);
+       if (r == 0)
                return handle_timeouts(ctx);
-       } else if (r == -1 && errno == EINTR) {
-               free(fds);
+       else if (r == -1 && errno == EINTR)
                return LIBUSB_ERROR_INTERRUPTED;
-       } else if (r < 0) {
-               free(fds);
-               usbi_err(ctx, "poll failed %d err=%d\n", r, errno);
+       else if (r < 0) {
+               usbi_err(ctx, "poll failed %d err=%d", r, errno);
                return LIBUSB_ERROR_IO;
        }
 
-       /* fd[0] is always the ctrl pipe */
+       special_event = 0;
+
+       /* fds[0] is always the event pipe */
        if (fds[0].revents) {
-               /* another thread wanted to interrupt event handling, and it succeeded!
-                * handle any other events that cropped up at the same time, and
-                * simply return */
-               usbi_dbg("caught a fish on the control pipe");
+               libusb_hotplug_message *message = NULL;
+               struct usbi_transfer *itransfer;
+               int ret = 0;
+
+               usbi_dbg("caught a fish on the event pipe");
 
-               if (r == 1) {
-                       r = 0;
+               /* take the the event data lock while processing events */
+               usbi_mutex_lock(&ctx->event_data_lock);
+
+               /* check if someone added a new poll fd */
+               if (ctx->pollfds_modified)
+                       usbi_dbg("someone updated the poll fds");
+
+               /* check if someone is closing a device */
+               if (ctx->device_close)
+                       usbi_dbg("someone is closing a device");
+
+               /* check for any pending hotplug messages */
+               if (!list_empty(&ctx->hotplug_msgs)) {
+                       usbi_dbg("hotplug message received");
+                       special_event = 1;
+                       message = list_first_entry(&ctx->hotplug_msgs, libusb_hotplug_message, list);
+                       list_del(&message->list);
+               }
+
+               /* complete any pending transfers */
+               while (ret == 0 && !list_empty(&ctx->completed_transfers)) {
+                       itransfer = list_first_entry(&ctx->completed_transfers, struct usbi_transfer, completed_list);
+                       list_del(&itransfer->completed_list);
+                       usbi_mutex_unlock(&ctx->event_data_lock);
+                       ret = usbi_backend->handle_transfer_completion(itransfer);
+                       if (ret)
+                               usbi_err(ctx, "backend handle_transfer_completion failed with error %d", ret);
+                       usbi_mutex_lock(&ctx->event_data_lock);
+               }
+
+               /* if no further pending events, clear the event pipe */
+               if (!usbi_pending_events(ctx))
+                       usbi_clear_event(ctx);
+
+               usbi_mutex_unlock(&ctx->event_data_lock);
+
+               /* process the hotplug message, if any */
+               if (message) {
+                       usbi_hotplug_match(ctx, message->device, message->event);
+
+                       /* the device left, dereference the device */
+                       if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == message->event)
+                               libusb_unref_device(message->device);
+
+                       free(message);
+               }
+
+               if (ret) {
+                       /* return error code */
+                       r = ret;
                        goto handled;
-               } else {
-                       /* prevent OS backend from trying to handle events on ctrl pipe */
-                       fds[0].revents = 0;
-                       r--;
                }
+
+               if (0 == --r)
+                       goto handled;
        }
 
 #ifdef USBI_TIMERFD_AVAILABLE
@@ -1915,31 +2184,30 @@ static int handle_events(struct libusb_context *ctx, struct timeval *tv)
                /* timerfd indicates that a timeout has expired */
                int ret;
                usbi_dbg("timerfd triggered");
+               special_event = 1;
 
                ret = handle_timerfd_trigger(ctx);
                if (ret < 0) {
                        /* return error code */
                        r = ret;
                        goto handled;
-               } else if (r == 1) {
-                       /* no more active file descriptors, nothing more to do */
-                       r = 0;
-                       goto handled;
-               } else {
-                       /* more events pending...
-                        * prevent OS backend from trying to handle events on timerfd */
-                       fds[1].revents = 0;
-                       r--;
                }
+
+               if (0 == --r)
+                       goto handled;
        }
 #endif
 
-       r = usbi_backend->handle_events(ctx, fdsnfds, r);
+       r = usbi_backend->handle_events(ctx, fds + internal_nfds, nfds - internal_nfds, r);
        if (r)
                usbi_err(ctx, "backend handle_events failed with error %d", r);
 
 handled:
-       free(fds);
+       if (r == 0 && special_event) {
+               timeout_ms = 0;
+               goto redo_poll;
+       }
+
        return r;
 }
 
@@ -1994,7 +2262,7 @@ static int get_next_timeout(libusb_context *ctx, struct timeval *tv,
  * timeval struct for non-blocking mode
  * \param completed pointer to completion integer to check, or NULL
  * \returns 0 on success, or a LIBUSB_ERROR code on failure
- * \see \ref mtasync
+ * \ref mtasync
  */
 int API_EXPORTED libusb_handle_events_timeout_completed(libusb_context *ctx,
        struct timeval *tv, int *completed)
@@ -2105,7 +2373,7 @@ int API_EXPORTED libusb_handle_events(libusb_context *ctx)
  * \param ctx the context to operate on, or NULL for the default context
  * \param completed pointer to completion integer to check, or NULL
  * \returns 0 on success, or a LIBUSB_ERROR code on failure
- * \see \ref mtasync
+ * \ref mtasync
  */
 int API_EXPORTED libusb_handle_events_completed(libusb_context *ctx,
        int *completed)
@@ -2131,7 +2399,7 @@ int API_EXPORTED libusb_handle_events_completed(libusb_context *ctx,
  * \param tv the maximum time to block waiting for events, or zero for
  * non-blocking mode
  * \returns 0 on success, or a LIBUSB_ERROR code on failure
- * \see \ref mtasync
+ * \ref mtasync
  */
 int API_EXPORTED libusb_handle_events_locked(libusb_context *ctx,
        struct timeval *tv)
@@ -2175,7 +2443,7 @@ int API_EXPORTED libusb_handle_events_locked(libusb_context *ctx,
  * \returns 0 if you must call into libusb at times determined by
  * libusb_get_next_timeout(), or 1 if all timeout events are handled internally
  * or through regular activity on the file descriptors.
- * \see \ref pollmain "Polling libusb file descriptors for event handling"
+ * \ref pollmain "Polling libusb file descriptors for event handling"
  */
 int API_EXPORTED libusb_pollfds_handle_timeouts(libusb_context *ctx)
 {
@@ -2222,9 +2490,8 @@ int API_EXPORTED libusb_get_next_timeout(libusb_context *ctx,
        struct usbi_transfer *transfer;
        struct timespec cur_ts;
        struct timeval cur_tv;
-       struct timeval *next_timeout;
+       struct timeval next_timeout = { 0, 0 };
        int r;
-       int found = 0;
 
        USBI_GET_CONTEXT(ctx);
        if (usbi_using_timerfd(ctx))
@@ -2239,37 +2506,35 @@ int API_EXPORTED libusb_get_next_timeout(libusb_context *ctx,
 
        /* find next transfer which hasn't already been processed as timed out */
        list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
-               if (transfer->flags & (USBI_TRANSFER_TIMED_OUT | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
+               if (transfer->flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
                        continue;
 
-               /* no timeout for this transfer? */
+               /* if we've reached transfers of infinte timeout, we're done looking */
                if (!timerisset(&transfer->timeout))
-                       continue;
+                       break;
 
-               found = 1;
+               next_timeout = transfer->timeout;
                break;
        }
        usbi_mutex_unlock(&ctx->flying_transfers_lock);
 
-       if (!found) {
+       if (!timerisset(&next_timeout)) {
                usbi_dbg("no URB with timeout or all handled by OS; no timeout!");
                return 0;
        }
 
-       next_timeout = &transfer->timeout;
-
        r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, &cur_ts);
        if (r < 0) {
                usbi_err(ctx, "failed to read monotonic clock, errno=%d", errno);
-               return LIBUSB_ERROR_OTHER;
+               return 0;
        }
        TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts);
 
-       if (!timercmp(&cur_tv, next_timeout, <)) {
+       if (!timercmp(&cur_tv, &next_timeout, <)) {
                usbi_dbg("first timeout already expired");
                timerclear(tv);
        } else {
-               timersub(next_timeout, &cur_tv, tv);
+               timersub(&next_timeout, &cur_tv, tv);
                usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec);
        }
 
@@ -2307,6 +2572,22 @@ void API_EXPORTED libusb_set_pollfd_notifiers(libusb_context *ctx,
        ctx->fd_cb_user_data = user_data;
 }
 
+/*
+ * Interrupt the iteration of the event handling thread, so that it picks
+ * up the fd change. Callers of this function must hold the event_data_lock.
+ */
+static void usbi_fd_notification(struct libusb_context *ctx)
+{
+       int pending_events;
+
+       /* Record that there is a new poll fd.
+        * Only signal an event if there are no prior pending events. */
+       pending_events = usbi_pending_events(ctx);
+       ctx->pollfds_modified = 1;
+       if (!pending_events)
+               usbi_signal_event(ctx);
+}
+
 /* Add a file descriptor to the list of file descriptors to be monitored.
  * events should be specified as a bitmask of events passed to poll(), e.g.
  * POLLIN and/or POLLOUT. */
@@ -2319,9 +2600,11 @@ int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events)
        usbi_dbg("add fd %d events %d", fd, events);
        ipollfd->pollfd.fd = fd;
        ipollfd->pollfd.events = events;
-       usbi_mutex_lock(&ctx->pollfds_lock);
-       list_add_tail(&ipollfd->list, &ctx->pollfds);
-       usbi_mutex_unlock(&ctx->pollfds_lock);
+       usbi_mutex_lock(&ctx->event_data_lock);
+       list_add_tail(&ipollfd->list, &ctx->ipollfds);
+       ctx->pollfds_cnt++;
+       usbi_fd_notification(ctx);
+       usbi_mutex_unlock(&ctx->event_data_lock);
 
        if (ctx->fd_added_cb)
                ctx->fd_added_cb(fd, events, ctx->fd_cb_user_data);
@@ -2335,8 +2618,8 @@ void usbi_remove_pollfd(struct libusb_context *ctx, int fd)
        int found = 0;
 
        usbi_dbg("remove fd %d", fd);
-       usbi_mutex_lock(&ctx->pollfds_lock);
-       list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd)
+       usbi_mutex_lock(&ctx->event_data_lock);
+       list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd)
                if (ipollfd->pollfd.fd == fd) {
                        found = 1;
                        break;
@@ -2344,12 +2627,14 @@ void usbi_remove_pollfd(struct libusb_context *ctx, int fd)
 
        if (!found) {
                usbi_dbg("couldn't find fd %d to remove", fd);
-               usbi_mutex_unlock(&ctx->pollfds_lock);
+               usbi_mutex_unlock(&ctx->event_data_lock);
                return;
        }
 
        list_del(&ipollfd->list);
-       usbi_mutex_unlock(&ctx->pollfds_lock);
+       ctx->pollfds_cnt--;
+       usbi_fd_notification(ctx);
+       usbi_mutex_unlock(&ctx->event_data_lock);
        free(ipollfd);
        if (ctx->fd_removed_cb)
                ctx->fd_removed_cb(fd, ctx->fd_cb_user_data);
@@ -2359,8 +2644,8 @@ void usbi_remove_pollfd(struct libusb_context *ctx, int fd)
  * Retrieve a list of file descriptors that should be polled by your main loop
  * as libusb event sources.
  *
- * The returned list is NULL-terminated and should be freed with free() when
- * done. The actual list contents must not be touched.
+ * The returned list is NULL-terminated and should be freed with libusb_free_pollfds()
+ * when done. The actual list contents must not be touched.
  *
  * As file descriptors are a Unix-specific concept, this function is not
  * available on Windows and will always return NULL.
@@ -2378,31 +2663,50 @@ const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds(
        struct libusb_pollfd **ret = NULL;
        struct usbi_pollfd *ipollfd;
        size_t i = 0;
-       size_t cnt = 0;
        USBI_GET_CONTEXT(ctx);
 
-       usbi_mutex_lock(&ctx->pollfds_lock);
-       list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd)
-               cnt++;
+       usbi_mutex_lock(&ctx->event_data_lock);
 
-       ret = calloc(cnt + 1, sizeof(struct libusb_pollfd *));
+       ret = calloc(ctx->pollfds_cnt + 1, sizeof(struct libusb_pollfd *));
        if (!ret)
                goto out;
 
-       list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd)
+       list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd)
                ret[i++] = (struct libusb_pollfd *) ipollfd;
-       ret[cnt] = NULL;
+       ret[ctx->pollfds_cnt] = NULL;
 
 out:
-       usbi_mutex_unlock(&ctx->pollfds_lock);
+       usbi_mutex_unlock(&ctx->event_data_lock);
        return (const struct libusb_pollfd **) ret;
 #else
+       usbi_err(ctx, "external polling of libusb's internal descriptors "\
+               "is not yet supported on Windows platforms");
        return NULL;
 #endif
 }
 
-/* Backends call this from handle_events to report disconnection of a device.
- * The transfers get cancelled appropriately.
+/** \ingroup poll
+ * Free a list of libusb_pollfd structures. This should be called for all
+ * pollfd lists allocated with libusb_get_pollfds().
+ *
+ * Since version 1.0.20, \ref LIBUSB_API_VERSION >= 0x01000104
+ *
+ * It is legal to call this function with a NULL pollfd list. In this case,
+ * the function will simply return safely.
+ *
+ * \param pollfds the list of libusb_pollfd structures to free
+ */
+void API_EXPORTED libusb_free_pollfds(const struct libusb_pollfd **pollfds)
+{
+       if (!pollfds)
+               return;
+
+       free((void *)pollfds);
+}
+
+/* Backends may call this from handle_events to report disconnection of a
+ * device. This function ensures transfers get cancelled appropriately.
+ * Callers of this function must hold the events_lock.
  */
 void usbi_handle_disconnect(struct libusb_device_handle *handle)
 {
@@ -2415,30 +2719,41 @@ void usbi_handle_disconnect(struct libusb_device_handle *handle)
        /* terminate all pending transfers with the LIBUSB_TRANSFER_NO_DEVICE
         * status code.
         *
-        * this is a bit tricky because:
-        * 1. we can't do transfer completion while holding flying_transfers_lock
-        * 2. the transfers list can change underneath us - if we were to build a
-        *    list of transfers to complete (while holding look), the situation
-        *    might be different by the time we come to free them
-        *
-        * so we resort to a loop-based approach as below
-        * FIXME: is this still potentially racy?
+        * when we find a transfer for this device on the list, there are two
+        * possible scenarios:
+        * 1. the transfer is currently in-flight, in which case we terminate the
+        *    transfer here
+        * 2. the transfer is not in-flight (or is but hasn't been marked as such),
+        *    in which case we record that the device disappeared and this will be
+        *    handled by libusb_submit_transfer()
         */
 
        while (1) {
-               usbi_mutex_lock(&HANDLE_CTX(handle)->flying_transfers_lock);
                to_cancel = NULL;
+               usbi_mutex_lock(&HANDLE_CTX(handle)->flying_transfers_lock);
                list_for_each_entry(cur, &HANDLE_CTX(handle)->flying_transfers, list, struct usbi_transfer)
                        if (USBI_TRANSFER_TO_LIBUSB_TRANSFER(cur)->dev_handle == handle) {
-                               to_cancel = cur;
-                               break;
+                               usbi_mutex_lock(&cur->flags_lock);
+                               if (cur->flags & USBI_TRANSFER_IN_FLIGHT)
+                                       to_cancel = cur;
+                               else
+                                       cur->flags |= USBI_TRANSFER_DEVICE_DISAPPEARED;
+                               usbi_mutex_unlock(&cur->flags_lock);
+
+                               if (to_cancel)
+                                       break;
                        }
                usbi_mutex_unlock(&HANDLE_CTX(handle)->flying_transfers_lock);
 
                if (!to_cancel)
                        break;
 
+               usbi_dbg("cancelling transfer %p from disconnect",
+                        USBI_TRANSFER_TO_LIBUSB_TRANSFER(to_cancel));
+
+               usbi_mutex_lock(&to_cancel->lock);
                usbi_backend->clear_transfer_priv(to_cancel);
+               usbi_mutex_unlock(&to_cancel->lock);
                usbi_handle_transfer_completion(to_cancel, LIBUSB_TRANSFER_NO_DEVICE);
        }