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