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