core: Add provisions for per-context private backend data
[platform/upstream/libusb.git] / libusb / core.c
index 1c3748d..06da8d0 100644 (file)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
 /*
- * Core functions for libusbx
+ * Core functions for libusb
  * Copyright © 2012-2013 Nathan Hjelm <hjelmn@cs.unm.edu>
  * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
  * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
+#ifdef HAVE_SYSLOG_H
+#include <syslog.h>
+#endif
+
+#ifdef __ANDROID__
+#include <android/log.h>
+#endif
 
 #include "libusbi.h"
 #include "hotplug.h"
 
-#if defined(OS_LINUX)
-const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
-#elif defined(OS_DARWIN)
-const struct usbi_os_backend * const usbi_backend = &darwin_backend;
-#elif defined(OS_OPENBSD)
-const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
-#elif defined(OS_WINDOWS)
-const struct usbi_os_backend * const usbi_backend = &windows_backend;
-#elif defined(OS_WINCE)
-const struct usbi_os_backend * const usbi_backend = &wince_backend;
-#else
-#error "Unsupported OS"
-#endif
-
 struct libusb_context *usbi_default_context = NULL;
-const struct libusb_version libusb_version_internal =
+static const struct libusb_version libusb_version_internal =
        { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
-         LIBUSB_RC, "http://libusbx.org" };
+         LIBUSB_RC, "http://libusb.info" };
 static int default_context_refcnt = 0;
 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
-static struct timeval timestamp_origin = { 0, 0 };
+static struct timespec timestamp_origin = { 0, 0 };
 
 usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
 struct list_head active_contexts_list;
 
 /**
- * \mainpage libusbx-1.0 API Reference
+ * \mainpage libusb-1.0 API Reference
  *
  * \section intro Introduction
  *
- * libusbx is an open source library that allows you to communicate with USB
+ * libusb is an open source library that allows you to communicate with USB
  * devices from userspace. For more info, see the
- * <a href="http://libusbx.org">libusbx homepage</a>.
+ * <a href="http://libusb.info">libusb homepage</a>.
  *
  * This documentation is aimed at application developers wishing to
  * communicate with USB peripherals from their own software. After reviewing
  * this documentation, feedback and questions can be sent to the
- * <a href="http://mailing-list.libusbx.org">libusbx-devel mailing list</a>.
+ * <a href="http://mailing-list.libusb.info">libusb-devel mailing list</a>.
  *
  * This documentation assumes knowledge of how to operate USB devices from
  * a software standpoint (descriptors, configurations, interfaces, endpoints,
@@ -83,6 +76,10 @@ struct list_head active_contexts_list;
  * Specification</a> which is available for free download. You can probably
  * find less verbose introductions by searching the web.
  *
+ * \section API Application Programming Interface (API)
+ *
+ * See the \ref libusb_api page for a complete list of the libusb functions.
+ *
  * \section features Library features
  *
  * - All transfer types supported (control/bulk/interrupt/isochronous)
@@ -93,51 +90,51 @@ struct list_head active_contexts_list;
  *   usually won't need to thread)
  * - Lightweight with lean API
  * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
- * - Hotplug support (see \ref hotplug)
+ * - Hotplug support (on some platforms). See \ref libusb_hotplug.
  *
  * \section gettingstarted Getting Started
  *
  * To begin reading the API documentation, start with the Modules page which
- * links to the different categories of libusbx's functionality.
+ * links to the different categories of libusb's functionality.
  *
  * One decision you will have to make is whether to use the synchronous
- * or the asynchronous data transfer interface. The \ref io documentation
+ * or the asynchronous data transfer interface. The \ref libusb_io documentation
  * provides some insight into this topic.
  *
- * Some example programs can be found in the libusbx source distribution under
- * the "examples" subdirectory. The libusbx homepage includes a list of
- * real-life project examples which use libusbx.
+ * Some example programs can be found in the libusb source distribution under
+ * the "examples" subdirectory. The libusb homepage includes a list of
+ * real-life project examples which use libusb.
  *
  * \section errorhandling Error handling
  *
- * libusbx functions typically return 0 on success or a negative error code
+ * libusb functions typically return 0 on success or a negative error code
  * on failure. These negative error codes relate to LIBUSB_ERROR constants
- * which are listed on the \ref misc "miscellaneous" documentation page.
+ * which are listed on the \ref libusb_misc "miscellaneous" documentation page.
  *
  * \section msglog Debug message logging
  *
- * libusbx uses stderr for all logging. By default, logging is set to NONE,
+ * libusb uses stderr for all logging. By default, logging is set to NONE,
  * which means that no output will be produced. However, unless the library
  * has been compiled with logging disabled, then any application calls to
  * libusb_set_debug(), or the setting of the environmental variable
  * LIBUSB_DEBUG outside of the application, can result in logging being
  * produced. Your application should therefore not close stderr, but instead
- * direct it to the null device if its output is undesireable.
+ * direct it to the null device if its output is undesirable.
  *
  * The libusb_set_debug() function can be used to enable logging of certain
- * messages. Under standard configuration, libusbx doesn't really log much
+ * messages. Under standard configuration, libusb doesn't really log much
  * so you are advised to use this function to enable all error/warning/
  * informational messages. It will help debug problems with your software.
  *
  * The logged messages are unstructured. There is no one-to-one correspondence
  * between messages being logged and success or failure return codes from
- * libusbx functions. There is no format to the messages, so you should not
+ * libusb functions. There is no format to the messages, so you should not
  * try to capture or parse them. They are not and will not be localized.
  * These messages are not intended to being passed to your application user;
- * instead, you should interpret the error codes returned from libusbx functions
+ * instead, you should interpret the error codes returned from libusb functions
  * and provide appropriate notification to the user. The messages are simply
  * there to aid you as a programmer, and if you're confused because you're
- * getting a strange error code from a libusbx function, enabling message
+ * getting a strange error code from a libusb function, enabling message
  * logging may give you a suitable explanation.
  *
  * The LIBUSB_DEBUG environment variable can be used to enable message logging
@@ -146,23 +143,37 @@ struct list_head active_contexts_list;
  * environment variable is set, the message logging verbosity level is fixed
  * and libusb_set_debug() effectively does nothing.
  *
- * libusbx can be compiled without any logging functions, useful for embedded
+ * libusb can be compiled without any logging functions, useful for embedded
  * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
  * variable have no effects.
  *
- * libusbx can also be compiled with verbose debugging messages always. When
+ * libusb can also be compiled with verbose debugging messages always. When
  * the library is compiled in this way, all messages of all verbosities are
  * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
  * have no effects.
  *
  * \section remarks Other remarks
  *
- * libusbx does have imperfections. The \ref caveats "caveats" page attempts
+ * libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts
  * to document these.
  */
 
 /**
- * \page caveats Caveats
+ * \page libusb_caveats Caveats
+ *
+ * \section fork Fork considerations
+ *
+ * libusb is <em>not</em> designed to work across fork() calls. Depending on
+ * the platform, there may be resources in the parent process that are not
+ * available to the child (e.g. the hotplug monitor thread on Linux). In
+ * addition, since the parent and child will share libusb's internal file
+ * descriptors, using libusb in any way from the child could cause the parent
+ * process's \ref libusb_context to get into an inconsistent state.
+ *
+ * On Linux, libusb's file descriptors will be marked as CLOEXEC, which means
+ * that it is safe to fork() and exec() without worrying about the child
+ * process needing to clean up state or having access to these file descriptors.
+ * Other platforms may not be so forgiving, so consider yourself warned!
  *
  * \section devresets Device resets
  *
@@ -172,7 +183,7 @@ struct list_head active_contexts_list;
  * reset).
  *
  * The problem is that any other program could reset the device your program
- * is working with, at any time. libusbx does not offer a mechanism to inform
+ * is working with, at any time. libusb does not offer a mechanism to inform
  * you when this has happened, so if someone else resets your device it will
  * not be clear to your own program why the device state has changed.
  *
@@ -197,7 +208,7 @@ struct list_head active_contexts_list;
  *
  * \section configsel Configuration selection and handling
  *
- * When libusbx presents a device handle to an application, there is a chance
+ * When libusb presents a device handle to an application, there is a chance
  * that the corresponding device may be in unconfigured state. For devices
  * with multiple configurations, there is also a chance that the configuration
  * currently selected is not the one that the application wants to use.
@@ -208,23 +219,25 @@ struct list_head active_contexts_list;
  * -# If the device is already in the desired configuration, calling
  *    libusb_set_configuration() using the same configuration value will cause
  *    a lightweight device reset. This may not be desirable behaviour.
- * -# libusbx will be unable to change configuration if the device is in
- *    another configuration and other programs or drivers have claimed
- *    interfaces under that configuration.
- * -# In the case where the desired configuration is already active, libusbx
+ * -# In the case where the desired configuration is already active, libusb
  *    may not even be able to perform a lightweight device reset. For example,
  *    take my USB keyboard with fingerprint reader: I'm interested in driving
- *    the fingerprint reader interface through libusbx, but the kernel's
+ *    the fingerprint reader interface through libusb, but the kernel's
  *    USB-HID driver will almost always have claimed the keyboard interface.
  *    Because the kernel has claimed an interface, it is not even possible to
  *    perform the lightweight device reset, so libusb_set_configuration() will
  *    fail. (Luckily the device in question only has a single configuration.)
+ * -# libusb will be unable to set a configuration if other programs or
+ *    drivers have claimed interfaces. In particular, this means that kernel
+ *    drivers must be detached from all the interfaces before
+ *    libusb_set_configuration() may succeed.
  *
  * One solution to some of the above problems is to consider the currently
  * active configuration. If the configuration we want is already active, then
  * we don't have to select any configuration:
 \code
-cfg = libusb_get_configuration(dev);
+cfg = -1;
+libusb_get_configuration(dev, &cfg);
 if (cfg != desired)
        libusb_set_configuration(dev, desired);
 \endcode
@@ -254,48 +267,47 @@ if (cfg != desired)
  * considerations apply to Darwin or other platforms.
  *
  * When a transfer completes early (i.e. when less data is received/sent in
- * any one packet than the transfer buffer allows for) then libusbx is designed
+ * any one packet than the transfer buffer allows for) then libusb is designed
  * to terminate the transfer immediately, not transferring or receiving any
  * more data unless other transfers have been queued by the user.
  *
- * On legacy platforms, libusbx is unable to do this in all situations. After
+ * On legacy platforms, libusb is unable to do this in all situations. After
  * the incomplete packet occurs, "surplus" data may be transferred. For recent
- * versions of libusbx, this information is kept (the data length of the
+ * versions of libusb, this information is kept (the data length of the
  * transfer is updated) and, for device-to-host transfers, any surplus data was
  * added to the buffer. Still, this is not a nice solution because it loses the
  * information about the end of the short packet, and the user probably wanted
  * that surplus data to arrive in the next logical transfer.
  *
- *
  * \section zlp Zero length packets
  *
- * - libusbx is able to send a packet of zero length to an endpoint simply by
+ * - libusb is able to send a packet of zero length to an endpoint simply by
  * submitting a transfer of zero length.
  * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
  * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
  */
 
 /**
- * \page contexts Contexts
+ * \page libusb_contexts Contexts
  *
- * It is possible that libusbx may be used simultaneously from two independent
+ * It is possible that libusb may be used simultaneously from two independent
  * libraries linked into the same executable. For example, if your application
  * has a plugin-like system which allows the user to dynamically load a range
  * of modules into your program, it is feasible that two independently
- * developed modules may both use libusbx.
+ * developed modules may both use libusb.
  *
- * libusbx is written to allow for these multiple user scenarios. The two
- * "instances" of libusbx will not interfere: libusb_set_debug() calls
+ * libusb is written to allow for these multiple user scenarios. The two
+ * "instances" of libusb will not interfere: libusb_set_debug() calls
  * from one user will not affect the same settings for other users, other
- * users can continue using libusbx after one of them calls libusb_exit(), etc.
+ * users can continue using libusb after one of them calls libusb_exit(), etc.
  *
- * This is made possible through libusbx's <em>context</em> concept. When you
+ * This is made possible through libusb's <em>context</em> concept. When you
  * call libusb_init(), you are (optionally) given a context. You can then pass
- * this context pointer back into future libusbx functions.
+ * this context pointer back into future libusb functions.
  *
  * In order to keep things simple for more simplistic applications, it is
  * legal to pass NULL to all functions requiring a context pointer (as long as
- * you're sure no other code will attempt to use libusbx from the same process).
+ * you're sure no other code will attempt to use libusb from the same process).
  * When you pass NULL, the default context will be used. The default context
  * is created the first time a process calls libusb_init() when no other
  * context is alive. Contexts are destroyed during libusb_exit().
@@ -308,21 +320,172 @@ if (cfg != desired)
  * reference count goes from 0 to 1, and is deinitialized and destroyed when
  * its reference count goes from 1 to 0.
  *
- * You may be wondering why only a subset of libusbx functions require a
- * context pointer in their function definition. Internally, libusbx stores
+ * You may be wondering why only a subset of libusb functions require a
+ * context pointer in their function definition. Internally, libusb stores
  * context pointers in other objects (e.g. libusb_device instances) and hence
  * can infer the context from those objects.
  */
 
+ /**
+  * \page libusb_api Application Programming Interface
+  *
+  * This is the complete list of libusb functions, structures and
+  * enumerations in alphabetical order.
+  *
+  * \section Functions
+  * - libusb_alloc_streams()
+  * - libusb_alloc_transfer()
+  * - libusb_attach_kernel_driver()
+  * - libusb_bulk_transfer()
+  * - libusb_cancel_transfer()
+  * - libusb_claim_interface()
+  * - libusb_clear_halt()
+  * - libusb_close()
+  * - libusb_control_transfer()
+  * - libusb_control_transfer_get_data()
+  * - libusb_control_transfer_get_setup()
+  * - libusb_cpu_to_le16()
+  * - libusb_detach_kernel_driver()
+  * - libusb_dev_mem_alloc()
+  * - libusb_dev_mem_free()
+  * - libusb_error_name()
+  * - libusb_event_handler_active()
+  * - libusb_event_handling_ok()
+  * - libusb_exit()
+  * - libusb_fill_bulk_stream_transfer()
+  * - libusb_fill_bulk_transfer()
+  * - libusb_fill_control_setup()
+  * - libusb_fill_control_transfer()
+  * - libusb_fill_interrupt_transfer()
+  * - libusb_fill_iso_transfer()
+  * - libusb_free_bos_descriptor()
+  * - libusb_free_config_descriptor()
+  * - libusb_free_container_id_descriptor()
+  * - libusb_free_device_list()
+  * - libusb_free_pollfds()
+  * - libusb_free_ss_endpoint_companion_descriptor()
+  * - libusb_free_ss_usb_device_capability_descriptor()
+  * - libusb_free_streams()
+  * - libusb_free_transfer()
+  * - libusb_free_usb_2_0_extension_descriptor()
+  * - libusb_get_active_config_descriptor()
+  * - libusb_get_bos_descriptor()
+  * - libusb_get_bus_number()
+  * - libusb_get_config_descriptor()
+  * - libusb_get_config_descriptor_by_value()
+  * - libusb_get_configuration()
+  * - libusb_get_container_id_descriptor()
+  * - libusb_get_descriptor()
+  * - libusb_get_device()
+  * - libusb_get_device_address()
+  * - libusb_get_device_descriptor()
+  * - libusb_get_device_list()
+  * - libusb_get_device_speed()
+  * - libusb_get_iso_packet_buffer()
+  * - libusb_get_iso_packet_buffer_simple()
+  * - libusb_get_max_iso_packet_size()
+  * - libusb_get_max_packet_size()
+  * - libusb_get_next_timeout()
+  * - libusb_get_parent()
+  * - libusb_get_pollfds()
+  * - libusb_get_port_number()
+  * - libusb_get_port_numbers()
+  * - libusb_get_port_path()
+  * - libusb_get_ss_endpoint_companion_descriptor()
+  * - libusb_get_ss_usb_device_capability_descriptor()
+  * - libusb_get_string_descriptor()
+  * - libusb_get_string_descriptor_ascii()
+  * - libusb_get_usb_2_0_extension_descriptor()
+  * - libusb_get_version()
+  * - libusb_handle_events()
+  * - libusb_handle_events_completed()
+  * - libusb_handle_events_locked()
+  * - libusb_handle_events_timeout()
+  * - libusb_handle_events_timeout_completed()
+  * - libusb_has_capability()
+  * - libusb_hotplug_deregister_callback()
+  * - libusb_hotplug_register_callback()
+  * - libusb_init()
+  * - libusb_interrupt_event_handler()
+  * - libusb_interrupt_transfer()
+  * - libusb_kernel_driver_active()
+  * - libusb_lock_events()
+  * - libusb_lock_event_waiters()
+  * - libusb_open()
+  * - libusb_open_device_with_vid_pid()
+  * - libusb_pollfds_handle_timeouts()
+  * - libusb_ref_device()
+  * - libusb_release_interface()
+  * - libusb_reset_device()
+  * - libusb_set_auto_detach_kernel_driver()
+  * - libusb_set_configuration()
+  * - libusb_set_debug()
+  * - libusb_set_interface_alt_setting()
+  * - libusb_set_iso_packet_lengths()
+  * - libusb_setlocale()
+  * - libusb_set_pollfd_notifiers()
+  * - libusb_strerror()
+  * - libusb_submit_transfer()
+  * - libusb_transfer_get_stream_id()
+  * - libusb_transfer_set_stream_id()
+  * - libusb_try_lock_events()
+  * - libusb_unlock_events()
+  * - libusb_unlock_event_waiters()
+  * - libusb_unref_device()
+  * - libusb_wait_for_event()
+  *
+  * \section Structures
+  * - libusb_bos_descriptor
+  * - libusb_bos_dev_capability_descriptor
+  * - libusb_config_descriptor
+  * - libusb_container_id_descriptor
+  * - \ref libusb_context
+  * - libusb_control_setup
+  * - \ref libusb_device
+  * - libusb_device_descriptor
+  * - \ref libusb_device_handle
+  * - libusb_endpoint_descriptor
+  * - libusb_interface
+  * - libusb_interface_descriptor
+  * - libusb_iso_packet_descriptor
+  * - libusb_pollfd
+  * - libusb_ss_endpoint_companion_descriptor
+  * - libusb_ss_usb_device_capability_descriptor
+  * - libusb_transfer
+  * - libusb_usb_2_0_extension_descriptor
+  * - libusb_version
+  *
+  * \section Enums
+  * - \ref libusb_bos_type
+  * - \ref libusb_capability
+  * - \ref libusb_class_code
+  * - \ref libusb_descriptor_type
+  * - \ref libusb_endpoint_direction
+  * - \ref libusb_error
+  * - \ref libusb_iso_sync_type
+  * - \ref libusb_iso_usage_type
+  * - \ref libusb_log_level
+  * - \ref libusb_request_recipient
+  * - \ref libusb_request_type
+  * - \ref libusb_speed
+  * - \ref libusb_ss_usb_device_capability_attributes
+  * - \ref libusb_standard_request
+  * - \ref libusb_supported_speed
+  * - \ref libusb_transfer_flags
+  * - \ref libusb_transfer_status
+  * - \ref libusb_transfer_type
+  * - \ref libusb_usb_2_0_extension_attributes
+  */
+
 /**
- * @defgroup lib Library initialization/deinitialization
- * This page details how to initialize and deinitialize libusbx. Initialization
- * must be performed before using any libusbx functionality, and similarly you
- * must not call any libusbx functions after deinitialization.
+ * @defgroup libusb_lib Library initialization/deinitialization
+ * This page details how to initialize and deinitialize libusb. Initialization
+ * must be performed before using any libusb functionality, and similarly you
+ * must not call any libusb functions after deinitialization.
  */
 
 /**
- * @defgroup dev Device handling and enumeration
+ * @defgroup libusb_dev Device handling and enumeration
  * The functionality documented below is designed to help with the following
  * operations:
  * - Enumerating the USB devices currently attached to the system
@@ -375,7 +538,7 @@ libusb_free_device_list(list, 1);
  * device.
  *
  * \section devshandles Devices and device handles
- * libusbx has a concept of a USB device, represented by the
+ * libusb has a concept of a USB device, represented by the
  * \ref libusb_device opaque type. A device represents a USB device that
  * is currently or was previously connected to the system. Using a reference
  * to a device, you can determine certain information about the device (e.g.
@@ -391,8 +554,8 @@ libusb_free_device_list(list, 1);
  * using the device.
  *
  * When you've found a device that you'd like to operate, you must ask
- * libusbx to open the device using the libusb_open() function. Assuming
- * success, libusbx then returns you a <em>device handle</em>
+ * libusb to open the device using the libusb_open() function. Assuming
+ * success, libusb then returns you a <em>device handle</em>
  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
  * operate on the handle rather than the original device pointer.
  *
@@ -400,10 +563,10 @@ libusb_free_device_list(list, 1);
  *
  * Device discovery (i.e. calling libusb_get_device_list()) returns a
  * freshly-allocated list of devices. The list itself must be freed when
- * you are done with it. libusbx also needs to know when it is OK to free
+ * you are done with it. libusb also needs to know when it is OK to free
  * the contents of the list - the devices themselves.
  *
- * To handle these issues, libusbx provides you with two separate items:
+ * To handle these issues, libusb provides you with two separate items:
  * - A function to free the list itself
  * - A reference counting system for the devices inside
  *
@@ -432,7 +595,7 @@ libusb_free_device_list(list, 1);
  * libusb_close().
  */
 
-/** @defgroup misc Miscellaneous */
+/** @defgroup libusb_misc Miscellaneous */
 
 /* we traverse usbfs without knowing how many devices we are going to find.
  * so we create this discovered_devs model which is similar to a linked-list
@@ -453,6 +616,16 @@ static struct discovered_devs *discovered_devs_alloc(void)
        return ret;
 }
 
+static void discovered_devs_free(struct discovered_devs *discdevs)
+{
+       size_t i;
+
+       for (i = 0; i < discdevs->len; i++)
+               libusb_unref_device(discdevs->devices[i]);
+
+       free(discdevs);
+}
+
 /* append a device to the discovered devices collection. may realloc itself,
  * returning new discdevs. returns NULL on realloc failure. */
 struct discovered_devs *discovered_devs_append(
@@ -460,6 +633,7 @@ struct discovered_devs *discovered_devs_append(
 {
        size_t len = discdevs->len;
        size_t capacity;
+       struct discovered_devs *new_discdevs;
 
        /* if there is space, just append the device */
        if (len < discdevs->capacity) {
@@ -471,25 +645,21 @@ struct discovered_devs *discovered_devs_append(
        /* exceeded capacity, need to grow */
        usbi_dbg("need to increase capacity");
        capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
-       discdevs = usbi_reallocf(discdevs,
+       /* can't use usbi_reallocf here because in failure cases it would
+        * free the existing discdevs without unreferencing its devices. */
+       new_discdevs = realloc(discdevs,
                sizeof(*discdevs) + (sizeof(void *) * capacity));
-       if (discdevs) {
-               discdevs->capacity = capacity;
-               discdevs->devices[len] = libusb_ref_device(dev);
-               discdevs->len++;
+       if (!new_discdevs) {
+               discovered_devs_free(discdevs);
+               return NULL;
        }
 
-       return discdevs;
-}
+       discdevs = new_discdevs;
+       discdevs->capacity = capacity;
+       discdevs->devices[len] = libusb_ref_device(dev);
+       discdevs->len++;
 
-static void discovered_devs_free(struct discovered_devs *discdevs)
-{
-       size_t i;
-
-       for (i = 0; i < discdevs->len; i++)
-               libusb_unref_device(discdevs->devices[i]);
-
-       free(discdevs);
+       return discdevs;
 }
 
 /* Allocate a new device with a specific session ID. The returned device has
@@ -497,14 +667,14 @@ static void discovered_devs_free(struct discovered_devs *discdevs)
 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
        unsigned long session_id)
 {
-       size_t priv_size = usbi_backend->device_priv_size;
+       size_t priv_size = usbi_backend.device_priv_size;
        struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
        int r;
 
        if (!dev)
                return NULL;
 
-       r = usbi_mutex_init(&dev->lock, NULL);
+       r = usbi_mutex_init(&dev->lock);
        if (r) {
                free(dev);
                return NULL;
@@ -524,11 +694,8 @@ struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
 
 void usbi_connect_device(struct libusb_device *dev)
 {
-       libusb_hotplug_message message;
-       ssize_t ret;
+       struct libusb_context *ctx = DEVICE_CTX(dev);
 
-       message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED;
-       message.device = dev;
        dev->attached = 1;
 
        usbi_mutex_lock(&dev->ctx->usb_devs_lock);
@@ -536,42 +703,32 @@ void usbi_connect_device(struct libusb_device *dev)
        usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
 
        /* Signal that an event has occurred for this device if we support hotplug AND
-        * the hotplug pipe is ready. This prevents an event from getting raised during
-        * initial enumeration. */
-       if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_pipe[1] > 0) {
-               ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
-               if (sizeof (message) != ret) {
-                       usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
-               }
+        * the hotplug message list is ready. This prevents an event from getting raised
+        * during initial enumeration. */
+       if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
+               usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED);
        }
 }
 
 void usbi_disconnect_device(struct libusb_device *dev)
 {
-       libusb_hotplug_message message;
-       struct libusb_context *ctx = dev->ctx;
-       ssize_t ret;
+       struct libusb_context *ctx = DEVICE_CTX(dev);
 
-       message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT;
-       message.device = dev;
        usbi_mutex_lock(&dev->lock);
        dev->attached = 0;
        usbi_mutex_unlock(&dev->lock);
 
-       /* Signal that an event has occurred for this device if we support hotplug AND
-        * the hotplug pipe is ready. This prevents an event from getting raised during
-        * initial enumeration. libusb_handle_events will take care of dereferencing the
-        * device. */
-       if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_pipe[1] > 0) {
-               ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
-               if (sizeof(message) != ret) {
-                       usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
-               }
-       }
-
        usbi_mutex_lock(&ctx->usb_devs_lock);
        list_del(&dev->list);
        usbi_mutex_unlock(&ctx->usb_devs_lock);
+
+       /* Signal that an event has occurred for this device if we support hotplug AND
+        * the hotplug message list is ready. This prevents an event from getting raised
+        * during initial enumeration. libusb_handle_events will take care of dereferencing
+        * the device. */
+       if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
+               usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);
+       }
 }
 
 /* Perform some final sanity checks on a newly discovered device. If this
@@ -597,7 +754,7 @@ int usbi_sanitize_device(struct libusb_device *dev)
        return 0;
 }
 
-/* Examine libusbx's internal list of known devices, looking for one with
+/* Examine libusb's internal list of known devices, looking for one with
  * a specific session ID. Returns the matching device if it was found, and
  * NULL otherwise. */
 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
@@ -609,7 +766,7 @@ struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
        usbi_mutex_lock(&ctx->usb_devs_lock);
        list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
                if (dev->session_data == session_id) {
-                       ret = dev;
+                       ret = libusb_ref_device(dev);
                        break;
                }
        usbi_mutex_unlock(&ctx->usb_devs_lock);
@@ -617,7 +774,7 @@ struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
        return ret;
 }
 
-/** @ingroup dev
+/** @ingroup libusb_dev
  * Returns a list of USB devices currently attached to the system. This is
  * your entry point into finding a USB device to operate.
  *
@@ -654,8 +811,8 @@ ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
                /* backend provides hotplug support */
                struct libusb_device *dev;
 
-               if (usbi_backend->hotplug_poll)
-                       usbi_backend->hotplug_poll();
+               if (usbi_backend.hotplug_poll)
+                       usbi_backend.hotplug_poll();
 
                usbi_mutex_lock(&ctx->usb_devs_lock);
                list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
@@ -669,7 +826,7 @@ ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
                usbi_mutex_unlock(&ctx->usb_devs_lock);
        } else {
                /* backend does not provide hotplug support */
-               r = usbi_backend->get_device_list(ctx, &discdevs);
+               r = usbi_backend.get_device_list(ctx, &discdevs);
        }
 
        if (r < 0) {
@@ -693,11 +850,12 @@ ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
        *list = ret;
 
 out:
-       discovered_devs_free(discdevs);
+       if (discdevs)
+               discovered_devs_free(discdevs);
        return len;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Frees a list of devices previously discovered using
  * libusb_get_device_list(). If the unref_devices parameter is set, the
  * reference count of each device in the list is decremented by 1.
@@ -720,7 +878,7 @@ void API_EXPORTED libusb_free_device_list(libusb_device **list,
        free(list);
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Get the number of the bus that a device is connected to.
  * \param dev a device
  * \returns the bus number
@@ -730,8 +888,17 @@ uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
        return dev->bus_number;
 }
 
-/** \ingroup dev
- * Get the number of the port that a device is connected to
+/** \ingroup libusb_dev
+ * Get the number of the port that a device is connected to.
+ * Unless the OS does something funky, or you are hot-plugging USB extension cards,
+ * the port number returned by this call is usually guaranteed to be uniquely tied
+ * to a physical port, meaning that different devices plugged on the same physical
+ * port should return the same port number.
+ *
+ * But outside of this, there is no guarantee that the port number returned by this
+ * call will remain the same, or even match the order in which ports have been
+ * numbered by the HUB/HCD manufacturer.
+ *
  * \param dev a device
  * \returns the port number (0 if not available)
  */
@@ -740,10 +907,10 @@ uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
        return dev->port_number;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Get the list of all port numbers from root for the specified device
  *
- * Since version 1.0.16, \ref LIBUSBX_API_VERSION >= 0x01000102
+ * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
  * \param dev a device
  * \param port_numbers the array that should contain the port numbers
  * \param port_numbers_len the maximum length of the array. As per the USB 3.0
@@ -755,26 +922,26 @@ int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
        uint8_t* port_numbers, int port_numbers_len)
 {
        int i = port_numbers_len;
+       struct libusb_context *ctx = DEVICE_CTX(dev);
 
-       while(dev) {
-               // HCDs can be listed as devices and would have port #0
-               // TODO: see how the other backends want to implement HCDs as parents
-               if (dev->port_number == 0)
-                       break;
-               i--;
-               if (i < 0) {
-                       usbi_warn(DEVICE_CTX(dev),
-                               "port numbers array too small");
+       if (port_numbers_len <= 0)
+               return LIBUSB_ERROR_INVALID_PARAM;
+
+       // HCDs can be listed as devices with port #0
+       while((dev) && (dev->port_number != 0)) {
+               if (--i < 0) {
+                       usbi_warn(ctx, "port numbers array is too small");
                        return LIBUSB_ERROR_OVERFLOW;
                }
                port_numbers[i] = dev->port_number;
                dev = dev->parent_dev;
        }
-       memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
+       if (i < port_numbers_len)
+               memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
        return port_numbers_len - i;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Deprecated please use libusb_get_port_numbers instead.
  */
 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
@@ -785,13 +952,13 @@ int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
        return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
 }
 
-/** \ingroup dev
- * Get the the parent from the specified device [EXPERIMENTAL]
+/** \ingroup libusb_dev
+ * Get the the parent from the specified device.
  * \param dev a device
  * \returns the device parent or NULL if not available
- * You should issue a libusb_get_device_list() before calling this
+ * You should issue a \ref libusb_get_device_list() before calling this
  * function and make sure that you only access the parent before issuing
- * libusb_free_device_list(). The reason is that libusbx currently does
+ * \ref libusb_free_device_list(). The reason is that libusb currently does
  * not maintain a permanent list of device instances, and therefore can
  * only guarantee that parents are fully instantiated within a 
  * libusb_get_device_list() - libusb_free_device_list() block.
@@ -802,7 +969,7 @@ libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
        return dev->parent_dev;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Get the address of the device on the bus it is connected to.
  * \param dev a device
  * \returns the device address
@@ -812,7 +979,7 @@ uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
        return dev->device_address;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Get the negotiated connection speed for a device.
  * \param dev a device
  * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
@@ -848,7 +1015,7 @@ static const struct libusb_endpoint_descriptor *find_endpoint(
        return NULL;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Convenience function to retrieve the wMaxPacketSize value for a particular
  * endpoint in the active device configuration.
  *
@@ -879,19 +1046,23 @@ int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
        }
 
        ep = find_endpoint(config, endpoint);
-       if (!ep)
-               return LIBUSB_ERROR_NOT_FOUND;
+       if (!ep) {
+               r = LIBUSB_ERROR_NOT_FOUND;
+               goto out;
+       }
 
        r = ep->wMaxPacketSize;
+
+out:
        libusb_free_config_descriptor(config);
        return r;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Calculate the maximum packet size which a specific endpoint is capable is
  * sending or receiving in the duration of 1 microframe
  *
- * Only the active configution is examined. The calculation is based on the
+ * Only the active configuration is examined. The calculation is based on the
  * wMaxPacketSize field in the endpoint descriptor as described in section
  * 9.6.6 in the USB 2.0 specifications.
  *
@@ -930,21 +1101,25 @@ int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
        }
 
        ep = find_endpoint(config, endpoint);
-       if (!ep)
-               return LIBUSB_ERROR_NOT_FOUND;
+       if (!ep) {
+               r = LIBUSB_ERROR_NOT_FOUND;
+               goto out;
+       }
 
        val = ep->wMaxPacketSize;
        ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
-       libusb_free_config_descriptor(config);
 
        r = val & 0x07ff;
        if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
                        || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
                r *= (1 + ((val >> 11) & 3));
+
+out:
+       libusb_free_config_descriptor(config);
        return r;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Increment the reference count of a device.
  * \param dev the device to reference
  * \returns the same device
@@ -958,7 +1133,7 @@ libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
        return dev;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Decrement the reference count of a device. If the decrement operation
  * causes the reference count to reach zero, the device shall be destroyed.
  * \param dev the device to unreference
@@ -979,8 +1154,8 @@ void API_EXPORTED libusb_unref_device(libusb_device *dev)
 
                libusb_unref_device(dev->parent_dev);
 
-               if (usbi_backend->destroy_device)
-                       usbi_backend->destroy_device(dev);
+               if (usbi_backend.destroy_device)
+                       usbi_backend.destroy_device(dev);
 
                if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
                        /* backend does not support hotplug */
@@ -993,50 +1168,44 @@ void API_EXPORTED libusb_unref_device(libusb_device *dev)
 }
 
 /*
- * Interrupt the iteration of the event handling thread, so that it picks
- * up the new fd.
+ * Signal the event pipe so that the event handling thread will be
+ * interrupted to process an internal event.
  */
-void usbi_fd_notification(struct libusb_context *ctx)
+int usbi_signal_event(struct libusb_context *ctx)
 {
        unsigned char dummy = 1;
        ssize_t r;
 
-       if (ctx == NULL)
-               return;
-
-       /* record that we are messing with poll fds */
-       usbi_mutex_lock(&ctx->pollfd_modify_lock);
-       ctx->pollfd_modify++;
-       usbi_mutex_unlock(&ctx->pollfd_modify_lock);
-
-       /* write some data on control pipe to interrupt event handlers */
-       r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
-       if (r <= 0) {
+       /* write some data on event pipe to interrupt event handlers */
+       r = usbi_write(ctx->event_pipe[1], &dummy, sizeof(dummy));
+       if (r != sizeof(dummy)) {
                usbi_warn(ctx, "internal signalling write failed");
-               usbi_mutex_lock(&ctx->pollfd_modify_lock);
-               ctx->pollfd_modify--;
-               usbi_mutex_unlock(&ctx->pollfd_modify_lock);
-               return;
+               return LIBUSB_ERROR_IO;
        }
 
-       /* take event handling lock */
-       libusb_lock_events(ctx);
+       return 0;
+}
+
+/*
+ * Clear the event pipe so that the event handling will no longer be
+ * interrupted.
+ */
+int usbi_clear_event(struct libusb_context *ctx)
+{
+       unsigned char dummy;
+       ssize_t r;
 
-       /* read the dummy data */
-       r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
-       if (r <= 0)
+       /* read some data on event pipe to clear it */
+       r = usbi_read(ctx->event_pipe[0], &dummy, sizeof(dummy));
+       if (r != sizeof(dummy)) {
                usbi_warn(ctx, "internal signalling read failed");
+               return LIBUSB_ERROR_IO;
+       }
 
-       /* we're done with modifying poll fds */
-       usbi_mutex_lock(&ctx->pollfd_modify_lock);
-       ctx->pollfd_modify--;
-       usbi_mutex_unlock(&ctx->pollfd_modify_lock);
-
-       /* Release event handling lock and wake up event waiters */
-       libusb_unlock_events(ctx);
+       return 0;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Open a device and obtain a device handle. A handle allows you to perform
  * I/O on the device in question.
  *
@@ -1047,7 +1216,7 @@ void usbi_fd_notification(struct libusb_context *ctx)
  * This is a non-blocking function; no requests are sent over the bus.
  *
  * \param dev the device to open
- * \param handle output location for the returned device handle pointer. Only
+ * \param dev_handle output location for the returned device handle pointer. Only
  * populated when the return code is 0.
  * \returns 0 on success
  * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
@@ -1056,11 +1225,11 @@ void usbi_fd_notification(struct libusb_context *ctx)
  * \returns another LIBUSB_ERROR code on other failure
  */
 int API_EXPORTED libusb_open(libusb_device *dev,
-       libusb_device_handle **handle)
+       libusb_device_handle **dev_handle)
 {
        struct libusb_context *ctx = DEVICE_CTX(dev);
-       struct libusb_device_handle *_handle;
-       size_t priv_size = usbi_backend->device_handle_priv_size;
+       struct libusb_device_handle *_dev_handle;
+       size_t priv_size = usbi_backend.device_handle_priv_size;
        int r;
        usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
 
@@ -1068,49 +1237,42 @@ int API_EXPORTED libusb_open(libusb_device *dev,
                return LIBUSB_ERROR_NO_DEVICE;
        }
 
-       _handle = malloc(sizeof(*_handle) + priv_size);
-       if (!_handle)
+       _dev_handle = malloc(sizeof(*_dev_handle) + priv_size);
+       if (!_dev_handle)
                return LIBUSB_ERROR_NO_MEM;
 
-       r = usbi_mutex_init(&_handle->lock, NULL);
+       r = usbi_mutex_init(&_dev_handle->lock);
        if (r) {
-               free(_handle);
+               free(_dev_handle);
                return LIBUSB_ERROR_OTHER;
        }
 
-       _handle->dev = libusb_ref_device(dev);
-       _handle->claimed_interfaces = 0;
-       memset(&_handle->os_priv, 0, priv_size);
+       _dev_handle->dev = libusb_ref_device(dev);
+       _dev_handle->auto_detach_kernel_driver = 0;
+       _dev_handle->claimed_interfaces = 0;
+       memset(&_dev_handle->os_priv, 0, priv_size);
 
-       r = usbi_backend->open(_handle);
+       r = usbi_backend.open(_dev_handle);
        if (r < 0) {
                usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
                libusb_unref_device(dev);
-               usbi_mutex_destroy(&_handle->lock);
-               free(_handle);
+               usbi_mutex_destroy(&_dev_handle->lock);
+               free(_dev_handle);
                return r;
        }
 
        usbi_mutex_lock(&ctx->open_devs_lock);
-       list_add(&_handle->list, &ctx->open_devs);
+       list_add(&_dev_handle->list, &ctx->open_devs);
        usbi_mutex_unlock(&ctx->open_devs_lock);
-       *handle = _handle;
-
-       /* At this point, we want to interrupt any existing event handlers so
-        * that they realise the addition of the new device's poll fd. One
-        * example when this is desirable is if the user is running a separate
-        * dedicated libusbx events handling thread, which is running with a long
-        * or infinite timeout. We want to interrupt that iteration of the loop,
-        * so that it picks up the new fd, and then continues. */
-       usbi_fd_notification(ctx);
+       *dev_handle = _dev_handle;
 
        return 0;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Convenience function for finding a device with a particular
  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
- * for those scenarios where you are using libusbx to knock up a quick test
+ * for those scenarios where you are using libusb to knock up a quick test
  * application - it allows you to avoid calling libusb_get_device_list() and
  * worrying about traversing/freeing the list.
  *
@@ -1121,8 +1283,8 @@ int API_EXPORTED libusb_open(libusb_device *dev,
  * \param ctx the context to operate on, or NULL for the default context
  * \param vendor_id the idVendor value to search for
  * \param product_id the idProduct value to search for
- * \returns a handle for the first found device, or NULL on error or if the
- * device could not be found. */
+ * \returns a device handle for the first found device, or NULL on error
+ * or if the device could not be found. */
 DEFAULT_VISIBILITY
 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
        libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
@@ -1130,7 +1292,7 @@ libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
        struct libusb_device **devs;
        struct libusb_device *found = NULL;
        struct libusb_device *dev;
-       struct libusb_device_handle *handle = NULL;
+       struct libusb_device_handle *dev_handle = NULL;
        size_t i = 0;
        int r;
 
@@ -1149,14 +1311,14 @@ libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
        }
 
        if (found) {
-               r = libusb_open(found, &handle);
+               r = libusb_open(found, &dev_handle);
                if (r < 0)
-                       handle = NULL;
+                       dev_handle = NULL;
        }
 
 out:
        libusb_free_device_list(devs, 1);
-       return handle;
+       return dev_handle;
 }
 
 static void do_close(struct libusb_context *ctx,
@@ -1165,8 +1327,6 @@ static void do_close(struct libusb_context *ctx,
        struct usbi_transfer *itransfer;
        struct usbi_transfer *tmp;
 
-       libusb_lock_events(ctx);
-
        /* remove any transfers in flight that are for this device */
        usbi_mutex_lock(&ctx->flying_transfers_lock);
 
@@ -1178,23 +1338,23 @@ static void do_close(struct libusb_context *ctx,
                if (transfer->dev_handle != dev_handle)
                        continue;
 
-               if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
+               usbi_mutex_lock(&itransfer->lock);
+               if (!(itransfer->state_flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
                        usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
 
-                       if (itransfer->flags & USBI_TRANSFER_CANCELLING)
+                       if (itransfer->state_flags & USBI_TRANSFER_CANCELLING)
                                usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
                        else
                                usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
                }
+               usbi_mutex_unlock(&itransfer->lock);
 
                /* remove from the list of in-flight transfers and make sure
                 * we don't accidentally use the device handle in the future
                 * (or that such accesses will be easily caught and identified as a crash)
                 */
-               usbi_mutex_lock(&itransfer->lock);
                list_del(&itransfer->list);
                transfer->dev_handle = NULL;
-               usbi_mutex_unlock(&itransfer->lock);
 
                /* it is up to the user to free up the actual transfer struct.  this is
                 * just making sure that we don't attempt to process the transfer after
@@ -1205,19 +1365,17 @@ static void do_close(struct libusb_context *ctx,
        }
        usbi_mutex_unlock(&ctx->flying_transfers_lock);
 
-       libusb_unlock_events(ctx);
-
        usbi_mutex_lock(&ctx->open_devs_lock);
        list_del(&dev_handle->list);
        usbi_mutex_unlock(&ctx->open_devs_lock);
 
-       usbi_backend->close(dev_handle);
+       usbi_backend.close(dev_handle);
        libusb_unref_device(dev_handle->dev);
        usbi_mutex_destroy(&dev_handle->lock);
        free(dev_handle);
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Close a device handle. Should be called on all open handles before your
  * application exits.
  *
@@ -1226,64 +1384,63 @@ static void do_close(struct libusb_context *ctx,
  *
  * This is a non-blocking function; no requests are sent over the bus.
  *
- * \param dev_handle the handle to close
+ * \param dev_handle the device handle to close
  */
 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
 {
        struct libusb_context *ctx;
-       unsigned char dummy = 1;
-       ssize_t r;
+       int handling_events;
+       int pending_events;
 
        if (!dev_handle)
                return;
        usbi_dbg("");
 
        ctx = HANDLE_CTX(dev_handle);
+       handling_events = usbi_handling_events(ctx);
 
        /* Similarly to libusb_open(), we want to interrupt all event handlers
         * at this point. More importantly, we want to perform the actual close of
         * the device while holding the event handling lock (preventing any other
         * thread from doing event handling) because we will be removing a file
-        * descriptor from the polling loop. */
-
-       /* record that we are messing with poll fds */
-       usbi_mutex_lock(&ctx->pollfd_modify_lock);
-       ctx->pollfd_modify++;
-       usbi_mutex_unlock(&ctx->pollfd_modify_lock);
-
-       /* write some data on control pipe to interrupt event handlers */
-       r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
-       if (r <= 0) {
-               usbi_warn(ctx, "internal signalling write failed, closing anyway");
-               do_close(ctx, dev_handle);
-               usbi_mutex_lock(&ctx->pollfd_modify_lock);
-               ctx->pollfd_modify--;
-               usbi_mutex_unlock(&ctx->pollfd_modify_lock);
-               return;
+        * descriptor from the polling loop. If this is being called by the current
+        * event handler, we can bypass the interruption code because we already
+        * hold the event handling lock. */
+
+       if (!handling_events) {
+               /* Record that we are closing a device.
+                * Only signal an event if there are no prior pending events. */
+               usbi_mutex_lock(&ctx->event_data_lock);
+               pending_events = usbi_pending_events(ctx);
+               ctx->device_close++;
+               if (!pending_events)
+                       usbi_signal_event(ctx);
+               usbi_mutex_unlock(&ctx->event_data_lock);
+
+               /* take event handling lock */
+               libusb_lock_events(ctx);
        }
 
-       /* take event handling lock */
-       libusb_lock_events(ctx);
-
-       /* read the dummy data */
-       r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
-       if (r <= 0)
-               usbi_warn(ctx, "internal signalling read failed, closing anyway");
-
        /* Close the device */
        do_close(ctx, dev_handle);
 
-       /* we're done with modifying poll fds */
-       usbi_mutex_lock(&ctx->pollfd_modify_lock);
-       ctx->pollfd_modify--;
-       usbi_mutex_unlock(&ctx->pollfd_modify_lock);
-
-       /* Release event handling lock and wake up event waiters */
-       libusb_unlock_events(ctx);
+       if (!handling_events) {
+               /* We're done with closing this device.
+                * Clear the event pipe if there are no further pending events. */
+               usbi_mutex_lock(&ctx->event_data_lock);
+               ctx->device_close--;
+               pending_events = usbi_pending_events(ctx);
+               if (!pending_events)
+                       usbi_clear_event(ctx);
+               usbi_mutex_unlock(&ctx->event_data_lock);
+
+               /* Release event handling lock and wake up event waiters */
+               libusb_unlock_events(ctx);
+       }
 }
 
-/** \ingroup dev
- * Get the underlying device for a handle. This function does not modify
+/** \ingroup libusb_dev
+ * Get the underlying device for a device handle. This function does not modify
  * the reference count of the returned device, so do not feel compelled to
  * unreference it when you are done.
  * \param dev_handle a device handle
@@ -1295,7 +1452,7 @@ libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
        return dev_handle->dev;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Determine the bConfigurationValue of the currently active configuration.
  *
  * You could formulate your own control request to obtain this information,
@@ -1308,29 +1465,29 @@ libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
  * This function will return a value of 0 in the <tt>config</tt> output
  * parameter if the device is in unconfigured state.
  *
- * \param dev a device handle
+ * \param dev_handle a device handle
  * \param config output location for the bConfigurationValue of the active
  * configuration (only valid for return code 0)
  * \returns 0 on success
  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  * \returns another LIBUSB_ERROR code on other failure
  */
-int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
+int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev_handle,
        int *config)
 {
        int r = LIBUSB_ERROR_NOT_SUPPORTED;
 
        usbi_dbg("");
-       if (usbi_backend->get_configuration)
-               r = usbi_backend->get_configuration(dev, config);
+       if (usbi_backend.get_configuration)
+               r = usbi_backend.get_configuration(dev_handle, config);
 
        if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
                uint8_t tmp = 0;
                usbi_dbg("falling back to control message");
-               r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
+               r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
                        LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
                if (r == 0) {
-                       usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
+                       usbi_err(HANDLE_CTX(dev_handle), "zero bytes returned in ctrl transfer?");
                        r = LIBUSB_ERROR_IO;
                } else if (r == 1) {
                        r = 0;
@@ -1346,7 +1503,7 @@ int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
        return r;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Set the active configuration for a device.
  *
  * The operating system may or may not have already set an active
@@ -1361,7 +1518,14 @@ int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
  * endpoint halts cleared, toggles reset).
  *
  * You cannot change/reset configuration if your application has claimed
- * interfaces - you should free them with libusb_release_interface() first.
+ * interfaces. It is advised to set the desired configuration before claiming
+ * interfaces.
+ *
+ * Alternatively you can call libusb_release_interface() first. Note if you
+ * do things this way you must ensure that auto_detach_kernel_driver for
+ * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
+ * release the interface(s).
+ *
  * You cannot change/reset configuration if other applications or drivers have
  * claimed interfaces.
  *
@@ -1375,28 +1539,33 @@ int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
  *
  * This is a blocking function.
  *
- * \param dev a device handle
+ * \param dev_handle a device handle
  * \param configuration the bConfigurationValue of the configuration you
- * wish to activate, or -1 if you wish to put the device in unconfigured state
+ * wish to activate, or -1 if you wish to put the device in an unconfigured
+ * state
  * \returns 0 on success
  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  * \returns another LIBUSB_ERROR code on other failure
+ * \see libusb_set_auto_detach_kernel_driver()
  */
-int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
+int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev_handle,
        int configuration)
 {
        usbi_dbg("configuration %d", configuration);
-       return usbi_backend->set_configuration(dev, configuration);
+       return usbi_backend.set_configuration(dev_handle, configuration);
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Claim an interface on a given device handle. You must claim the interface
  * you wish to use before you can perform I/O on any of its endpoints.
  *
  * It is legal to attempt to claim an already-claimed interface, in which
- * case libusbx just returns 0 without doing anything.
+ * case libusb just returns 0 without doing anything.
+ *
+ * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
+ * will be detached if necessary, on failure the detach error is returned.
  *
  * Claiming of interfaces is a purely logical operation; it does not cause
  * any requests to be sent over the bus. Interface claiming is used to
@@ -1405,7 +1574,7 @@ int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
  *
  * This is a non-blocking function.
  *
- * \param dev a device handle
+ * \param dev_handle a device handle
  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
  * wish to claim
  * \returns 0 on success
@@ -1414,8 +1583,9 @@ int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
  * interface
  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  * \returns a LIBUSB_ERROR code on other failure
+ * \see libusb_set_auto_detach_kernel_driver()
  */
-int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
+int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev_handle,
        int interface_number)
 {
        int r = 0;
@@ -1424,38 +1594,42 @@ int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
        if (interface_number >= USB_MAXINTERFACES)
                return LIBUSB_ERROR_INVALID_PARAM;
 
-       if (!dev->dev->attached)
+       if (!dev_handle->dev->attached)
                return LIBUSB_ERROR_NO_DEVICE;
 
-       usbi_mutex_lock(&dev->lock);
-       if (dev->claimed_interfaces & (1 << interface_number))
+       usbi_mutex_lock(&dev_handle->lock);
+       if (dev_handle->claimed_interfaces & (1 << interface_number))
                goto out;
 
-       r = usbi_backend->claim_interface(dev, interface_number);
+       r = usbi_backend.claim_interface(dev_handle, interface_number);
        if (r == 0)
-               dev->claimed_interfaces |= 1 << interface_number;
+               dev_handle->claimed_interfaces |= 1 << interface_number;
 
 out:
-       usbi_mutex_unlock(&dev->lock);
+       usbi_mutex_unlock(&dev_handle->lock);
        return r;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Release an interface previously claimed with libusb_claim_interface(). You
  * should release all claimed interfaces before closing a device handle.
  *
  * This is a blocking function. A SET_INTERFACE control request will be sent
  * to the device, resetting interface state to the first alternate setting.
  *
- * \param dev a device handle
+ * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
+ * driver will be re-attached after releasing the interface.
+ *
+ * \param dev_handle a device handle
  * \param interface_number the <tt>bInterfaceNumber</tt> of the
  * previously-claimed interface
  * \returns 0 on success
  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  * \returns another LIBUSB_ERROR code on other failure
+ * \see libusb_set_auto_detach_kernel_driver()
  */
-int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
+int API_EXPORTED libusb_release_interface(libusb_device_handle *dev_handle,
        int interface_number)
 {
        int r;
@@ -1464,22 +1638,22 @@ int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
        if (interface_number >= USB_MAXINTERFACES)
                return LIBUSB_ERROR_INVALID_PARAM;
 
-       usbi_mutex_lock(&dev->lock);
-       if (!(dev->claimed_interfaces & (1 << interface_number))) {
+       usbi_mutex_lock(&dev_handle->lock);
+       if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
                r = LIBUSB_ERROR_NOT_FOUND;
                goto out;
        }
 
-       r = usbi_backend->release_interface(dev, interface_number);
+       r = usbi_backend.release_interface(dev_handle, interface_number);
        if (r == 0)
-               dev->claimed_interfaces &= ~(1 << interface_number);
+               dev_handle->claimed_interfaces &= ~(1 << interface_number);
 
 out:
-       usbi_mutex_unlock(&dev->lock);
+       usbi_mutex_unlock(&dev_handle->lock);
        return r;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Activate an alternate setting for an interface. The interface must have
  * been previously claimed with libusb_claim_interface().
  *
@@ -1489,7 +1663,7 @@ out:
  *
  * This is a blocking function.
  *
- * \param dev a device handle
+ * \param dev_handle a device handle
  * \param interface_number the <tt>bInterfaceNumber</tt> of the
  * previously-claimed interface
  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
@@ -1500,7 +1674,7 @@ out:
  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  * \returns another LIBUSB_ERROR code on other failure
  */
-int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
+int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
        int interface_number, int alternate_setting)
 {
        usbi_dbg("interface %d altsetting %d",
@@ -1508,23 +1682,23 @@ int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
        if (interface_number >= USB_MAXINTERFACES)
                return LIBUSB_ERROR_INVALID_PARAM;
 
-       usbi_mutex_lock(&dev->lock);
-       if (!dev->dev->attached) {
-               usbi_mutex_unlock(&dev->lock);
+       usbi_mutex_lock(&dev_handle->lock);
+       if (!dev_handle->dev->attached) {
+               usbi_mutex_unlock(&dev_handle->lock);
                return LIBUSB_ERROR_NO_DEVICE;
        }
 
-       if (!(dev->claimed_interfaces & (1 << interface_number))) {
-               usbi_mutex_unlock(&dev->lock);
+       if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
+               usbi_mutex_unlock(&dev_handle->lock);
                return LIBUSB_ERROR_NOT_FOUND;
        }
-       usbi_mutex_unlock(&dev->lock);
+       usbi_mutex_unlock(&dev_handle->lock);
 
-       return usbi_backend->set_interface_altsetting(dev, interface_number,
+       return usbi_backend.set_interface_altsetting(dev_handle, interface_number,
                alternate_setting);
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
  * are unable to receive or transmit data until the halt condition is stalled.
  *
@@ -1533,24 +1707,24 @@ int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
  *
  * This is a blocking function.
  *
- * \param dev a device handle
+ * \param dev_handle a device handle
  * \param endpoint the endpoint to clear halt status
  * \returns 0 on success
  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  * \returns another LIBUSB_ERROR code on other failure
  */
-int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
+int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev_handle,
        unsigned char endpoint)
 {
        usbi_dbg("endpoint %x", endpoint);
-       if (!dev->dev->attached)
+       if (!dev_handle->dev->attached)
                return LIBUSB_ERROR_NO_DEVICE;
 
-       return usbi_backend->clear_halt(dev, endpoint);
+       return usbi_backend.clear_halt(dev_handle, endpoint);
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Perform a USB port reset to reinitialize a device. The system will attempt
  * to restore the previous configuration and alternate settings after the
  * reset has completed.
@@ -1563,29 +1737,146 @@ int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
  *
  * This is a blocking function which usually incurs a noticeable delay.
  *
- * \param dev a handle of the device to reset
+ * \param dev_handle a handle of the device to reset
  * \returns 0 on success
  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
  * device has been disconnected
  * \returns another LIBUSB_ERROR code on other failure
  */
-int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
+int API_EXPORTED libusb_reset_device(libusb_device_handle *dev_handle)
 {
        usbi_dbg("");
-       if (!dev->dev->attached)
+       if (!dev_handle->dev->attached)
                return LIBUSB_ERROR_NO_DEVICE;
 
-       return usbi_backend->reset_device(dev);
+       return usbi_backend.reset_device(dev_handle);
 }
 
-/** \ingroup dev
+/** \ingroup libusb_asyncio
+ * Allocate up to num_streams usb bulk streams on the specified endpoints. This
+ * function takes an array of endpoints rather then a single endpoint because
+ * some protocols require that endpoints are setup with similar stream ids.
+ * All endpoints passed in must belong to the same interface.
+ *
+ * Note this function may return less streams then requested. Also note that the
+ * same number of streams are allocated for each endpoint in the endpoint array.
+ *
+ * Stream id 0 is reserved, and should not be used to communicate with devices.
+ * If libusb_alloc_streams() returns with a value of N, you may use stream ids
+ * 1 to N.
+ *
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
+ *
+ * \param dev_handle a device handle
+ * \param num_streams number of streams to try to allocate
+ * \param endpoints array of endpoints to allocate streams on
+ * \param num_endpoints length of the endpoints array
+ * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev_handle,
+       uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
+{
+       usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints);
+
+       if (!dev_handle->dev->attached)
+               return LIBUSB_ERROR_NO_DEVICE;
+
+       if (usbi_backend.alloc_streams)
+               return usbi_backend.alloc_streams(dev_handle, num_streams, endpoints,
+                                                  num_endpoints);
+       else
+               return LIBUSB_ERROR_NOT_SUPPORTED;
+}
+
+/** \ingroup libusb_asyncio
+ * Free usb bulk streams allocated with libusb_alloc_streams().
+ *
+ * Note streams are automatically free-ed when releasing an interface.
+ *
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
+ *
+ * \param dev_handle a device handle
+ * \param endpoints array of endpoints to free streams on
+ * \param num_endpoints length of the endpoints array
+ * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_free_streams(libusb_device_handle *dev_handle,
+       unsigned char *endpoints, int num_endpoints)
+{
+       usbi_dbg("eps %d", num_endpoints);
+
+       if (!dev_handle->dev->attached)
+               return LIBUSB_ERROR_NO_DEVICE;
+
+       if (usbi_backend.free_streams)
+               return usbi_backend.free_streams(dev_handle, endpoints,
+                                                 num_endpoints);
+       else
+               return LIBUSB_ERROR_NOT_SUPPORTED;
+}
+
+/** \ingroup libusb_asyncio
+ * Attempts to allocate a block of persistent DMA memory suitable for transfers
+ * against the given device. If successful, will return a block of memory
+ * that is suitable for use as "buffer" in \ref libusb_transfer against this
+ * device. Using this memory instead of regular memory means that the host
+ * controller can use DMA directly into the buffer to increase performance, and
+ * also that transfers can no longer fail due to kernel memory fragmentation.
+ *
+ * Note that this means you should not modify this memory (or even data on
+ * the same cache lines) when a transfer is in progress, although it is legal
+ * to have several transfers going on within the same memory block.
+ *
+ * Will return NULL on failure. Many systems do not support such zerocopy
+ * and will always return NULL. Memory allocated with this function must be
+ * freed with \ref libusb_dev_mem_free. Specifically, this means that the
+ * flag \ref LIBUSB_TRANSFER_FREE_BUFFER cannot be used to free memory allocated
+ * with this function.
+ *
+ * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
+ *
+ * \param dev_handle a device handle
+ * \param length size of desired data buffer
+ * \returns a pointer to the newly allocated memory, or NULL on failure
+ */
+DEFAULT_VISIBILITY
+unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle,
+        size_t length)
+{
+       if (!dev_handle->dev->attached)
+               return NULL;
+
+       if (usbi_backend.dev_mem_alloc)
+               return usbi_backend.dev_mem_alloc(dev_handle, length);
+       else
+               return NULL;
+}
+
+/** \ingroup libusb_asyncio
+ * Free device memory allocated with libusb_dev_mem_alloc().
+ *
+ * \param dev_handle a device handle
+ * \param buffer pointer to the previously allocated memory
+ * \param length size of previously allocated memory
+ * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_dev_mem_free(libusb_device_handle *dev_handle,
+       unsigned char *buffer, size_t length)
+{
+       if (usbi_backend.dev_mem_free)
+               return usbi_backend.dev_mem_free(dev_handle, buffer, length);
+       else
+               return LIBUSB_ERROR_NOT_SUPPORTED;
+}
+
+/** \ingroup libusb_dev
  * Determine if a kernel driver is active on an interface. If a kernel driver
- * is active, you cannot claim the interface, and libusbx will be unable to
+ * is active, you cannot claim the interface, and libusb will be unable to
  * perform I/O.
  *
  * This functionality is not available on Windows.
  *
- * \param dev a device handle
+ * \param dev_handle a device handle
  * \param interface_number the interface to check
  * \returns 0 if no kernel driver is active
  * \returns 1 if a kernel driver is active
@@ -1595,31 +1886,31 @@ int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
  * \returns another LIBUSB_ERROR code on other failure
  * \see libusb_detach_kernel_driver()
  */
-int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
+int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev_handle,
        int interface_number)
 {
        usbi_dbg("interface %d", interface_number);
 
-       if (!dev->dev->attached)
+       if (!dev_handle->dev->attached)
                return LIBUSB_ERROR_NO_DEVICE;
 
-       if (usbi_backend->kernel_driver_active)
-               return usbi_backend->kernel_driver_active(dev, interface_number);
+       if (usbi_backend.kernel_driver_active)
+               return usbi_backend.kernel_driver_active(dev_handle, interface_number);
        else
                return LIBUSB_ERROR_NOT_SUPPORTED;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Detach a kernel driver from an interface. If successful, you will then be
  * able to claim the interface and perform I/O.
  *
  * This functionality is not available on Darwin or Windows.
  *
- * Note that libusbx itself also talks to the device through a special kernel
+ * Note that libusb itself also talks to the device through a special kernel
  * driver, if this driver is already attached to the device, this call will
  * not detach it and return LIBUSB_ERROR_NOT_FOUND.
  *
- * \param dev a device handle
+ * \param dev_handle a device handle
  * \param interface_number the interface to detach the driver from
  * \returns 0 on success
  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
@@ -1630,28 +1921,28 @@ int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
  * \returns another LIBUSB_ERROR code on other failure
  * \see libusb_kernel_driver_active()
  */
-int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
+int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
        int interface_number)
 {
        usbi_dbg("interface %d", interface_number);
 
-       if (!dev->dev->attached)
+       if (!dev_handle->dev->attached)
                return LIBUSB_ERROR_NO_DEVICE;
 
-       if (usbi_backend->detach_kernel_driver)
-               return usbi_backend->detach_kernel_driver(dev, interface_number);
+       if (usbi_backend.detach_kernel_driver)
+               return usbi_backend.detach_kernel_driver(dev_handle, interface_number);
        else
                return LIBUSB_ERROR_NOT_SUPPORTED;
 }
 
-/** \ingroup dev
+/** \ingroup libusb_dev
  * Re-attach an interface's kernel driver, which was previously detached
  * using libusb_detach_kernel_driver(). This call is only effective on
  * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
  *
  * This functionality is not available on Darwin or Windows.
  *
- * \param dev a device handle
+ * \param dev_handle a device handle
  * \param interface_number the interface to attach the driver from
  * \returns 0 on success
  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
@@ -1664,40 +1955,72 @@ int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
  * \returns another LIBUSB_ERROR code on other failure
  * \see libusb_kernel_driver_active()
  */
-int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
+int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
        int interface_number)
 {
        usbi_dbg("interface %d", interface_number);
 
-       if (!dev->dev->attached)
+       if (!dev_handle->dev->attached)
                return LIBUSB_ERROR_NO_DEVICE;
 
-       if (usbi_backend->attach_kernel_driver)
-               return usbi_backend->attach_kernel_driver(dev, interface_number);
+       if (usbi_backend.attach_kernel_driver)
+               return usbi_backend.attach_kernel_driver(dev_handle, interface_number);
        else
                return LIBUSB_ERROR_NOT_SUPPORTED;
 }
 
-/** \ingroup lib
+/** \ingroup libusb_dev
+ * Enable/disable libusb's automatic kernel driver detachment. When this is
+ * enabled libusb will automatically detach the kernel driver on an interface
+ * when claiming the interface, and attach it when releasing the interface.
+ *
+ * Automatic kernel driver detachment is disabled on newly opened device
+ * handles by default.
+ *
+ * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
+ * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
+ * continue as if this function was never called.
+ *
+ * \param dev_handle a device handle
+ * \param enable whether to enable or disable auto kernel driver detachment
+ *
+ * \returns LIBUSB_SUCCESS on success
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
+ * is not available
+ * \see libusb_claim_interface()
+ * \see libusb_release_interface()
+ * \see libusb_set_configuration()
+ */
+int API_EXPORTED libusb_set_auto_detach_kernel_driver(
+       libusb_device_handle *dev_handle, int enable)
+{
+       if (!(usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
+               return LIBUSB_ERROR_NOT_SUPPORTED;
+
+       dev_handle->auto_detach_kernel_driver = enable;
+       return LIBUSB_SUCCESS;
+}
+
+/** \ingroup libusb_lib
  * Set log message verbosity.
  *
  * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
  * printed. If you choose to increase the message verbosity level, ensure
  * that your application does not close the stdout/stderr file descriptors.
  *
- * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusbx is conservative
+ * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusb is conservative
  * with its message logging and most of the time, will only log messages that
  * explain error conditions and other oddities. This will help you debug
  * your software.
  *
- * If the LIBUSB_DEBUG environment variable was set when libusbx was
+ * If the LIBUSB_DEBUG environment variable was set when libusb was
  * initialized, this function does nothing: the message verbosity is fixed
  * to the value in the environment variable.
  *
- * If libusbx was compiled without any message logging, this function does
+ * If libusb was compiled without any message logging, this function does
  * nothing: you'll never get any messages.
  *
- * If libusbx was compiled with verbose debug message logging, this function
+ * If libusb was compiled with verbose debug message logging, this function
  * does nothing: you'll always get messages from all levels.
  *
  * \param ctx the context to operate on, or NULL for the default context
@@ -1710,9 +2033,9 @@ void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
                ctx->debug = level;
 }
 
-/** \ingroup lib
+/** \ingroup libusb_lib
  * Initialize libusb. This function must be called before calling any other
- * libusbx function.
+ * libusb function.
  *
  * If you do not provide an output location for a context pointer, a default
  * context will be created. If there was already a default context, it will
@@ -1721,12 +2044,13 @@ void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
  * \param context Optional output location for context pointer.
  * Only valid on return code 0.
  * \returns 0 on success, or a LIBUSB_ERROR code on failure
- * \see contexts
+ * \see libusb_contexts
  */
 int API_EXPORTED libusb_init(libusb_context **context)
 {
        struct libusb_device *dev, *next;
        char *dbg = getenv("LIBUSB_DEBUG");
+       size_t priv_size = usbi_backend.context_priv_size;
        struct libusb_context *ctx;
        static int first_init = 1;
        int r = 0;
@@ -1734,7 +2058,7 @@ int API_EXPORTED libusb_init(libusb_context **context)
        usbi_mutex_static_lock(&default_context_lock);
 
        if (!timestamp_origin.tv_sec) {
-               usbi_gettimeofday(&timestamp_origin, NULL);
+               usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &timestamp_origin);
        }
 
        if (!context && usbi_default_context) {
@@ -1744,7 +2068,7 @@ int API_EXPORTED libusb_init(libusb_context **context)
                return 0;
        }
 
-       ctx = calloc(1, sizeof(*ctx));
+       ctx = calloc(1, sizeof(*ctx) + priv_size);
        if (!ctx) {
                r = LIBUSB_ERROR_NO_MEM;
                goto err_unlock;
@@ -1767,12 +2091,12 @@ int API_EXPORTED libusb_init(libusb_context **context)
                usbi_dbg("created default context");
        }
 
-       usbi_dbg("libusbx v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
-               libusb_version_internal.micro, libusb_version_internal.nano);
+       usbi_dbg("libusb v%u.%u.%u.%u%s", libusb_version_internal.major, libusb_version_internal.minor,
+               libusb_version_internal.micro, libusb_version_internal.nano, libusb_version_internal.rc);
 
-       usbi_mutex_init(&ctx->usb_devs_lock, NULL);
-       usbi_mutex_init(&ctx->open_devs_lock, NULL);
-       usbi_mutex_init(&ctx->hotplug_cbs_lock, NULL);
+       usbi_mutex_init(&ctx->usb_devs_lock);
+       usbi_mutex_init(&ctx->open_devs_lock);
+       usbi_mutex_init(&ctx->hotplug_cbs_lock);
        list_init(&ctx->usb_devs);
        list_init(&ctx->open_devs);
        list_init(&ctx->hotplug_cbs);
@@ -1785,8 +2109,8 @@ int API_EXPORTED libusb_init(libusb_context **context)
        list_add (&ctx->list, &active_contexts_list);
        usbi_mutex_static_unlock(&active_contexts_lock);
 
-       if (usbi_backend->init) {
-               r = usbi_backend->init(ctx);
+       if (usbi_backend.init) {
+               r = usbi_backend.init(ctx);
                if (r)
                        goto err_free_ctx;
        }
@@ -1803,15 +2127,13 @@ int API_EXPORTED libusb_init(libusb_context **context)
        return 0;
 
 err_backend_exit:
-       if (usbi_backend->exit)
-               usbi_backend->exit();
+       if (usbi_backend.exit)
+               usbi_backend.exit();
 err_free_ctx:
-       if (ctx == usbi_default_context)
+       if (ctx == usbi_default_context) {
                usbi_default_context = NULL;
-
-       usbi_mutex_destroy(&ctx->open_devs_lock);
-       usbi_mutex_destroy(&ctx->usb_devs_lock);
-       usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
+               default_context_refcnt--;
+       }
 
        usbi_mutex_static_lock(&active_contexts_lock);
        list_del (&ctx->list);
@@ -1824,13 +2146,17 @@ err_free_ctx:
        }
        usbi_mutex_unlock(&ctx->usb_devs_lock);
 
+       usbi_mutex_destroy(&ctx->open_devs_lock);
+       usbi_mutex_destroy(&ctx->usb_devs_lock);
+       usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
+
        free(ctx);
 err_unlock:
        usbi_mutex_static_unlock(&default_context_lock);
        return r;
 }
 
-/** \ingroup lib
+/** \ingroup libusb_lib
  * Deinitialize libusb. Should be called after closing all open devices and
  * before your application terminates.
  * \param ctx the context to deinitialize, or NULL for the default context
@@ -1838,6 +2164,7 @@ err_unlock:
 void API_EXPORTED libusb_exit(struct libusb_context *ctx)
 {
        struct libusb_device *dev, *next;
+       struct timeval tv = { 0, 0 };
 
        usbi_dbg("");
        USBI_GET_CONTEXT(ctx);
@@ -1860,23 +2187,39 @@ void API_EXPORTED libusb_exit(struct libusb_context *ctx)
        list_del (&ctx->list);
        usbi_mutex_static_unlock(&active_contexts_lock);
 
-       usbi_hotplug_deregister_all(ctx);
+       if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
+               usbi_hotplug_deregister_all(ctx);
+
+               /*
+                * Ensure any pending unplug events are read from the hotplug
+                * pipe. The usb_device-s hold in the events are no longer part
+                * of usb_devs, but the events still hold a reference!
+                *
+                * Note we don't do this if the application has left devices
+                * open (which implies a buggy app) to avoid packet completion
+                * handlers running when the app does not expect them to run.
+                */
+               if (list_empty(&ctx->open_devs))
+                       libusb_handle_events_timeout(ctx, &tv);
 
-       usbi_mutex_lock(&ctx->usb_devs_lock);
-       list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
-               list_del(&dev->list);
-               libusb_unref_device(dev);
+               usbi_mutex_lock(&ctx->usb_devs_lock);
+               list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
+                       list_del(&dev->list);
+                       libusb_unref_device(dev);
+               }
+               usbi_mutex_unlock(&ctx->usb_devs_lock);
        }
-       usbi_mutex_unlock(&ctx->usb_devs_lock);
 
-       /* a little sanity check. doesn't bother with open_devs locking because
-        * unless there is an application bug, nobody will be accessing this. */
+       /* a few sanity checks. don't bother with locking because unless
+        * there is an application bug, nobody will be accessing these. */
+       if (!list_empty(&ctx->usb_devs))
+               usbi_warn(ctx, "some libusb_devices were leaked");
        if (!list_empty(&ctx->open_devs))
                usbi_warn(ctx, "application left some devices open");
 
        usbi_io_exit(ctx);
-       if (usbi_backend->exit)
-               usbi_backend->exit();
+       if (usbi_backend.exit)
+               usbi_backend.exit();
 
        usbi_mutex_destroy(&ctx->open_devs_lock);
        usbi_mutex_destroy(&ctx->usb_devs_lock);
@@ -1884,7 +2227,7 @@ void API_EXPORTED libusb_exit(struct libusb_context *ctx)
        free(ctx);
 }
 
-/** \ingroup misc
+/** \ingroup libusb_misc
  * Check at runtime if the loaded library has a given capability.
  * This call should be performed after \ref libusb_init(), to ensure the
  * backend has updated its capability set.
@@ -1898,105 +2241,144 @@ int API_EXPORTED libusb_has_capability(uint32_t capability)
        case LIBUSB_CAP_HAS_CAPABILITY:
                return 1;
        case LIBUSB_CAP_HAS_HOTPLUG:
-               return !(usbi_backend->get_device_list);
+               return !(usbi_backend.get_device_list);
        case LIBUSB_CAP_HAS_HID_ACCESS:
-               return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS);
+               return (usbi_backend.caps & USBI_CAP_HAS_HID_ACCESS);
        case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
-               return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
+               return (usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
        }
        return 0;
 }
 
 /* this is defined in libusbi.h if needed */
-#ifdef LIBUSB_GETTIMEOFDAY_WIN32
-/*
- * gettimeofday
- * Implementation according to:
- * The Open Group Base Specifications Issue 6
- * IEEE Std 1003.1, 2004 Edition
- */
-
+#ifdef LIBUSB_PRINTF_WIN32
 /*
- *  THIS SOFTWARE IS NOT COPYRIGHTED
+ * Prior to VS2015, Microsoft did not provide the snprintf() function and
+ * provided a vsnprintf() that did not guarantee NULL-terminated output.
+ * Microsoft did provide a _snprintf() function, but again it did not
+ * guarantee NULL-terminated output.
  *
- *  This source code is offered for use in the public domain. You may
- *  use, modify or distribute it freely.
- *
- *  This code is distributed in the hope that it will be useful but
- *  WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
- *  DISCLAIMED. This includes but is not limited to warranties of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- *
- *  Contributed by:
- *  Danny Smith <dannysmith@users.sourceforge.net>
+ * The below implementations guarantee NULL-terminated output and are
+ * C99 compliant.
  */
 
-/* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
-#define _W32_FT_OFFSET (116444736000000000)
+int usbi_snprintf(char *str, size_t size, const char *format, ...)
+{
+       va_list ap;
+       int ret;
+
+       va_start(ap, format);
+       ret = usbi_vsnprintf(str, size, format, ap);
+       va_end(ap);
+
+       return ret;
+}
 
-int usbi_gettimeofday(struct timeval *tp, void *tzp)
+int usbi_vsnprintf(char *str, size_t size, const char *format, va_list ap)
 {
-       union {
-               unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
-               FILETIME ft;
-       } _now;
-       UNUSED(tzp);
-
-       if(tp) {
-#if defined(OS_WINCE)
-               SYSTEMTIME st;
-               GetSystemTime(&st);
-               SystemTimeToFileTime(&st, &_now.ft);
-#else
-               GetSystemTimeAsFileTime (&_now.ft);
-#endif
-               tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
-               tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
+       int ret;
+
+       ret = _vsnprintf(str, size, format, ap);
+       if (ret < 0 || ret == (int)size) {
+               /* Output is truncated, ensure buffer is NULL-terminated and
+                * determine how many characters would have been written. */
+               str[size - 1] = '\0';
+               if (ret < 0)
+                       ret = _vsnprintf(NULL, 0, format, ap);
        }
-       /* Always return 0 as per Open Group Base Specifications Issue 6.
-          Do not set errno on error.  */
-       return 0;
+
+       return ret;
 }
 #endif
 
+static void usbi_log_str(struct libusb_context *ctx,
+       enum libusb_log_level level, const char * str)
+{
+#if defined(USE_SYSTEM_LOGGING_FACILITY)
+#if defined(OS_WINDOWS)
+       OutputDebugString(str);
+#elif defined(OS_WINCE)
+       /* Windows CE only supports the Unicode version of OutputDebugString. */
+       WCHAR wbuf[USBI_MAX_LOG_LEN];
+       MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
+       OutputDebugStringW(wbuf);
+#elif defined(__ANDROID__)
+       int priority = ANDROID_LOG_UNKNOWN;
+       switch (level) {
+       case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
+       case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
+       case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
+       case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
+       case LIBUSB_LOG_LEVEL_NONE: return;
+       }
+       __android_log_write(priority, "libusb", str);
+#elif defined(HAVE_SYSLOG_FUNC)
+       int syslog_level = LOG_INFO;
+       switch (level) {
+       case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
+       case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
+       case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
+       case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
+       case LIBUSB_LOG_LEVEL_NONE: return;
+       }
+       syslog(syslog_level, "%s", str);
+#else /* All of gcc, Clang, XCode seem to use #warning */
+#warning System logging is not supported on this platform. Logging to stderr will be used instead.
+       fputs(str, stderr);
+#endif
+#else
+       fputs(str, stderr);
+#endif /* USE_SYSTEM_LOGGING_FACILITY */
+       UNUSED(ctx);
+       UNUSED(level);
+}
+
 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
        const char *function, const char *format, va_list args)
 {
        const char *prefix = "";
-       struct timeval now;
-       int global_debug;
+       char buf[USBI_MAX_LOG_LEN];
+       struct timespec now;
+       int global_debug, header_len, text_len;
        static int has_debug_header_been_displayed = 0;
 
 #ifdef ENABLE_DEBUG_LOGGING
        global_debug = 1;
        UNUSED(ctx);
 #else
+       int ctx_level = 0;
+
        USBI_GET_CONTEXT(ctx);
-       if (ctx == NULL)
-               return;
-       global_debug = (ctx->debug == LIBUSB_LOG_LEVEL_DEBUG);
-       if (!ctx->debug)
+       if (ctx) {
+               ctx_level = ctx->debug;
+       } else {
+               char *dbg = getenv("LIBUSB_DEBUG");
+               if (dbg)
+                       ctx_level = atoi(dbg);
+       }
+       global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
+       if (!ctx_level)
                return;
-       if (level == LIBUSB_LOG_LEVEL_WARNING && ctx->debug < LIBUSB_LOG_LEVEL_WARNING)
+       if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING)
                return;
-       if (level == LIBUSB_LOG_LEVEL_INFO && ctx->debug < LIBUSB_LOG_LEVEL_INFO)
+       if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO)
                return;
-       if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx->debug < LIBUSB_LOG_LEVEL_DEBUG)
+       if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG)
                return;
 #endif
 
-       usbi_gettimeofday(&now, NULL);
+       usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &now);
        if ((global_debug) && (!has_debug_header_been_displayed)) {
                has_debug_header_been_displayed = 1;
-               fprintf(stderr, "[timestamp] [threadID] facility level [function call] <message>\n");
-               fprintf(stderr, "--------------------------------------------------------------------------------\n");
+               usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>" USBI_LOG_LINE_END);
+               usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END);
        }
-       if (now.tv_usec < timestamp_origin.tv_usec) {
+       if (now.tv_nsec < timestamp_origin.tv_nsec) {
                now.tv_sec--;
-               now.tv_usec += 1000000;
+               now.tv_nsec += 1000000000L;
        }
        now.tv_sec -= timestamp_origin.tv_sec;
-       now.tv_usec -= timestamp_origin.tv_usec;
+       now.tv_nsec -= timestamp_origin.tv_nsec;
 
        switch (level) {
        case LIBUSB_LOG_LEVEL_INFO:
@@ -2012,22 +2394,42 @@ void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
                prefix = "debug";
                break;
        case LIBUSB_LOG_LEVEL_NONE:
-               break;
+               return;
        default:
                prefix = "unknown";
                break;
        }
 
        if (global_debug) {
-               fprintf(stderr, "[%2d.%06d] [%08x] libusbx: %s [%s] ",
-                       (int)now.tv_sec, (int)now.tv_usec, usbi_get_tid(), prefix, function);
+               header_len = snprintf(buf, sizeof(buf),
+                       "[%2d.%06d] [%08x] libusb: %s [%s] ",
+                       (int)now.tv_sec, (int)(now.tv_nsec / 1000L), usbi_get_tid(), prefix, function);
        } else {
-               fprintf(stderr, "libusbx: %s [%s] ", prefix, function);
+               header_len = snprintf(buf, sizeof(buf),
+                       "libusb: %s [%s] ", prefix, function);
        }
 
-       vfprintf(stderr, format, args);
+       if (header_len < 0 || header_len >= (int)sizeof(buf)) {
+               /* Somehow snprintf failed to write to the buffer,
+                * remove the header so something useful is output. */
+               header_len = 0;
+       }
+       /* Make sure buffer is NUL terminated */
+       buf[header_len] = '\0';
+       text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
+               format, args);
+       if (text_len < 0 || text_len + header_len >= (int)sizeof(buf)) {
+               /* Truncated log output. On some platforms a -1 return value means
+                * that the output was truncated. */
+               text_len = sizeof(buf) - header_len;
+       }
+       if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
+               /* Need to truncate the text slightly to fit on the terminator. */
+               text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
+       }
+       strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
 
-       fprintf(stderr, "\n");
+       usbi_log_str(ctx, level, buf);
 }
 
 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
@@ -2040,8 +2442,8 @@ void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
        va_end (args);
 }
 
-/** \ingroup misc
- * Returns a constant NULL-terminated string with the ASCII name of a libusbx
+/** \ingroup libusb_misc
+ * Returns a constant NULL-terminated string with the ASCII name of a libusb
  * error or transfer status code. The caller must not free() the returned
  * string.
  *
@@ -2100,7 +2502,7 @@ DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
        }
 }
 
-/** \ingroup misc
+/** \ingroup libusb_misc
  * Returns a pointer to const struct libusb_version with the version
  * (major, minor, micro, nano and rc) of the running library.
  */