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