Home | History | Annotate | Download | only in libusb
      1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
      2 /*
      3  * Core functions for libusbx
      4  * Copyright  2012-2013 Nathan Hjelm <hjelmn (at) cs.unm.edu>
      5  * Copyright  2007-2008 Daniel Drake <dsd (at) gentoo.org>
      6  * Copyright  2001 Johannes Erdfelt <johannes (at) erdfelt.com>
      7  *
      8  * This library is free software; you can redistribute it and/or
      9  * modify it under the terms of the GNU Lesser General Public
     10  * License as published by the Free Software Foundation; either
     11  * version 2.1 of the License, or (at your option) any later version.
     12  *
     13  * This library is distributed in the hope that it will be useful,
     14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     16  * Lesser General Public License for more details.
     17  *
     18  * You should have received a copy of the GNU Lesser General Public
     19  * License along with this library; if not, write to the Free Software
     20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
     21  */
     22 
     23 #include "config.h"
     24 
     25 #include <errno.h>
     26 #include <stdarg.h>
     27 #include <stdio.h>
     28 #include <stdlib.h>
     29 #include <string.h>
     30 #ifdef HAVE_SYS_TYPES_H
     31 #include <sys/types.h>
     32 #endif
     33 #ifdef HAVE_SYS_TIME_H
     34 #include <sys/time.h>
     35 #endif
     36 
     37 #ifdef __ANDROID__
     38 #include <android/log.h>
     39 #endif
     40 
     41 #include "libusbi.h"
     42 #include "hotplug.h"
     43 
     44 #if defined(OS_LINUX)
     45 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
     46 #elif defined(OS_DARWIN)
     47 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
     48 #elif defined(OS_OPENBSD)
     49 const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
     50 #elif defined(OS_WINDOWS)
     51 const struct usbi_os_backend * const usbi_backend = &windows_backend;
     52 #elif defined(OS_WINCE)
     53 const struct usbi_os_backend * const usbi_backend = &wince_backend;
     54 #else
     55 #error "Unsupported OS"
     56 #endif
     57 
     58 struct libusb_context *usbi_default_context = NULL;
     59 const struct libusb_version libusb_version_internal =
     60 	{ LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
     61 	  LIBUSB_RC, "http://libusbx.org" };
     62 static int default_context_refcnt = 0;
     63 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
     64 static struct timeval timestamp_origin = { 0, 0 };
     65 
     66 usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
     67 struct list_head active_contexts_list;
     68 
     69 /**
     70  * \mainpage libusbx-1.0 API Reference
     71  *
     72  * \section intro Introduction
     73  *
     74  * libusbx is an open source library that allows you to communicate with USB
     75  * devices from userspace. For more info, see the
     76  * <a href="http://libusbx.org">libusbx homepage</a>.
     77  *
     78  * This documentation is aimed at application developers wishing to
     79  * communicate with USB peripherals from their own software. After reviewing
     80  * this documentation, feedback and questions can be sent to the
     81  * <a href="http://mailing-list.libusbx.org">libusbx-devel mailing list</a>.
     82  *
     83  * This documentation assumes knowledge of how to operate USB devices from
     84  * a software standpoint (descriptors, configurations, interfaces, endpoints,
     85  * control/bulk/interrupt/isochronous transfers, etc). Full information
     86  * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
     87  * Specification</a> which is available for free download. You can probably
     88  * find less verbose introductions by searching the web.
     89  *
     90  * \section features Library features
     91  *
     92  * - All transfer types supported (control/bulk/interrupt/isochronous)
     93  * - 2 transfer interfaces:
     94  *    -# Synchronous (simple)
     95  *    -# Asynchronous (more complicated, but more powerful)
     96  * - Thread safe (although the asynchronous interface means that you
     97  *   usually won't need to thread)
     98  * - Lightweight with lean API
     99  * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
    100  * - Hotplug support (on some platforms). See \ref hotplug.
    101  *
    102  * \section gettingstarted Getting Started
    103  *
    104  * To begin reading the API documentation, start with the Modules page which
    105  * links to the different categories of libusbx's functionality.
    106  *
    107  * One decision you will have to make is whether to use the synchronous
    108  * or the asynchronous data transfer interface. The \ref io documentation
    109  * provides some insight into this topic.
    110  *
    111  * Some example programs can be found in the libusbx source distribution under
    112  * the "examples" subdirectory. The libusbx homepage includes a list of
    113  * real-life project examples which use libusbx.
    114  *
    115  * \section errorhandling Error handling
    116  *
    117  * libusbx functions typically return 0 on success or a negative error code
    118  * on failure. These negative error codes relate to LIBUSB_ERROR constants
    119  * which are listed on the \ref misc "miscellaneous" documentation page.
    120  *
    121  * \section msglog Debug message logging
    122  *
    123  * libusbx uses stderr for all logging. By default, logging is set to NONE,
    124  * which means that no output will be produced. However, unless the library
    125  * has been compiled with logging disabled, then any application calls to
    126  * libusb_set_debug(), or the setting of the environmental variable
    127  * LIBUSB_DEBUG outside of the application, can result in logging being
    128  * produced. Your application should therefore not close stderr, but instead
    129  * direct it to the null device if its output is undesireable.
    130  *
    131  * The libusb_set_debug() function can be used to enable logging of certain
    132  * messages. Under standard configuration, libusbx doesn't really log much
    133  * so you are advised to use this function to enable all error/warning/
    134  * informational messages. It will help debug problems with your software.
    135  *
    136  * The logged messages are unstructured. There is no one-to-one correspondence
    137  * between messages being logged and success or failure return codes from
    138  * libusbx functions. There is no format to the messages, so you should not
    139  * try to capture or parse them. They are not and will not be localized.
    140  * These messages are not intended to being passed to your application user;
    141  * instead, you should interpret the error codes returned from libusbx functions
    142  * and provide appropriate notification to the user. The messages are simply
    143  * there to aid you as a programmer, and if you're confused because you're
    144  * getting a strange error code from a libusbx function, enabling message
    145  * logging may give you a suitable explanation.
    146  *
    147  * The LIBUSB_DEBUG environment variable can be used to enable message logging
    148  * at run-time. This environment variable should be set to a log level number,
    149  * which is interpreted the same as the libusb_set_debug() parameter. When this
    150  * environment variable is set, the message logging verbosity level is fixed
    151  * and libusb_set_debug() effectively does nothing.
    152  *
    153  * libusbx can be compiled without any logging functions, useful for embedded
    154  * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
    155  * variable have no effects.
    156  *
    157  * libusbx can also be compiled with verbose debugging messages always. When
    158  * the library is compiled in this way, all messages of all verbosities are
    159  * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
    160  * have no effects.
    161  *
    162  * \section remarks Other remarks
    163  *
    164  * libusbx does have imperfections. The \ref caveats "caveats" page attempts
    165  * to document these.
    166  */
    167 
    168 /**
    169  * \page caveats Caveats
    170  *
    171  * \section devresets Device resets
    172  *
    173  * The libusb_reset_device() function allows you to reset a device. If your
    174  * program has to call such a function, it should obviously be aware that
    175  * the reset will cause device state to change (e.g. register values may be
    176  * reset).
    177  *
    178  * The problem is that any other program could reset the device your program
    179  * is working with, at any time. libusbx does not offer a mechanism to inform
    180  * you when this has happened, so if someone else resets your device it will
    181  * not be clear to your own program why the device state has changed.
    182  *
    183  * Ultimately, this is a limitation of writing drivers in userspace.
    184  * Separation from the USB stack in the underlying kernel makes it difficult
    185  * for the operating system to deliver such notifications to your program.
    186  * The Linux kernel USB stack allows such reset notifications to be delivered
    187  * to in-kernel USB drivers, but it is not clear how such notifications could
    188  * be delivered to second-class drivers that live in userspace.
    189  *
    190  * \section blockonly Blocking-only functionality
    191  *
    192  * The functionality listed below is only available through synchronous,
    193  * blocking functions. There are no asynchronous/non-blocking alternatives,
    194  * and no clear ways of implementing these.
    195  *
    196  * - Configuration activation (libusb_set_configuration())
    197  * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
    198  * - Releasing of interfaces (libusb_release_interface())
    199  * - Clearing of halt/stall condition (libusb_clear_halt())
    200  * - Device resets (libusb_reset_device())
    201  *
    202  * \section configsel Configuration selection and handling
    203  *
    204  * When libusbx presents a device handle to an application, there is a chance
    205  * that the corresponding device may be in unconfigured state. For devices
    206  * with multiple configurations, there is also a chance that the configuration
    207  * currently selected is not the one that the application wants to use.
    208  *
    209  * The obvious solution is to add a call to libusb_set_configuration() early
    210  * on during your device initialization routines, but there are caveats to
    211  * be aware of:
    212  * -# If the device is already in the desired configuration, calling
    213  *    libusb_set_configuration() using the same configuration value will cause
    214  *    a lightweight device reset. This may not be desirable behaviour.
    215  * -# libusbx will be unable to change configuration if the device is in
    216  *    another configuration and other programs or drivers have claimed
    217  *    interfaces under that configuration.
    218  * -# In the case where the desired configuration is already active, libusbx
    219  *    may not even be able to perform a lightweight device reset. For example,
    220  *    take my USB keyboard with fingerprint reader: I'm interested in driving
    221  *    the fingerprint reader interface through libusbx, but the kernel's
    222  *    USB-HID driver will almost always have claimed the keyboard interface.
    223  *    Because the kernel has claimed an interface, it is not even possible to
    224  *    perform the lightweight device reset, so libusb_set_configuration() will
    225  *    fail. (Luckily the device in question only has a single configuration.)
    226  *
    227  * One solution to some of the above problems is to consider the currently
    228  * active configuration. If the configuration we want is already active, then
    229  * we don't have to select any configuration:
    230 \code
    231 cfg = libusb_get_configuration(dev);
    232 if (cfg != desired)
    233 	libusb_set_configuration(dev, desired);
    234 \endcode
    235  *
    236  * This is probably suitable for most scenarios, but is inherently racy:
    237  * another application or driver may change the selected configuration
    238  * <em>after</em> the libusb_get_configuration() call.
    239  *
    240  * Even in cases where libusb_set_configuration() succeeds, consider that other
    241  * applications or drivers may change configuration after your application
    242  * calls libusb_set_configuration().
    243  *
    244  * One possible way to lock your device into a specific configuration is as
    245  * follows:
    246  * -# Set the desired configuration (or use the logic above to realise that
    247  *    it is already in the desired configuration)
    248  * -# Claim the interface that you wish to use
    249  * -# Check that the currently active configuration is the one that you want
    250  *    to use.
    251  *
    252  * The above method works because once an interface is claimed, no application
    253  * or driver is able to select another configuration.
    254  *
    255  * \section earlycomp Early transfer completion
    256  *
    257  * NOTE: This section is currently Linux-centric. I am not sure if any of these
    258  * considerations apply to Darwin or other platforms.
    259  *
    260  * When a transfer completes early (i.e. when less data is received/sent in
    261  * any one packet than the transfer buffer allows for) then libusbx is designed
    262  * to terminate the transfer immediately, not transferring or receiving any
    263  * more data unless other transfers have been queued by the user.
    264  *
    265  * On legacy platforms, libusbx is unable to do this in all situations. After
    266  * the incomplete packet occurs, "surplus" data may be transferred. For recent
    267  * versions of libusbx, this information is kept (the data length of the
    268  * transfer is updated) and, for device-to-host transfers, any surplus data was
    269  * added to the buffer. Still, this is not a nice solution because it loses the
    270  * information about the end of the short packet, and the user probably wanted
    271  * that surplus data to arrive in the next logical transfer.
    272  *
    273  *
    274  * \section zlp Zero length packets
    275  *
    276  * - libusbx is able to send a packet of zero length to an endpoint simply by
    277  * submitting a transfer of zero length.
    278  * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
    279  * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
    280  */
    281 
    282 /**
    283  * \page contexts Contexts
    284  *
    285  * It is possible that libusbx may be used simultaneously from two independent
    286  * libraries linked into the same executable. For example, if your application
    287  * has a plugin-like system which allows the user to dynamically load a range
    288  * of modules into your program, it is feasible that two independently
    289  * developed modules may both use libusbx.
    290  *
    291  * libusbx is written to allow for these multiple user scenarios. The two
    292  * "instances" of libusbx will not interfere: libusb_set_debug() calls
    293  * from one user will not affect the same settings for other users, other
    294  * users can continue using libusbx after one of them calls libusb_exit(), etc.
    295  *
    296  * This is made possible through libusbx's <em>context</em> concept. When you
    297  * call libusb_init(), you are (optionally) given a context. You can then pass
    298  * this context pointer back into future libusbx functions.
    299  *
    300  * In order to keep things simple for more simplistic applications, it is
    301  * legal to pass NULL to all functions requiring a context pointer (as long as
    302  * you're sure no other code will attempt to use libusbx from the same process).
    303  * When you pass NULL, the default context will be used. The default context
    304  * is created the first time a process calls libusb_init() when no other
    305  * context is alive. Contexts are destroyed during libusb_exit().
    306  *
    307  * The default context is reference-counted and can be shared. That means that
    308  * if libusb_init(NULL) is called twice within the same process, the two
    309  * users end up sharing the same context. The deinitialization and freeing of
    310  * the default context will only happen when the last user calls libusb_exit().
    311  * In other words, the default context is created and initialized when its
    312  * reference count goes from 0 to 1, and is deinitialized and destroyed when
    313  * its reference count goes from 1 to 0.
    314  *
    315  * You may be wondering why only a subset of libusbx functions require a
    316  * context pointer in their function definition. Internally, libusbx stores
    317  * context pointers in other objects (e.g. libusb_device instances) and hence
    318  * can infer the context from those objects.
    319  */
    320 
    321 /**
    322  * @defgroup lib Library initialization/deinitialization
    323  * This page details how to initialize and deinitialize libusbx. Initialization
    324  * must be performed before using any libusbx functionality, and similarly you
    325  * must not call any libusbx functions after deinitialization.
    326  */
    327 
    328 /**
    329  * @defgroup dev Device handling and enumeration
    330  * The functionality documented below is designed to help with the following
    331  * operations:
    332  * - Enumerating the USB devices currently attached to the system
    333  * - Choosing a device to operate from your software
    334  * - Opening and closing the chosen device
    335  *
    336  * \section nutshell In a nutshell...
    337  *
    338  * The description below really makes things sound more complicated than they
    339  * actually are. The following sequence of function calls will be suitable
    340  * for almost all scenarios and does not require you to have such a deep
    341  * understanding of the resource management issues:
    342  * \code
    343 // discover devices
    344 libusb_device **list;
    345 libusb_device *found = NULL;
    346 ssize_t cnt = libusb_get_device_list(NULL, &list);
    347 ssize_t i = 0;
    348 int err = 0;
    349 if (cnt < 0)
    350 	error();
    351 
    352 for (i = 0; i < cnt; i++) {
    353 	libusb_device *device = list[i];
    354 	if (is_interesting(device)) {
    355 		found = device;
    356 		break;
    357 	}
    358 }
    359 
    360 if (found) {
    361 	libusb_device_handle *handle;
    362 
    363 	err = libusb_open(found, &handle);
    364 	if (err)
    365 		error();
    366 	// etc
    367 }
    368 
    369 libusb_free_device_list(list, 1);
    370 \endcode
    371  *
    372  * The two important points:
    373  * - You asked libusb_free_device_list() to unreference the devices (2nd
    374  *   parameter)
    375  * - You opened the device before freeing the list and unreferencing the
    376  *   devices
    377  *
    378  * If you ended up with a handle, you can now proceed to perform I/O on the
    379  * device.
    380  *
    381  * \section devshandles Devices and device handles
    382  * libusbx has a concept of a USB device, represented by the
    383  * \ref libusb_device opaque type. A device represents a USB device that
    384  * is currently or was previously connected to the system. Using a reference
    385  * to a device, you can determine certain information about the device (e.g.
    386  * you can read the descriptor data).
    387  *
    388  * The libusb_get_device_list() function can be used to obtain a list of
    389  * devices currently connected to the system. This is known as device
    390  * discovery.
    391  *
    392  * Just because you have a reference to a device does not mean it is
    393  * necessarily usable. The device may have been unplugged, you may not have
    394  * permission to operate such device, or another program or driver may be
    395  * using the device.
    396  *
    397  * When you've found a device that you'd like to operate, you must ask
    398  * libusbx to open the device using the libusb_open() function. Assuming
    399  * success, libusbx then returns you a <em>device handle</em>
    400  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
    401  * operate on the handle rather than the original device pointer.
    402  *
    403  * \section devref Device discovery and reference counting
    404  *
    405  * Device discovery (i.e. calling libusb_get_device_list()) returns a
    406  * freshly-allocated list of devices. The list itself must be freed when
    407  * you are done with it. libusbx also needs to know when it is OK to free
    408  * the contents of the list - the devices themselves.
    409  *
    410  * To handle these issues, libusbx provides you with two separate items:
    411  * - A function to free the list itself
    412  * - A reference counting system for the devices inside
    413  *
    414  * New devices presented by the libusb_get_device_list() function all have a
    415  * reference count of 1. You can increase and decrease reference count using
    416  * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
    417  * its reference count reaches 0.
    418  *
    419  * With the above information in mind, the process of opening a device can
    420  * be viewed as follows:
    421  * -# Discover devices using libusb_get_device_list().
    422  * -# Choose the device that you want to operate, and call libusb_open().
    423  * -# Unref all devices in the discovered device list.
    424  * -# Free the discovered device list.
    425  *
    426  * The order is important - you must not unreference the device before
    427  * attempting to open it, because unreferencing it may destroy the device.
    428  *
    429  * For convenience, the libusb_free_device_list() function includes a
    430  * parameter to optionally unreference all the devices in the list before
    431  * freeing the list itself. This combines steps 3 and 4 above.
    432  *
    433  * As an implementation detail, libusb_open() actually adds a reference to
    434  * the device in question. This is because the device remains available
    435  * through the handle via libusb_get_device(). The reference is deleted during
    436  * libusb_close().
    437  */
    438 
    439 /** @defgroup misc Miscellaneous */
    440 
    441 /* we traverse usbfs without knowing how many devices we are going to find.
    442  * so we create this discovered_devs model which is similar to a linked-list
    443  * which grows when required. it can be freed once discovery has completed,
    444  * eliminating the need for a list node in the libusb_device structure
    445  * itself. */
    446 #define DISCOVERED_DEVICES_SIZE_STEP 8
    447 
    448 static struct discovered_devs *discovered_devs_alloc(void)
    449 {
    450 	struct discovered_devs *ret =
    451 		malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
    452 
    453 	if (ret) {
    454 		ret->len = 0;
    455 		ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
    456 	}
    457 	return ret;
    458 }
    459 
    460 /* append a device to the discovered devices collection. may realloc itself,
    461  * returning new discdevs. returns NULL on realloc failure. */
    462 struct discovered_devs *discovered_devs_append(
    463 	struct discovered_devs *discdevs, struct libusb_device *dev)
    464 {
    465 	size_t len = discdevs->len;
    466 	size_t capacity;
    467 
    468 	/* if there is space, just append the device */
    469 	if (len < discdevs->capacity) {
    470 		discdevs->devices[len] = libusb_ref_device(dev);
    471 		discdevs->len++;
    472 		return discdevs;
    473 	}
    474 
    475 	/* exceeded capacity, need to grow */
    476 	usbi_dbg("need to increase capacity");
    477 	capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
    478 	discdevs = usbi_reallocf(discdevs,
    479 		sizeof(*discdevs) + (sizeof(void *) * capacity));
    480 	if (discdevs) {
    481 		discdevs->capacity = capacity;
    482 		discdevs->devices[len] = libusb_ref_device(dev);
    483 		discdevs->len++;
    484 	}
    485 
    486 	return discdevs;
    487 }
    488 
    489 static void discovered_devs_free(struct discovered_devs *discdevs)
    490 {
    491 	size_t i;
    492 
    493 	for (i = 0; i < discdevs->len; i++)
    494 		libusb_unref_device(discdevs->devices[i]);
    495 
    496 	free(discdevs);
    497 }
    498 
    499 /* Allocate a new device with a specific session ID. The returned device has
    500  * a reference count of 1. */
    501 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
    502 	unsigned long session_id)
    503 {
    504 	size_t priv_size = usbi_backend->device_priv_size;
    505 	struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
    506 	int r;
    507 
    508 	if (!dev)
    509 		return NULL;
    510 
    511 	r = usbi_mutex_init(&dev->lock, NULL);
    512 	if (r) {
    513 		free(dev);
    514 		return NULL;
    515 	}
    516 
    517 	dev->ctx = ctx;
    518 	dev->refcnt = 1;
    519 	dev->session_data = session_id;
    520 	dev->speed = LIBUSB_SPEED_UNKNOWN;
    521 
    522 	if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
    523 		usbi_connect_device (dev);
    524 	}
    525 
    526 	return dev;
    527 }
    528 
    529 void usbi_connect_device(struct libusb_device *dev)
    530 {
    531 	libusb_hotplug_message message;
    532 	ssize_t ret;
    533 
    534 	memset(&message, 0, sizeof(message));
    535 	message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED;
    536 	message.device = dev;
    537 	dev->attached = 1;
    538 
    539 	usbi_mutex_lock(&dev->ctx->usb_devs_lock);
    540 	list_add(&dev->list, &dev->ctx->usb_devs);
    541 	usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
    542 
    543 	/* Signal that an event has occurred for this device if we support hotplug AND
    544 	 * the hotplug pipe is ready. This prevents an event from getting raised during
    545 	 * initial enumeration. */
    546 	if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_pipe[1] > 0) {
    547 		ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
    548 		if (sizeof (message) != ret) {
    549 			usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
    550 		}
    551 	}
    552 }
    553 
    554 void usbi_disconnect_device(struct libusb_device *dev)
    555 {
    556 	libusb_hotplug_message message;
    557 	struct libusb_context *ctx = dev->ctx;
    558 	ssize_t ret;
    559 
    560 	memset(&message, 0, sizeof(message));
    561 	message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT;
    562 	message.device = dev;
    563 	usbi_mutex_lock(&dev->lock);
    564 	dev->attached = 0;
    565 	usbi_mutex_unlock(&dev->lock);
    566 
    567 	/* Signal that an event has occurred for this device if we support hotplug AND
    568 	 * the hotplug pipe is ready. This prevents an event from getting raised during
    569 	 * initial enumeration. libusb_handle_events will take care of dereferencing the
    570 	 * device. */
    571 	if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_pipe[1] > 0) {
    572 		ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
    573 		if (sizeof(message) != ret) {
    574 			usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
    575 		}
    576 	}
    577 
    578 	usbi_mutex_lock(&ctx->usb_devs_lock);
    579 	list_del(&dev->list);
    580 	usbi_mutex_unlock(&ctx->usb_devs_lock);
    581 }
    582 
    583 /* Perform some final sanity checks on a newly discovered device. If this
    584  * function fails (negative return code), the device should not be added
    585  * to the discovered device list. */
    586 int usbi_sanitize_device(struct libusb_device *dev)
    587 {
    588 	int r;
    589 	uint8_t num_configurations;
    590 
    591 	r = usbi_device_cache_descriptor(dev);
    592 	if (r < 0)
    593 		return r;
    594 
    595 	num_configurations = dev->device_descriptor.bNumConfigurations;
    596 	if (num_configurations > USB_MAXCONFIG) {
    597 		usbi_err(DEVICE_CTX(dev), "too many configurations");
    598 		return LIBUSB_ERROR_IO;
    599 	} else if (0 == num_configurations)
    600 		usbi_dbg("zero configurations, maybe an unauthorized device");
    601 
    602 	dev->num_configurations = num_configurations;
    603 	return 0;
    604 }
    605 
    606 /* Examine libusbx's internal list of known devices, looking for one with
    607  * a specific session ID. Returns the matching device if it was found, and
    608  * NULL otherwise. */
    609 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
    610 	unsigned long session_id)
    611 {
    612 	struct libusb_device *dev;
    613 	struct libusb_device *ret = NULL;
    614 
    615 	usbi_mutex_lock(&ctx->usb_devs_lock);
    616 	list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
    617 		if (dev->session_data == session_id) {
    618 			ret = dev;
    619 			break;
    620 		}
    621 	usbi_mutex_unlock(&ctx->usb_devs_lock);
    622 
    623 	return ret;
    624 }
    625 
    626 /** @ingroup dev
    627  * Returns a list of USB devices currently attached to the system. This is
    628  * your entry point into finding a USB device to operate.
    629  *
    630  * You are expected to unreference all the devices when you are done with
    631  * them, and then free the list with libusb_free_device_list(). Note that
    632  * libusb_free_device_list() can unref all the devices for you. Be careful
    633  * not to unreference a device you are about to open until after you have
    634  * opened it.
    635  *
    636  * This return value of this function indicates the number of devices in
    637  * the resultant list. The list is actually one element larger, as it is
    638  * NULL-terminated.
    639  *
    640  * \param ctx the context to operate on, or NULL for the default context
    641  * \param list output location for a list of devices. Must be later freed with
    642  * libusb_free_device_list().
    643  * \returns the number of devices in the outputted list, or any
    644  * \ref libusb_error according to errors encountered by the backend.
    645  */
    646 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
    647 	libusb_device ***list)
    648 {
    649 	struct discovered_devs *discdevs = discovered_devs_alloc();
    650 	struct libusb_device **ret;
    651 	int r = 0;
    652 	ssize_t i, len;
    653 	USBI_GET_CONTEXT(ctx);
    654 	usbi_dbg("");
    655 
    656 	if (!discdevs)
    657 		return LIBUSB_ERROR_NO_MEM;
    658 
    659 	if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
    660 		/* backend provides hotplug support */
    661 		struct libusb_device *dev;
    662 
    663 		if (usbi_backend->hotplug_poll)
    664 			usbi_backend->hotplug_poll();
    665 
    666 		usbi_mutex_lock(&ctx->usb_devs_lock);
    667 		list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
    668 			discdevs = discovered_devs_append(discdevs, dev);
    669 
    670 			if (!discdevs) {
    671 				r = LIBUSB_ERROR_NO_MEM;
    672 				break;
    673 			}
    674 		}
    675 		usbi_mutex_unlock(&ctx->usb_devs_lock);
    676 	} else {
    677 		/* backend does not provide hotplug support */
    678 		r = usbi_backend->get_device_list(ctx, &discdevs);
    679 	}
    680 
    681 	if (r < 0) {
    682 		len = r;
    683 		goto out;
    684 	}
    685 
    686 	/* convert discovered_devs into a list */
    687 	len = discdevs->len;
    688 	ret = calloc(len + 1, sizeof(struct libusb_device *));
    689 	if (!ret) {
    690 		len = LIBUSB_ERROR_NO_MEM;
    691 		goto out;
    692 	}
    693 
    694 	ret[len] = NULL;
    695 	for (i = 0; i < len; i++) {
    696 		struct libusb_device *dev = discdevs->devices[i];
    697 		ret[i] = libusb_ref_device(dev);
    698 	}
    699 	*list = ret;
    700 
    701 out:
    702 	discovered_devs_free(discdevs);
    703 	return len;
    704 }
    705 
    706 /** \ingroup dev
    707  * Frees a list of devices previously discovered using
    708  * libusb_get_device_list(). If the unref_devices parameter is set, the
    709  * reference count of each device in the list is decremented by 1.
    710  * \param list the list to free
    711  * \param unref_devices whether to unref the devices in the list
    712  */
    713 void API_EXPORTED libusb_free_device_list(libusb_device **list,
    714 	int unref_devices)
    715 {
    716 	if (!list)
    717 		return;
    718 
    719 	if (unref_devices) {
    720 		int i = 0;
    721 		struct libusb_device *dev;
    722 
    723 		while ((dev = list[i++]) != NULL)
    724 			libusb_unref_device(dev);
    725 	}
    726 	free(list);
    727 }
    728 
    729 /** \ingroup dev
    730  * Get the number of the bus that a device is connected to.
    731  * \param dev a device
    732  * \returns the bus number
    733  */
    734 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
    735 {
    736 	return dev->bus_number;
    737 }
    738 
    739 /** \ingroup dev
    740  * Get the number of the port that a device is connected to.
    741  * Unless the OS does something funky, or you are hot-plugging USB extension cards,
    742  * the port number returned by this call is usually guaranteed to be uniquely tied
    743  * to a physical port, meaning that different devices plugged on the same physical
    744  * port should return the same port number.
    745  *
    746  * But outside of this, there is no guarantee that the port number returned by this
    747  * call will remain the same, or even match the order in which ports have been
    748  * numbered by the HUB/HCD manufacturer.
    749  *
    750  * \param dev a device
    751  * \returns the port number (0 if not available)
    752  */
    753 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
    754 {
    755 	return dev->port_number;
    756 }
    757 
    758 /** \ingroup dev
    759  * Get the list of all port numbers from root for the specified device
    760  *
    761  * Since version 1.0.16, \ref LIBUSBX_API_VERSION >= 0x01000102
    762  * \param dev a device
    763  * \param port_numbers the array that should contain the port numbers
    764  * \param port_numbers_len the maximum length of the array. As per the USB 3.0
    765  * specs, the current maximum limit for the depth is 7.
    766  * \returns the number of elements filled
    767  * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
    768  */
    769 int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
    770 	uint8_t* port_numbers, int port_numbers_len)
    771 {
    772 	int i = port_numbers_len;
    773 
    774 	while(dev) {
    775 		// HCDs can be listed as devices and would have port #0
    776 		// TODO: see how the other backends want to implement HCDs as parents
    777 		if (dev->port_number == 0)
    778 			break;
    779 		i--;
    780 		if (i < 0) {
    781 			usbi_warn(DEVICE_CTX(dev),
    782 				"port numbers array too small");
    783 			return LIBUSB_ERROR_OVERFLOW;
    784 		}
    785 		port_numbers[i] = dev->port_number;
    786 		dev = dev->parent_dev;
    787 	}
    788 	memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
    789 	return port_numbers_len - i;
    790 }
    791 
    792 /** \ingroup dev
    793  * Deprecated please use libusb_get_port_numbers instead.
    794  */
    795 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
    796 	uint8_t* port_numbers, uint8_t port_numbers_len)
    797 {
    798 	UNUSED(ctx);
    799 
    800 	return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
    801 }
    802 
    803 /** \ingroup dev
    804  * Get the the parent from the specified device.
    805  * \param dev a device
    806  * \returns the device parent or NULL if not available
    807  * You should issue a \ref libusb_get_device_list() before calling this
    808  * function and make sure that you only access the parent before issuing
    809  * \ref libusb_free_device_list(). The reason is that libusbx currently does
    810  * not maintain a permanent list of device instances, and therefore can
    811  * only guarantee that parents are fully instantiated within a
    812  * libusb_get_device_list() - libusb_free_device_list() block.
    813  */
    814 DEFAULT_VISIBILITY
    815 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
    816 {
    817 	return dev->parent_dev;
    818 }
    819 
    820 /** \ingroup dev
    821  * Get the address of the device on the bus it is connected to.
    822  * \param dev a device
    823  * \returns the device address
    824  */
    825 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
    826 {
    827 	return dev->device_address;
    828 }
    829 
    830 /** \ingroup dev
    831  * Get the negotiated connection speed for a device.
    832  * \param dev a device
    833  * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
    834  * the OS doesn't know or doesn't support returning the negotiated speed.
    835  */
    836 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
    837 {
    838 	return dev->speed;
    839 }
    840 
    841 static const struct libusb_endpoint_descriptor *find_endpoint(
    842 	struct libusb_config_descriptor *config, unsigned char endpoint)
    843 {
    844 	int iface_idx;
    845 	for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
    846 		const struct libusb_interface *iface = &config->interface[iface_idx];
    847 		int altsetting_idx;
    848 
    849 		for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
    850 				altsetting_idx++) {
    851 			const struct libusb_interface_descriptor *altsetting
    852 				= &iface->altsetting[altsetting_idx];
    853 			int ep_idx;
    854 
    855 			for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
    856 				const struct libusb_endpoint_descriptor *ep =
    857 					&altsetting->endpoint[ep_idx];
    858 				if (ep->bEndpointAddress == endpoint)
    859 					return ep;
    860 			}
    861 		}
    862 	}
    863 	return NULL;
    864 }
    865 
    866 /** \ingroup dev
    867  * Convenience function to retrieve the wMaxPacketSize value for a particular
    868  * endpoint in the active device configuration.
    869  *
    870  * This function was originally intended to be of assistance when setting up
    871  * isochronous transfers, but a design mistake resulted in this function
    872  * instead. It simply returns the wMaxPacketSize value without considering
    873  * its contents. If you're dealing with isochronous transfers, you probably
    874  * want libusb_get_max_iso_packet_size() instead.
    875  *
    876  * \param dev a device
    877  * \param endpoint address of the endpoint in question
    878  * \returns the wMaxPacketSize value
    879  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
    880  * \returns LIBUSB_ERROR_OTHER on other failure
    881  */
    882 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
    883 	unsigned char endpoint)
    884 {
    885 	struct libusb_config_descriptor *config;
    886 	const struct libusb_endpoint_descriptor *ep;
    887 	int r;
    888 
    889 	r = libusb_get_active_config_descriptor(dev, &config);
    890 	if (r < 0) {
    891 		usbi_err(DEVICE_CTX(dev),
    892 			"could not retrieve active config descriptor");
    893 		return LIBUSB_ERROR_OTHER;
    894 	}
    895 
    896 	ep = find_endpoint(config, endpoint);
    897 	if (!ep)
    898 		return LIBUSB_ERROR_NOT_FOUND;
    899 
    900 	r = ep->wMaxPacketSize;
    901 	libusb_free_config_descriptor(config);
    902 	return r;
    903 }
    904 
    905 /** \ingroup dev
    906  * Calculate the maximum packet size which a specific endpoint is capable is
    907  * sending or receiving in the duration of 1 microframe
    908  *
    909  * Only the active configuration is examined. The calculation is based on the
    910  * wMaxPacketSize field in the endpoint descriptor as described in section
    911  * 9.6.6 in the USB 2.0 specifications.
    912  *
    913  * If acting on an isochronous or interrupt endpoint, this function will
    914  * multiply the value found in bits 0:10 by the number of transactions per
    915  * microframe (determined by bits 11:12). Otherwise, this function just
    916  * returns the numeric value found in bits 0:10.
    917  *
    918  * This function is useful for setting up isochronous transfers, for example
    919  * you might pass the return value from this function to
    920  * libusb_set_iso_packet_lengths() in order to set the length field of every
    921  * isochronous packet in a transfer.
    922  *
    923  * Since v1.0.3.
    924  *
    925  * \param dev a device
    926  * \param endpoint address of the endpoint in question
    927  * \returns the maximum packet size which can be sent/received on this endpoint
    928  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
    929  * \returns LIBUSB_ERROR_OTHER on other failure
    930  */
    931 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
    932 	unsigned char endpoint)
    933 {
    934 	struct libusb_config_descriptor *config;
    935 	const struct libusb_endpoint_descriptor *ep;
    936 	enum libusb_transfer_type ep_type;
    937 	uint16_t val;
    938 	int r;
    939 
    940 	r = libusb_get_active_config_descriptor(dev, &config);
    941 	if (r < 0) {
    942 		usbi_err(DEVICE_CTX(dev),
    943 			"could not retrieve active config descriptor");
    944 		return LIBUSB_ERROR_OTHER;
    945 	}
    946 
    947 	ep = find_endpoint(config, endpoint);
    948 	if (!ep)
    949 		return LIBUSB_ERROR_NOT_FOUND;
    950 
    951 	val = ep->wMaxPacketSize;
    952 	ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
    953 	libusb_free_config_descriptor(config);
    954 
    955 	r = val & 0x07ff;
    956 	if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
    957 			|| ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
    958 		r *= (1 + ((val >> 11) & 3));
    959 	return r;
    960 }
    961 
    962 /** \ingroup dev
    963  * Increment the reference count of a device.
    964  * \param dev the device to reference
    965  * \returns the same device
    966  */
    967 DEFAULT_VISIBILITY
    968 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
    969 {
    970 	usbi_mutex_lock(&dev->lock);
    971 	dev->refcnt++;
    972 	usbi_mutex_unlock(&dev->lock);
    973 	return dev;
    974 }
    975 
    976 /** \ingroup dev
    977  * Decrement the reference count of a device. If the decrement operation
    978  * causes the reference count to reach zero, the device shall be destroyed.
    979  * \param dev the device to unreference
    980  */
    981 void API_EXPORTED libusb_unref_device(libusb_device *dev)
    982 {
    983 	int refcnt;
    984 
    985 	if (!dev)
    986 		return;
    987 
    988 	usbi_mutex_lock(&dev->lock);
    989 	refcnt = --dev->refcnt;
    990 	usbi_mutex_unlock(&dev->lock);
    991 
    992 	if (refcnt == 0) {
    993 		usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
    994 
    995 		libusb_unref_device(dev->parent_dev);
    996 
    997 		if (usbi_backend->destroy_device)
    998 			usbi_backend->destroy_device(dev);
    999 
   1000 		if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
   1001 			/* backend does not support hotplug */
   1002 			usbi_disconnect_device(dev);
   1003 		}
   1004 
   1005 		usbi_mutex_destroy(&dev->lock);
   1006 		free(dev);
   1007 	}
   1008 }
   1009 
   1010 /*
   1011  * Interrupt the iteration of the event handling thread, so that it picks
   1012  * up the new fd.
   1013  */
   1014 void usbi_fd_notification(struct libusb_context *ctx)
   1015 {
   1016 	unsigned char dummy = 1;
   1017 	ssize_t r;
   1018 
   1019 	if (ctx == NULL)
   1020 		return;
   1021 
   1022 	/* record that we are messing with poll fds */
   1023 	usbi_mutex_lock(&ctx->pollfd_modify_lock);
   1024 	ctx->pollfd_modify++;
   1025 	usbi_mutex_unlock(&ctx->pollfd_modify_lock);
   1026 
   1027 	/* write some data on control pipe to interrupt event handlers */
   1028 	r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
   1029 	if (r <= 0) {
   1030 		usbi_warn(ctx, "internal signalling write failed");
   1031 		usbi_mutex_lock(&ctx->pollfd_modify_lock);
   1032 		ctx->pollfd_modify--;
   1033 		usbi_mutex_unlock(&ctx->pollfd_modify_lock);
   1034 		return;
   1035 	}
   1036 
   1037 	/* take event handling lock */
   1038 	libusb_lock_events(ctx);
   1039 
   1040 	/* read the dummy data */
   1041 	r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
   1042 	if (r <= 0)
   1043 		usbi_warn(ctx, "internal signalling read failed");
   1044 
   1045 	/* we're done with modifying poll fds */
   1046 	usbi_mutex_lock(&ctx->pollfd_modify_lock);
   1047 	ctx->pollfd_modify--;
   1048 	usbi_mutex_unlock(&ctx->pollfd_modify_lock);
   1049 
   1050 	/* Release event handling lock and wake up event waiters */
   1051 	libusb_unlock_events(ctx);
   1052 }
   1053 
   1054 /** \ingroup dev
   1055  * Open a device and obtain a device handle. A handle allows you to perform
   1056  * I/O on the device in question.
   1057  *
   1058  * Internally, this function adds a reference to the device and makes it
   1059  * available to you through libusb_get_device(). This reference is removed
   1060  * during libusb_close().
   1061  *
   1062  * This is a non-blocking function; no requests are sent over the bus.
   1063  *
   1064  * \param dev the device to open
   1065  * \param handle output location for the returned device handle pointer. Only
   1066  * populated when the return code is 0.
   1067  * \returns 0 on success
   1068  * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
   1069  * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
   1070  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1071  * \returns another LIBUSB_ERROR code on other failure
   1072  */
   1073 int API_EXPORTED libusb_open(libusb_device *dev,
   1074 	libusb_device_handle **handle)
   1075 {
   1076 	struct libusb_context *ctx = DEVICE_CTX(dev);
   1077 	struct libusb_device_handle *_handle;
   1078 	size_t priv_size = usbi_backend->device_handle_priv_size;
   1079 	int r;
   1080 	usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
   1081 
   1082 	if (!dev->attached) {
   1083 		return LIBUSB_ERROR_NO_DEVICE;
   1084 	}
   1085 
   1086 	_handle = malloc(sizeof(*_handle) + priv_size);
   1087 	if (!_handle)
   1088 		return LIBUSB_ERROR_NO_MEM;
   1089 
   1090 	r = usbi_mutex_init(&_handle->lock, NULL);
   1091 	if (r) {
   1092 		free(_handle);
   1093 		return LIBUSB_ERROR_OTHER;
   1094 	}
   1095 
   1096 	_handle->dev = libusb_ref_device(dev);
   1097 	_handle->auto_detach_kernel_driver = 0;
   1098 	_handle->claimed_interfaces = 0;
   1099 	memset(&_handle->os_priv, 0, priv_size);
   1100 
   1101 	r = usbi_backend->open(_handle);
   1102 	if (r < 0) {
   1103 		usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
   1104 		libusb_unref_device(dev);
   1105 		usbi_mutex_destroy(&_handle->lock);
   1106 		free(_handle);
   1107 		return r;
   1108 	}
   1109 
   1110 	usbi_mutex_lock(&ctx->open_devs_lock);
   1111 	list_add(&_handle->list, &ctx->open_devs);
   1112 	usbi_mutex_unlock(&ctx->open_devs_lock);
   1113 	*handle = _handle;
   1114 
   1115 	/* At this point, we want to interrupt any existing event handlers so
   1116 	 * that they realise the addition of the new device's poll fd. One
   1117 	 * example when this is desirable is if the user is running a separate
   1118 	 * dedicated libusbx events handling thread, which is running with a long
   1119 	 * or infinite timeout. We want to interrupt that iteration of the loop,
   1120 	 * so that it picks up the new fd, and then continues. */
   1121 	usbi_fd_notification(ctx);
   1122 
   1123 	return 0;
   1124 }
   1125 
   1126 /** \ingroup dev
   1127  * Convenience function for finding a device with a particular
   1128  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
   1129  * for those scenarios where you are using libusbx to knock up a quick test
   1130  * application - it allows you to avoid calling libusb_get_device_list() and
   1131  * worrying about traversing/freeing the list.
   1132  *
   1133  * This function has limitations and is hence not intended for use in real
   1134  * applications: if multiple devices have the same IDs it will only
   1135  * give you the first one, etc.
   1136  *
   1137  * \param ctx the context to operate on, or NULL for the default context
   1138  * \param vendor_id the idVendor value to search for
   1139  * \param product_id the idProduct value to search for
   1140  * \returns a handle for the first found device, or NULL on error or if the
   1141  * device could not be found. */
   1142 DEFAULT_VISIBILITY
   1143 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
   1144 	libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
   1145 {
   1146 	struct libusb_device **devs;
   1147 	struct libusb_device *found = NULL;
   1148 	struct libusb_device *dev;
   1149 	struct libusb_device_handle *handle = NULL;
   1150 	size_t i = 0;
   1151 	int r;
   1152 
   1153 	if (libusb_get_device_list(ctx, &devs) < 0)
   1154 		return NULL;
   1155 
   1156 	while ((dev = devs[i++]) != NULL) {
   1157 		struct libusb_device_descriptor desc;
   1158 		r = libusb_get_device_descriptor(dev, &desc);
   1159 		if (r < 0)
   1160 			goto out;
   1161 		if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
   1162 			found = dev;
   1163 			break;
   1164 		}
   1165 	}
   1166 
   1167 	if (found) {
   1168 		r = libusb_open(found, &handle);
   1169 		if (r < 0)
   1170 			handle = NULL;
   1171 	}
   1172 
   1173 out:
   1174 	libusb_free_device_list(devs, 1);
   1175 	return handle;
   1176 }
   1177 
   1178 static void do_close(struct libusb_context *ctx,
   1179 	struct libusb_device_handle *dev_handle)
   1180 {
   1181 	struct usbi_transfer *itransfer;
   1182 	struct usbi_transfer *tmp;
   1183 
   1184 	libusb_lock_events(ctx);
   1185 
   1186 	/* remove any transfers in flight that are for this device */
   1187 	usbi_mutex_lock(&ctx->flying_transfers_lock);
   1188 
   1189 	/* safe iteration because transfers may be being deleted */
   1190 	list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
   1191 		struct libusb_transfer *transfer =
   1192 			USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1193 
   1194 		if (transfer->dev_handle != dev_handle)
   1195 			continue;
   1196 
   1197 		if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
   1198 			usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
   1199 
   1200 			if (itransfer->flags & USBI_TRANSFER_CANCELLING)
   1201 				usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
   1202 			else
   1203 				usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
   1204 		}
   1205 
   1206 		/* remove from the list of in-flight transfers and make sure
   1207 		 * we don't accidentally use the device handle in the future
   1208 		 * (or that such accesses will be easily caught and identified as a crash)
   1209 		 */
   1210 		usbi_mutex_lock(&itransfer->lock);
   1211 		list_del(&itransfer->list);
   1212 		transfer->dev_handle = NULL;
   1213 		usbi_mutex_unlock(&itransfer->lock);
   1214 
   1215 		/* it is up to the user to free up the actual transfer struct.  this is
   1216 		 * just making sure that we don't attempt to process the transfer after
   1217 		 * the device handle is invalid
   1218 		 */
   1219 		usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
   1220 			 transfer, dev_handle);
   1221 	}
   1222 	usbi_mutex_unlock(&ctx->flying_transfers_lock);
   1223 
   1224 	libusb_unlock_events(ctx);
   1225 
   1226 	usbi_mutex_lock(&ctx->open_devs_lock);
   1227 	list_del(&dev_handle->list);
   1228 	usbi_mutex_unlock(&ctx->open_devs_lock);
   1229 
   1230 	usbi_backend->close(dev_handle);
   1231 	libusb_unref_device(dev_handle->dev);
   1232 	usbi_mutex_destroy(&dev_handle->lock);
   1233 	free(dev_handle);
   1234 }
   1235 
   1236 /** \ingroup dev
   1237  * Close a device handle. Should be called on all open handles before your
   1238  * application exits.
   1239  *
   1240  * Internally, this function destroys the reference that was added by
   1241  * libusb_open() on the given device.
   1242  *
   1243  * This is a non-blocking function; no requests are sent over the bus.
   1244  *
   1245  * \param dev_handle the handle to close
   1246  */
   1247 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
   1248 {
   1249 	struct libusb_context *ctx;
   1250 	unsigned char dummy = 1;
   1251 	ssize_t r;
   1252 
   1253 	if (!dev_handle)
   1254 		return;
   1255 	usbi_dbg("");
   1256 
   1257 	ctx = HANDLE_CTX(dev_handle);
   1258 
   1259 	/* Similarly to libusb_open(), we want to interrupt all event handlers
   1260 	 * at this point. More importantly, we want to perform the actual close of
   1261 	 * the device while holding the event handling lock (preventing any other
   1262 	 * thread from doing event handling) because we will be removing a file
   1263 	 * descriptor from the polling loop. */
   1264 
   1265 	/* record that we are messing with poll fds */
   1266 	usbi_mutex_lock(&ctx->pollfd_modify_lock);
   1267 	ctx->pollfd_modify++;
   1268 	usbi_mutex_unlock(&ctx->pollfd_modify_lock);
   1269 
   1270 	/* write some data on control pipe to interrupt event handlers */
   1271 	r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
   1272 	if (r <= 0) {
   1273 		usbi_warn(ctx, "internal signalling write failed, closing anyway");
   1274 		do_close(ctx, dev_handle);
   1275 		usbi_mutex_lock(&ctx->pollfd_modify_lock);
   1276 		ctx->pollfd_modify--;
   1277 		usbi_mutex_unlock(&ctx->pollfd_modify_lock);
   1278 		return;
   1279 	}
   1280 
   1281 	/* take event handling lock */
   1282 	libusb_lock_events(ctx);
   1283 
   1284 	/* read the dummy data */
   1285 	r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
   1286 	if (r <= 0)
   1287 		usbi_warn(ctx, "internal signalling read failed, closing anyway");
   1288 
   1289 	/* Close the device */
   1290 	do_close(ctx, dev_handle);
   1291 
   1292 	/* we're done with modifying poll fds */
   1293 	usbi_mutex_lock(&ctx->pollfd_modify_lock);
   1294 	ctx->pollfd_modify--;
   1295 	usbi_mutex_unlock(&ctx->pollfd_modify_lock);
   1296 
   1297 	/* Release event handling lock and wake up event waiters */
   1298 	libusb_unlock_events(ctx);
   1299 }
   1300 
   1301 /** \ingroup dev
   1302  * Get the underlying device for a handle. This function does not modify
   1303  * the reference count of the returned device, so do not feel compelled to
   1304  * unreference it when you are done.
   1305  * \param dev_handle a device handle
   1306  * \returns the underlying device
   1307  */
   1308 DEFAULT_VISIBILITY
   1309 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
   1310 {
   1311 	return dev_handle->dev;
   1312 }
   1313 
   1314 /** \ingroup dev
   1315  * Determine the bConfigurationValue of the currently active configuration.
   1316  *
   1317  * You could formulate your own control request to obtain this information,
   1318  * but this function has the advantage that it may be able to retrieve the
   1319  * information from operating system caches (no I/O involved).
   1320  *
   1321  * If the OS does not cache this information, then this function will block
   1322  * while a control transfer is submitted to retrieve the information.
   1323  *
   1324  * This function will return a value of 0 in the <tt>config</tt> output
   1325  * parameter if the device is in unconfigured state.
   1326  *
   1327  * \param dev a device handle
   1328  * \param config output location for the bConfigurationValue of the active
   1329  * configuration (only valid for return code 0)
   1330  * \returns 0 on success
   1331  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1332  * \returns another LIBUSB_ERROR code on other failure
   1333  */
   1334 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
   1335 	int *config)
   1336 {
   1337 	int r = LIBUSB_ERROR_NOT_SUPPORTED;
   1338 
   1339 	usbi_dbg("");
   1340 	if (usbi_backend->get_configuration)
   1341 		r = usbi_backend->get_configuration(dev, config);
   1342 
   1343 	if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
   1344 		uint8_t tmp = 0;
   1345 		usbi_dbg("falling back to control message");
   1346 		r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
   1347 			LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
   1348 		if (r == 0) {
   1349 			usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
   1350 			r = LIBUSB_ERROR_IO;
   1351 		} else if (r == 1) {
   1352 			r = 0;
   1353 			*config = tmp;
   1354 		} else {
   1355 			usbi_dbg("control failed, error %d", r);
   1356 		}
   1357 	}
   1358 
   1359 	if (r == 0)
   1360 		usbi_dbg("active config %d", *config);
   1361 
   1362 	return r;
   1363 }
   1364 
   1365 /** \ingroup dev
   1366  * Set the active configuration for a device.
   1367  *
   1368  * The operating system may or may not have already set an active
   1369  * configuration on the device. It is up to your application to ensure the
   1370  * correct configuration is selected before you attempt to claim interfaces
   1371  * and perform other operations.
   1372  *
   1373  * If you call this function on a device already configured with the selected
   1374  * configuration, then this function will act as a lightweight device reset:
   1375  * it will issue a SET_CONFIGURATION request using the current configuration,
   1376  * causing most USB-related device state to be reset (altsetting reset to zero,
   1377  * endpoint halts cleared, toggles reset).
   1378  *
   1379  * You cannot change/reset configuration if your application has claimed
   1380  * interfaces. It is advised to set the desired configuration before claiming
   1381  * interfaces.
   1382  *
   1383  * Alternatively you can call libusb_release_interface() first. Note if you
   1384  * do things this way you must ensure that auto_detach_kernel_driver for
   1385  * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
   1386  * release the interface(s).
   1387  *
   1388  * You cannot change/reset configuration if other applications or drivers have
   1389  * claimed interfaces.
   1390  *
   1391  * A configuration value of -1 will put the device in unconfigured state.
   1392  * The USB specifications state that a configuration value of 0 does this,
   1393  * however buggy devices exist which actually have a configuration 0.
   1394  *
   1395  * You should always use this function rather than formulating your own
   1396  * SET_CONFIGURATION control request. This is because the underlying operating
   1397  * system needs to know when such changes happen.
   1398  *
   1399  * This is a blocking function.
   1400  *
   1401  * \param dev a device handle
   1402  * \param configuration the bConfigurationValue of the configuration you
   1403  * wish to activate, or -1 if you wish to put the device in unconfigured state
   1404  * \returns 0 on success
   1405  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
   1406  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
   1407  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1408  * \returns another LIBUSB_ERROR code on other failure
   1409  * \see libusb_set_auto_detach_kernel_driver()
   1410  */
   1411 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
   1412 	int configuration)
   1413 {
   1414 	usbi_dbg("configuration %d", configuration);
   1415 	return usbi_backend->set_configuration(dev, configuration);
   1416 }
   1417 
   1418 /** \ingroup dev
   1419  * Claim an interface on a given device handle. You must claim the interface
   1420  * you wish to use before you can perform I/O on any of its endpoints.
   1421  *
   1422  * It is legal to attempt to claim an already-claimed interface, in which
   1423  * case libusbx just returns 0 without doing anything.
   1424  *
   1425  * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
   1426  * will be detached if necessary, on failure the detach error is returned.
   1427  *
   1428  * Claiming of interfaces is a purely logical operation; it does not cause
   1429  * any requests to be sent over the bus. Interface claiming is used to
   1430  * instruct the underlying operating system that your application wishes
   1431  * to take ownership of the interface.
   1432  *
   1433  * This is a non-blocking function.
   1434  *
   1435  * \param dev a device handle
   1436  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
   1437  * wish to claim
   1438  * \returns 0 on success
   1439  * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
   1440  * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
   1441  * interface
   1442  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1443  * \returns a LIBUSB_ERROR code on other failure
   1444  * \see libusb_set_auto_detach_kernel_driver()
   1445  */
   1446 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
   1447 	int interface_number)
   1448 {
   1449 	int r = 0;
   1450 
   1451 	usbi_dbg("interface %d", interface_number);
   1452 	if (interface_number >= USB_MAXINTERFACES)
   1453 		return LIBUSB_ERROR_INVALID_PARAM;
   1454 
   1455 	if (!dev->dev->attached)
   1456 		return LIBUSB_ERROR_NO_DEVICE;
   1457 
   1458 	usbi_mutex_lock(&dev->lock);
   1459 	if (dev->claimed_interfaces & (1 << interface_number))
   1460 		goto out;
   1461 
   1462 	r = usbi_backend->claim_interface(dev, interface_number);
   1463 	if (r == 0)
   1464 		dev->claimed_interfaces |= 1 << interface_number;
   1465 
   1466 out:
   1467 	usbi_mutex_unlock(&dev->lock);
   1468 	return r;
   1469 }
   1470 
   1471 /** \ingroup dev
   1472  * Release an interface previously claimed with libusb_claim_interface(). You
   1473  * should release all claimed interfaces before closing a device handle.
   1474  *
   1475  * This is a blocking function. A SET_INTERFACE control request will be sent
   1476  * to the device, resetting interface state to the first alternate setting.
   1477  *
   1478  * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
   1479  * driver will be re-attached after releasing the interface.
   1480  *
   1481  * \param dev a device handle
   1482  * \param interface_number the <tt>bInterfaceNumber</tt> of the
   1483  * previously-claimed interface
   1484  * \returns 0 on success
   1485  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
   1486  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1487  * \returns another LIBUSB_ERROR code on other failure
   1488  * \see libusb_set_auto_detach_kernel_driver()
   1489  */
   1490 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
   1491 	int interface_number)
   1492 {
   1493 	int r;
   1494 
   1495 	usbi_dbg("interface %d", interface_number);
   1496 	if (interface_number >= USB_MAXINTERFACES)
   1497 		return LIBUSB_ERROR_INVALID_PARAM;
   1498 
   1499 	usbi_mutex_lock(&dev->lock);
   1500 	if (!(dev->claimed_interfaces & (1 << interface_number))) {
   1501 		r = LIBUSB_ERROR_NOT_FOUND;
   1502 		goto out;
   1503 	}
   1504 
   1505 	r = usbi_backend->release_interface(dev, interface_number);
   1506 	if (r == 0)
   1507 		dev->claimed_interfaces &= ~(1 << interface_number);
   1508 
   1509 out:
   1510 	usbi_mutex_unlock(&dev->lock);
   1511 	return r;
   1512 }
   1513 
   1514 /** \ingroup dev
   1515  * Activate an alternate setting for an interface. The interface must have
   1516  * been previously claimed with libusb_claim_interface().
   1517  *
   1518  * You should always use this function rather than formulating your own
   1519  * SET_INTERFACE control request. This is because the underlying operating
   1520  * system needs to know when such changes happen.
   1521  *
   1522  * This is a blocking function.
   1523  *
   1524  * \param dev a device handle
   1525  * \param interface_number the <tt>bInterfaceNumber</tt> of the
   1526  * previously-claimed interface
   1527  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
   1528  * setting to activate
   1529  * \returns 0 on success
   1530  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
   1531  * requested alternate setting does not exist
   1532  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1533  * \returns another LIBUSB_ERROR code on other failure
   1534  */
   1535 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
   1536 	int interface_number, int alternate_setting)
   1537 {
   1538 	usbi_dbg("interface %d altsetting %d",
   1539 		interface_number, alternate_setting);
   1540 	if (interface_number >= USB_MAXINTERFACES)
   1541 		return LIBUSB_ERROR_INVALID_PARAM;
   1542 
   1543 	usbi_mutex_lock(&dev->lock);
   1544 	if (!dev->dev->attached) {
   1545 		usbi_mutex_unlock(&dev->lock);
   1546 		return LIBUSB_ERROR_NO_DEVICE;
   1547 	}
   1548 
   1549 	if (!(dev->claimed_interfaces & (1 << interface_number))) {
   1550 		usbi_mutex_unlock(&dev->lock);
   1551 		return LIBUSB_ERROR_NOT_FOUND;
   1552 	}
   1553 	usbi_mutex_unlock(&dev->lock);
   1554 
   1555 	return usbi_backend->set_interface_altsetting(dev, interface_number,
   1556 		alternate_setting);
   1557 }
   1558 
   1559 /** \ingroup dev
   1560  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
   1561  * are unable to receive or transmit data until the halt condition is stalled.
   1562  *
   1563  * You should cancel all pending transfers before attempting to clear the halt
   1564  * condition.
   1565  *
   1566  * This is a blocking function.
   1567  *
   1568  * \param dev a device handle
   1569  * \param endpoint the endpoint to clear halt status
   1570  * \returns 0 on success
   1571  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
   1572  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1573  * \returns another LIBUSB_ERROR code on other failure
   1574  */
   1575 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
   1576 	unsigned char endpoint)
   1577 {
   1578 	usbi_dbg("endpoint %x", endpoint);
   1579 	if (!dev->dev->attached)
   1580 		return LIBUSB_ERROR_NO_DEVICE;
   1581 
   1582 	return usbi_backend->clear_halt(dev, endpoint);
   1583 }
   1584 
   1585 /** \ingroup dev
   1586  * Perform a USB port reset to reinitialize a device. The system will attempt
   1587  * to restore the previous configuration and alternate settings after the
   1588  * reset has completed.
   1589  *
   1590  * If the reset fails, the descriptors change, or the previous state cannot be
   1591  * restored, the device will appear to be disconnected and reconnected. This
   1592  * means that the device handle is no longer valid (you should close it) and
   1593  * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
   1594  * when this is the case.
   1595  *
   1596  * This is a blocking function which usually incurs a noticeable delay.
   1597  *
   1598  * \param dev a handle of the device to reset
   1599  * \returns 0 on success
   1600  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
   1601  * device has been disconnected
   1602  * \returns another LIBUSB_ERROR code on other failure
   1603  */
   1604 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
   1605 {
   1606 	usbi_dbg("");
   1607 	if (!dev->dev->attached)
   1608 		return LIBUSB_ERROR_NO_DEVICE;
   1609 
   1610 	return usbi_backend->reset_device(dev);
   1611 }
   1612 
   1613 /** \ingroup dev
   1614  * Determine if a kernel driver is active on an interface. If a kernel driver
   1615  * is active, you cannot claim the interface, and libusbx will be unable to
   1616  * perform I/O.
   1617  *
   1618  * This functionality is not available on Windows.
   1619  *
   1620  * \param dev a device handle
   1621  * \param interface_number the interface to check
   1622  * \returns 0 if no kernel driver is active
   1623  * \returns 1 if a kernel driver is active
   1624  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1625  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
   1626  * is not available
   1627  * \returns another LIBUSB_ERROR code on other failure
   1628  * \see libusb_detach_kernel_driver()
   1629  */
   1630 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
   1631 	int interface_number)
   1632 {
   1633 	usbi_dbg("interface %d", interface_number);
   1634 
   1635 	if (!dev->dev->attached)
   1636 		return LIBUSB_ERROR_NO_DEVICE;
   1637 
   1638 	if (usbi_backend->kernel_driver_active)
   1639 		return usbi_backend->kernel_driver_active(dev, interface_number);
   1640 	else
   1641 		return LIBUSB_ERROR_NOT_SUPPORTED;
   1642 }
   1643 
   1644 /** \ingroup dev
   1645  * Detach a kernel driver from an interface. If successful, you will then be
   1646  * able to claim the interface and perform I/O.
   1647  *
   1648  * This functionality is not available on Darwin or Windows.
   1649  *
   1650  * Note that libusbx itself also talks to the device through a special kernel
   1651  * driver, if this driver is already attached to the device, this call will
   1652  * not detach it and return LIBUSB_ERROR_NOT_FOUND.
   1653  *
   1654  * \param dev a device handle
   1655  * \param interface_number the interface to detach the driver from
   1656  * \returns 0 on success
   1657  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
   1658  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
   1659  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1660  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
   1661  * is not available
   1662  * \returns another LIBUSB_ERROR code on other failure
   1663  * \see libusb_kernel_driver_active()
   1664  */
   1665 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
   1666 	int interface_number)
   1667 {
   1668 	usbi_dbg("interface %d", interface_number);
   1669 
   1670 	if (!dev->dev->attached)
   1671 		return LIBUSB_ERROR_NO_DEVICE;
   1672 
   1673 	if (usbi_backend->detach_kernel_driver)
   1674 		return usbi_backend->detach_kernel_driver(dev, interface_number);
   1675 	else
   1676 		return LIBUSB_ERROR_NOT_SUPPORTED;
   1677 }
   1678 
   1679 /** \ingroup dev
   1680  * Re-attach an interface's kernel driver, which was previously detached
   1681  * using libusb_detach_kernel_driver(). This call is only effective on
   1682  * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
   1683  *
   1684  * This functionality is not available on Darwin or Windows.
   1685  *
   1686  * \param dev a device handle
   1687  * \param interface_number the interface to attach the driver from
   1688  * \returns 0 on success
   1689  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
   1690  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
   1691  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
   1692  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
   1693  * is not available
   1694  * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
   1695  * interface is claimed by a program or driver
   1696  * \returns another LIBUSB_ERROR code on other failure
   1697  * \see libusb_kernel_driver_active()
   1698  */
   1699 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
   1700 	int interface_number)
   1701 {
   1702 	usbi_dbg("interface %d", interface_number);
   1703 
   1704 	if (!dev->dev->attached)
   1705 		return LIBUSB_ERROR_NO_DEVICE;
   1706 
   1707 	if (usbi_backend->attach_kernel_driver)
   1708 		return usbi_backend->attach_kernel_driver(dev, interface_number);
   1709 	else
   1710 		return LIBUSB_ERROR_NOT_SUPPORTED;
   1711 }
   1712 
   1713 /** \ingroup dev
   1714  * Enable/disable libusbx's automatic kernel driver detachment. When this is
   1715  * enabled libusbx will automatically detach the kernel driver on an interface
   1716  * when claiming the interface, and attach it when releasing the interface.
   1717  *
   1718  * Automatic kernel driver detachment is disabled on newly opened device
   1719  * handles by default.
   1720  *
   1721  * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
   1722  * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusbx will
   1723  * continue as if this function was never called.
   1724  *
   1725  * \param dev a device handle
   1726  * \param enable whether to enable or disable auto kernel driver detachment
   1727  *
   1728  * \returns LIBUSB_SUCCESS on success
   1729  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
   1730  * is not available
   1731  * \see libusb_claim_interface()
   1732  * \see libusb_release_interface()
   1733  * \see libusb_set_configuration()
   1734  */
   1735 int API_EXPORTED libusb_set_auto_detach_kernel_driver(
   1736 	libusb_device_handle *dev, int enable)
   1737 {
   1738 	if (!(usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
   1739 		return LIBUSB_ERROR_NOT_SUPPORTED;
   1740 
   1741 	dev->auto_detach_kernel_driver = enable;
   1742 	return LIBUSB_SUCCESS;
   1743 }
   1744 
   1745 /** \ingroup lib
   1746  * Set log message verbosity.
   1747  *
   1748  * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
   1749  * printed. If you choose to increase the message verbosity level, ensure
   1750  * that your application does not close the stdout/stderr file descriptors.
   1751  *
   1752  * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusbx is conservative
   1753  * with its message logging and most of the time, will only log messages that
   1754  * explain error conditions and other oddities. This will help you debug
   1755  * your software.
   1756  *
   1757  * If the LIBUSB_DEBUG environment variable was set when libusbx was
   1758  * initialized, this function does nothing: the message verbosity is fixed
   1759  * to the value in the environment variable.
   1760  *
   1761  * If libusbx was compiled without any message logging, this function does
   1762  * nothing: you'll never get any messages.
   1763  *
   1764  * If libusbx was compiled with verbose debug message logging, this function
   1765  * does nothing: you'll always get messages from all levels.
   1766  *
   1767  * \param ctx the context to operate on, or NULL for the default context
   1768  * \param level debug level to set
   1769  */
   1770 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
   1771 {
   1772 	USBI_GET_CONTEXT(ctx);
   1773 	if (!ctx->debug_fixed)
   1774 		ctx->debug = level;
   1775 }
   1776 
   1777 /** \ingroup lib
   1778  * Initialize libusb. This function must be called before calling any other
   1779  * libusbx function.
   1780  *
   1781  * If you do not provide an output location for a context pointer, a default
   1782  * context will be created. If there was already a default context, it will
   1783  * be reused (and nothing will be initialized/reinitialized).
   1784  *
   1785  * \param context Optional output location for context pointer.
   1786  * Only valid on return code 0.
   1787  * \returns 0 on success, or a LIBUSB_ERROR code on failure
   1788  * \see contexts
   1789  */
   1790 int API_EXPORTED libusb_init(libusb_context **context)
   1791 {
   1792 	struct libusb_device *dev, *next;
   1793 	char *dbg = getenv("LIBUSB_DEBUG");
   1794 	struct libusb_context *ctx;
   1795 	static int first_init = 1;
   1796 	int r = 0;
   1797 
   1798 	usbi_mutex_static_lock(&default_context_lock);
   1799 
   1800 	if (!timestamp_origin.tv_sec) {
   1801 		usbi_gettimeofday(&timestamp_origin, NULL);
   1802 	}
   1803 
   1804 	if (!context && usbi_default_context) {
   1805 		usbi_dbg("reusing default context");
   1806 		default_context_refcnt++;
   1807 		usbi_mutex_static_unlock(&default_context_lock);
   1808 		return 0;
   1809 	}
   1810 
   1811 	ctx = calloc(1, sizeof(*ctx));
   1812 	if (!ctx) {
   1813 		r = LIBUSB_ERROR_NO_MEM;
   1814 		goto err_unlock;
   1815 	}
   1816 
   1817 #ifdef ENABLE_DEBUG_LOGGING
   1818 	ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
   1819 #endif
   1820 
   1821 	if (dbg) {
   1822 		ctx->debug = atoi(dbg);
   1823 		if (ctx->debug)
   1824 			ctx->debug_fixed = 1;
   1825 	}
   1826 
   1827 	/* default context should be initialized before calling usbi_dbg */
   1828 	if (!usbi_default_context) {
   1829 		usbi_default_context = ctx;
   1830 		default_context_refcnt++;
   1831 		usbi_dbg("created default context");
   1832 	}
   1833 
   1834 	usbi_dbg("libusbx v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
   1835 		libusb_version_internal.micro, libusb_version_internal.nano);
   1836 
   1837 	usbi_mutex_init(&ctx->usb_devs_lock, NULL);
   1838 	usbi_mutex_init(&ctx->open_devs_lock, NULL);
   1839 	usbi_mutex_init(&ctx->hotplug_cbs_lock, NULL);
   1840 	list_init(&ctx->usb_devs);
   1841 	list_init(&ctx->open_devs);
   1842 	list_init(&ctx->hotplug_cbs);
   1843 
   1844 	usbi_mutex_static_lock(&active_contexts_lock);
   1845 	if (first_init) {
   1846 		first_init = 0;
   1847 		list_init (&active_contexts_list);
   1848 	}
   1849 	list_add (&ctx->list, &active_contexts_list);
   1850 	usbi_mutex_static_unlock(&active_contexts_lock);
   1851 
   1852 	if (usbi_backend->init) {
   1853 		r = usbi_backend->init(ctx);
   1854 		if (r)
   1855 			goto err_free_ctx;
   1856 	}
   1857 
   1858 	r = usbi_io_init(ctx);
   1859 	if (r < 0)
   1860 		goto err_backend_exit;
   1861 
   1862 	usbi_mutex_static_unlock(&default_context_lock);
   1863 
   1864 	if (context)
   1865 		*context = ctx;
   1866 
   1867 	return 0;
   1868 
   1869 err_backend_exit:
   1870 	if (usbi_backend->exit)
   1871 		usbi_backend->exit();
   1872 err_free_ctx:
   1873 	if (ctx == usbi_default_context)
   1874 		usbi_default_context = NULL;
   1875 
   1876 	usbi_mutex_destroy(&ctx->open_devs_lock);
   1877 	usbi_mutex_destroy(&ctx->usb_devs_lock);
   1878 	usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
   1879 
   1880 	usbi_mutex_static_lock(&active_contexts_lock);
   1881 	list_del (&ctx->list);
   1882 	usbi_mutex_static_unlock(&active_contexts_lock);
   1883 
   1884 	usbi_mutex_lock(&ctx->usb_devs_lock);
   1885 	list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
   1886 		list_del(&dev->list);
   1887 		libusb_unref_device(dev);
   1888 	}
   1889 	usbi_mutex_unlock(&ctx->usb_devs_lock);
   1890 
   1891 	free(ctx);
   1892 err_unlock:
   1893 	usbi_mutex_static_unlock(&default_context_lock);
   1894 	return r;
   1895 }
   1896 
   1897 /** \ingroup lib
   1898  * Deinitialize libusb. Should be called after closing all open devices and
   1899  * before your application terminates.
   1900  * \param ctx the context to deinitialize, or NULL for the default context
   1901  */
   1902 void API_EXPORTED libusb_exit(struct libusb_context *ctx)
   1903 {
   1904 	struct libusb_device *dev, *next;
   1905 
   1906 	usbi_dbg("");
   1907 	USBI_GET_CONTEXT(ctx);
   1908 
   1909 	/* if working with default context, only actually do the deinitialization
   1910 	 * if we're the last user */
   1911 	usbi_mutex_static_lock(&default_context_lock);
   1912 	if (ctx == usbi_default_context) {
   1913 		if (--default_context_refcnt > 0) {
   1914 			usbi_dbg("not destroying default context");
   1915 			usbi_mutex_static_unlock(&default_context_lock);
   1916 			return;
   1917 		}
   1918 		usbi_dbg("destroying default context");
   1919 		usbi_default_context = NULL;
   1920 	}
   1921 	usbi_mutex_static_unlock(&default_context_lock);
   1922 
   1923 	usbi_mutex_static_lock(&active_contexts_lock);
   1924 	list_del (&ctx->list);
   1925 	usbi_mutex_static_unlock(&active_contexts_lock);
   1926 
   1927 	if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
   1928 		usbi_hotplug_deregister_all(ctx);
   1929 		usbi_mutex_lock(&ctx->usb_devs_lock);
   1930 		list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
   1931 			list_del(&dev->list);
   1932 			libusb_unref_device(dev);
   1933 		}
   1934 		usbi_mutex_unlock(&ctx->usb_devs_lock);
   1935 	}
   1936 
   1937 	/* a few sanity checks. don't bother with locking because unless
   1938 	 * there is an application bug, nobody will be accessing these. */
   1939 	if (!list_empty(&ctx->usb_devs))
   1940 		usbi_warn(ctx, "some libusb_devices were leaked");
   1941 	if (!list_empty(&ctx->open_devs))
   1942 		usbi_warn(ctx, "application left some devices open");
   1943 
   1944 	usbi_io_exit(ctx);
   1945 	if (usbi_backend->exit)
   1946 		usbi_backend->exit();
   1947 
   1948 	usbi_mutex_destroy(&ctx->open_devs_lock);
   1949 	usbi_mutex_destroy(&ctx->usb_devs_lock);
   1950 	usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
   1951 	free(ctx);
   1952 }
   1953 
   1954 /** \ingroup misc
   1955  * Check at runtime if the loaded library has a given capability.
   1956  * This call should be performed after \ref libusb_init(), to ensure the
   1957  * backend has updated its capability set.
   1958  *
   1959  * \param capability the \ref libusb_capability to check for
   1960  * \returns nonzero if the running library has the capability, 0 otherwise
   1961  */
   1962 int API_EXPORTED libusb_has_capability(uint32_t capability)
   1963 {
   1964 	switch (capability) {
   1965 	case LIBUSB_CAP_HAS_CAPABILITY:
   1966 		return 1;
   1967 	case LIBUSB_CAP_HAS_HOTPLUG:
   1968 		return !(usbi_backend->get_device_list);
   1969 	case LIBUSB_CAP_HAS_HID_ACCESS:
   1970 		return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS);
   1971 	case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
   1972 		return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
   1973 	}
   1974 	return 0;
   1975 }
   1976 
   1977 /* this is defined in libusbi.h if needed */
   1978 #ifdef LIBUSB_GETTIMEOFDAY_WIN32
   1979 /*
   1980  * gettimeofday
   1981  * Implementation according to:
   1982  * The Open Group Base Specifications Issue 6
   1983  * IEEE Std 1003.1, 2004 Edition
   1984  */
   1985 
   1986 /*
   1987  *  THIS SOFTWARE IS NOT COPYRIGHTED
   1988  *
   1989  *  This source code is offered for use in the public domain. You may
   1990  *  use, modify or distribute it freely.
   1991  *
   1992  *  This code is distributed in the hope that it will be useful but
   1993  *  WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
   1994  *  DISCLAIMED. This includes but is not limited to warranties of
   1995  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
   1996  *
   1997  *  Contributed by:
   1998  *  Danny Smith <dannysmith (at) users.sourceforge.net>
   1999  */
   2000 
   2001 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
   2002 #define _W32_FT_OFFSET (116444736000000000)
   2003 
   2004 int usbi_gettimeofday(struct timeval *tp, void *tzp)
   2005 {
   2006 	union {
   2007 		unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
   2008 		FILETIME ft;
   2009 	} _now;
   2010 	UNUSED(tzp);
   2011 
   2012 	if(tp) {
   2013 #if defined(OS_WINCE)
   2014 		SYSTEMTIME st;
   2015 		GetSystemTime(&st);
   2016 		SystemTimeToFileTime(&st, &_now.ft);
   2017 #else
   2018 		GetSystemTimeAsFileTime (&_now.ft);
   2019 #endif
   2020 		tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
   2021 		tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
   2022 	}
   2023 	/* Always return 0 as per Open Group Base Specifications Issue 6.
   2024 	   Do not set errno on error.  */
   2025 	return 0;
   2026 }
   2027 #endif
   2028 
   2029 static void usbi_log_str(struct libusb_context *ctx, const char * str)
   2030 {
   2031 	UNUSED(ctx);
   2032 	fputs(str, stderr);
   2033 }
   2034 
   2035 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
   2036 	const char *function, const char *format, va_list args)
   2037 {
   2038 	const char *prefix = "";
   2039 	char buf[USBI_MAX_LOG_LEN];
   2040 	struct timeval now;
   2041 	int global_debug, header_len, text_len;
   2042 	static int has_debug_header_been_displayed = 0;
   2043 
   2044 #ifdef ENABLE_DEBUG_LOGGING
   2045 	global_debug = 1;
   2046 	UNUSED(ctx);
   2047 #else
   2048 	USBI_GET_CONTEXT(ctx);
   2049 	if (ctx == NULL)
   2050 		return;
   2051 	global_debug = (ctx->debug == LIBUSB_LOG_LEVEL_DEBUG);
   2052 	if (!ctx->debug)
   2053 		return;
   2054 	if (level == LIBUSB_LOG_LEVEL_WARNING && ctx->debug < LIBUSB_LOG_LEVEL_WARNING)
   2055 		return;
   2056 	if (level == LIBUSB_LOG_LEVEL_INFO && ctx->debug < LIBUSB_LOG_LEVEL_INFO)
   2057 		return;
   2058 	if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx->debug < LIBUSB_LOG_LEVEL_DEBUG)
   2059 		return;
   2060 #endif
   2061 
   2062 #ifdef __ANDROID__
   2063 	int prio;
   2064 	switch (level) {
   2065 	case LOG_LEVEL_INFO:
   2066 		prio = ANDROID_LOG_INFO;
   2067 		break;
   2068 	case LOG_LEVEL_WARNING:
   2069 		prio = ANDROID_LOG_WARN;
   2070 		break;
   2071 	case LOG_LEVEL_ERROR:
   2072 		prio = ANDROID_LOG_ERROR;
   2073 		break;
   2074 	case LOG_LEVEL_DEBUG:
   2075 		prio = ANDROID_LOG_DEBUG;
   2076 		break;
   2077 	default:
   2078 		prio = ANDROID_LOG_UNKNOWN;
   2079 		break;
   2080 	}
   2081 
   2082 	__android_log_vprint(prio, "LibUsb", format, args);
   2083 #else
   2084 	usbi_gettimeofday(&now, NULL);
   2085 	if ((global_debug) && (!has_debug_header_been_displayed)) {
   2086 		has_debug_header_been_displayed = 1;
   2087 		usbi_log_str(ctx, "[timestamp] [threadID] facility level [function call] <message>\n");
   2088 		usbi_log_str(ctx, "--------------------------------------------------------------------------------\n");
   2089 	}
   2090 	if (now.tv_usec < timestamp_origin.tv_usec) {
   2091 		now.tv_sec--;
   2092 		now.tv_usec += 1000000;
   2093 	}
   2094 	now.tv_sec -= timestamp_origin.tv_sec;
   2095 	now.tv_usec -= timestamp_origin.tv_usec;
   2096 
   2097 	switch (level) {
   2098 	case LIBUSB_LOG_LEVEL_INFO:
   2099 		prefix = "info";
   2100 		break;
   2101 	case LIBUSB_LOG_LEVEL_WARNING:
   2102 		prefix = "warning";
   2103 		break;
   2104 	case LIBUSB_LOG_LEVEL_ERROR:
   2105 		prefix = "error";
   2106 		break;
   2107 	case LIBUSB_LOG_LEVEL_DEBUG:
   2108 		prefix = "debug";
   2109 		break;
   2110 	case LIBUSB_LOG_LEVEL_NONE:
   2111 		break;
   2112 	default:
   2113 		prefix = "unknown";
   2114 		break;
   2115 	}
   2116 
   2117 	if (global_debug) {
   2118 		header_len = snprintf(buf, sizeof(buf),
   2119 			"[%2d.%06d] [%08x] libusbx: %s [%s] ",
   2120 			(int)now.tv_sec, (int)now.tv_usec, usbi_get_tid(), prefix, function);
   2121 	} else {
   2122 		header_len = snprintf(buf, sizeof(buf),
   2123 			"libusbx: %s [%s] ", prefix, function);
   2124 	}
   2125 
   2126 	if (header_len < 0 || header_len >= sizeof(buf)) {
   2127 		/* Somehow snprintf failed to write to the buffer,
   2128 		 * remove the header so something useful is output. */
   2129 		header_len = 0;
   2130 	}
   2131 	/* Make sure buffer is NUL terminated */
   2132 	buf[header_len] = '\0';
   2133 	text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
   2134 		format, args);
   2135 	if (text_len < 0 || text_len + header_len >= sizeof(buf)) {
   2136 		/* Truncated log output. On some platforms a -1 return value means
   2137 		 * that the output was truncated. */
   2138 		text_len = sizeof(buf) - header_len;
   2139 	}
   2140 	if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
   2141 		/* Need to truncate the text slightly to fit on the terminator. */
   2142 		text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
   2143 	}
   2144 	strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
   2145 
   2146 	usbi_log_str(ctx, buf);
   2147 #endif
   2148 }
   2149 
   2150 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
   2151 	const char *function, const char *format, ...)
   2152 {
   2153 	va_list args;
   2154 
   2155 	va_start (args, format);
   2156 	usbi_log_v(ctx, level, function, format, args);
   2157 	va_end (args);
   2158 }
   2159 
   2160 /** \ingroup misc
   2161  * Returns a constant NULL-terminated string with the ASCII name of a libusbx
   2162  * error or transfer status code. The caller must not free() the returned
   2163  * string.
   2164  *
   2165  * \param error_code The \ref libusb_error or libusb_transfer_status code to
   2166  * return the name of.
   2167  * \returns The error name, or the string **UNKNOWN** if the value of
   2168  * error_code is not a known error / status code.
   2169  */
   2170 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
   2171 {
   2172 	switch (error_code) {
   2173 	case LIBUSB_ERROR_IO:
   2174 		return "LIBUSB_ERROR_IO";
   2175 	case LIBUSB_ERROR_INVALID_PARAM:
   2176 		return "LIBUSB_ERROR_INVALID_PARAM";
   2177 	case LIBUSB_ERROR_ACCESS:
   2178 		return "LIBUSB_ERROR_ACCESS";
   2179 	case LIBUSB_ERROR_NO_DEVICE:
   2180 		return "LIBUSB_ERROR_NO_DEVICE";
   2181 	case LIBUSB_ERROR_NOT_FOUND:
   2182 		return "LIBUSB_ERROR_NOT_FOUND";
   2183 	case LIBUSB_ERROR_BUSY:
   2184 		return "LIBUSB_ERROR_BUSY";
   2185 	case LIBUSB_ERROR_TIMEOUT:
   2186 		return "LIBUSB_ERROR_TIMEOUT";
   2187 	case LIBUSB_ERROR_OVERFLOW:
   2188 		return "LIBUSB_ERROR_OVERFLOW";
   2189 	case LIBUSB_ERROR_PIPE:
   2190 		return "LIBUSB_ERROR_PIPE";
   2191 	case LIBUSB_ERROR_INTERRUPTED:
   2192 		return "LIBUSB_ERROR_INTERRUPTED";
   2193 	case LIBUSB_ERROR_NO_MEM:
   2194 		return "LIBUSB_ERROR_NO_MEM";
   2195 	case LIBUSB_ERROR_NOT_SUPPORTED:
   2196 		return "LIBUSB_ERROR_NOT_SUPPORTED";
   2197 	case LIBUSB_ERROR_OTHER:
   2198 		return "LIBUSB_ERROR_OTHER";
   2199 
   2200 	case LIBUSB_TRANSFER_ERROR:
   2201 		return "LIBUSB_TRANSFER_ERROR";
   2202 	case LIBUSB_TRANSFER_TIMED_OUT:
   2203 		return "LIBUSB_TRANSFER_TIMED_OUT";
   2204 	case LIBUSB_TRANSFER_CANCELLED:
   2205 		return "LIBUSB_TRANSFER_CANCELLED";
   2206 	case LIBUSB_TRANSFER_STALL:
   2207 		return "LIBUSB_TRANSFER_STALL";
   2208 	case LIBUSB_TRANSFER_NO_DEVICE:
   2209 		return "LIBUSB_TRANSFER_NO_DEVICE";
   2210 	case LIBUSB_TRANSFER_OVERFLOW:
   2211 		return "LIBUSB_TRANSFER_OVERFLOW";
   2212 
   2213 	case 0:
   2214 		return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
   2215 	default:
   2216 		return "**UNKNOWN**";
   2217 	}
   2218 }
   2219 
   2220 /** \ingroup misc
   2221  * Returns a pointer to const struct libusb_version with the version
   2222  * (major, minor, micro, nano and rc) of the running library.
   2223  */
   2224 DEFAULT_VISIBILITY
   2225 const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
   2226 {
   2227 	return &libusb_version_internal;
   2228 }
   2229