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