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