libusb 1.0.20-rc3
[platform/upstream/libusb.git] / libusb / io.c
index 0e219f8..279288c 100644 (file)
@@ -466,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
@@ -1114,10 +1122,11 @@ int usbi_io_init(struct libusb_context *ctx)
        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_recursive(&ctx->event_data_lock, NULL);
+       usbi_mutex_init(&ctx->event_data_lock, NULL);
        list_init(&ctx->flying_transfers);
        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->event_pipe);
@@ -1212,71 +1221,6 @@ static int calculate_timeout(struct usbi_transfer *transfer)
        return 0;
 }
 
-/* add a transfer to the (timeout-sorted) active transfers list.
- * Callers of this function must hold the flying_transfers_lock.
- * This function *always* adds the transfer to the flying_transfers list,
- * it will return non 0 if it fails to update the timer, but even then the
- * transfer is added to 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;
-
-       /* 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
-
-       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
@@ -1304,8 +1248,8 @@ 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)
@@ -1316,7 +1260,10 @@ struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(
 
        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
@@ -1342,11 +1289,13 @@ 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);
 }
 
@@ -1367,8 +1316,7 @@ static int disarm_timerfd(struct libusb_context *ctx)
 /* 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.
+ * returns 0 on success or a LIBUSB_ERROR code on failure.
  */
 static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
 {
@@ -1383,7 +1331,7 @@ static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
                        goto disarm;
 
                /* act on first transfer that is not already cancelled */
-               if (!(transfer->flags & USBI_TRANSFER_TIMED_OUT)) {
+               if (!(transfer->flags & USBI_TRANSFER_TIMEOUT_HANDLED)) {
                        int r;
                        const struct itimerspec it = { {0, 0},
                                { cur_tv->tv_sec, cur_tv->tv_usec * 1000 } };
@@ -1391,7 +1339,7 @@ static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
                        r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
                        if (r < 0)
                                return LIBUSB_ERROR_OTHER;
-                       return 1;
+                       return 0;
                }
        }
 
@@ -1406,6 +1354,96 @@ static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
 }
 #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.
@@ -1420,13 +1458,18 @@ static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
  */
 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;
 
-       usbi_mutex_lock(&ctx->flying_transfers_lock);
+       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);
@@ -1434,21 +1477,45 @@ 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);
 
        r = add_to_flying_list(itransfer);
-       if (r == LIBUSB_SUCCESS) {
-               r = usbi_backend->submit_transfer(itransfer);
+       if (r) {
+               usbi_mutex_lock(&itransfer->flags_lock);
+               itransfer->flags = 0;
+               goto out;
        }
-       if (r != LIBUSB_SUCCESS) {
-               list_del(&itransfer->list);
-               arm_timerfd_for_next_timeout(ctx);
+
+       /* 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 {
-               /* keep a reference to this device */
-               libusb_ref_device(transfer->dev_handle->dev);
+               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);
-       usbi_mutex_unlock(&ctx->flying_transfers_lock);
        return r;
 }
 
@@ -1462,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)
@@ -1472,8 +1539,14 @@ 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) {
                if (r != LIBUSB_ERROR_NOT_FOUND &&
@@ -1489,6 +1562,8 @@ 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;
 }
@@ -1543,23 +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 = 0;
+       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);
-       if (usbi_using_timerfd(ctx))
-               r = arm_timerfd_for_next_timeout(ctx);
-       usbi_mutex_unlock(&ctx->flying_transfers_lock);
-       if (usbi_using_timerfd(ctx) && (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) {
@@ -1583,7 +1653,7 @@ int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
        if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
                libusb_free_transfer(transfer);
        libusb_unref_device(handle->dev);
-       return 0;
+       return r;
 }
 
 /* Similar to usbi_handle_transfer_completion() but exclusively for transfers
@@ -1604,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.
@@ -1857,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);
 }
@@ -1891,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 */
@@ -2019,7 +2107,7 @@ redo_poll:
        else if (r == -1 && errno == EINTR)
                return LIBUSB_ERROR_INTERRUPTED;
        else if (r < 0) {
-               usbi_err(ctx, "poll failed %d err=%d\n", r, errno);
+               usbi_err(ctx, "poll failed %d err=%d", r, errno);
                return LIBUSB_ERROR_IO;
        }
 
@@ -2028,6 +2116,8 @@ redo_poll:
        /* fds[0] is always the event pipe */
        if (fds[0].revents) {
                libusb_hotplug_message *message = NULL;
+               struct usbi_transfer *itransfer;
+               int ret = 0;
 
                usbi_dbg("caught a fish on the event pipe");
 
@@ -2050,6 +2140,17 @@ redo_poll:
                        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);
@@ -2067,6 +2168,12 @@ redo_poll:
                        free(message);
                }
 
+               if (ret) {
+                       /* return error code */
+                       r = ret;
+                       goto handled;
+               }
+
                if (0 == --r)
                        goto handled;
        }
@@ -2383,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))
@@ -2400,25 +2506,23 @@ 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);
@@ -2426,11 +2530,11 @@ int API_EXPORTED libusb_get_next_timeout(libusb_context *ctx,
        }
        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);
        }
 
@@ -2468,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. */
@@ -2524,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.
@@ -2565,6 +2685,25 @@ out:
 #endif
 }
 
+/** \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.
@@ -2580,33 +2719,29 @@ 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
-        *    because the completion handler may try to re-submit the transfer
-        * 2. the transfers list can change underneath us - if we were to build a
-        *    list of transfers to complete (while holding lock), the situation
-        *    might be different by the time we come to free them
-        *
-        * so we resort to a loop-based approach as below
-        *
-        * This is safe because transfers are only removed from the
-        * flying_transfer list by usbi_handle_transfer_completion and
-        * libusb_close, both of which hold the events_lock while doing so,
-        * so usbi_handle_disconnect cannot be running at the same time.
-        *
-        * Note that libusb_submit_transfer also removes the transfer from
-        * the flying_transfer list on submission failure, but it keeps the
-        * flying_transfer list locked between addition and removal, so
-        * usbi_handle_disconnect never sees such transfers.
+        * 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);
 
@@ -2616,7 +2751,9 @@ void usbi_handle_disconnect(struct libusb_device_handle *handle)
                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);
        }