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