Pause event handling while opening and closing devices
[platform/upstream/libusb.git] / libusb / core.c
1 /*
2  * Core functions for libusb
3  * Copyright (C) 2007-2008 Daniel Drake <dsd@gentoo.org>
4  * Copyright (c) 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 <poll.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31
32 #include "libusb.h"
33 #include "libusbi.h"
34
35 #ifdef OS_LINUX
36 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
37 #else
38 #error "Unsupported OS"
39 #endif
40
41 struct libusb_context *usbi_default_context = NULL;
42 static pthread_mutex_t default_context_lock = PTHREAD_MUTEX_INITIALIZER;
43
44 /**
45  * \mainpage libusb-1.0 API Reference
46  *
47  * \section intro Introduction
48  *
49  * libusb is an open source library that allows you to communicate with USB
50  * devices from userspace. For more info, see the
51  * <a href="http://libusb.sourceforge.net">libusb homepage</a>.
52  *
53  * This documentation is aimed at application developers wishing to
54  * communicate with USB peripherals from their own software. After reviewing
55  * this documentation, feedback and questions can be sent to the
56  * <a href="http://sourceforge.net/mail/?group_id=1674">libusb-devel mailing
57  * list</a>.
58  *
59  * This documentation assumes knowledge of how to operate USB devices from
60  * a software standpoint (descriptors, configurations, interfaces, endpoints,
61  * control/bulk/interrupt/isochronous transfers, etc). Full information
62  * can be found in the <a href="http://www.usb.org/developers/docs/">USB 2.0
63  * Specification</a> which is available for free download. You can probably
64  * find less verbose introductions by searching the web.
65  *
66  * \section features Library features
67  *
68  * - All transfer types supported (control/bulk/interrupt/isochronous)
69  * - 2 transfer interfaces:
70  *    -# Synchronous (simple)
71  *    -# Asynchronous (more complicated, but more powerful)
72  * - Thread safe (although the asynchronous interface means that you
73  *   usually won't need to thread)
74  * - Lightweight with lean API
75  * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
76  *
77  * \section gettingstarted Getting Started
78  *
79  * To begin reading the API documentation, start with the Modules page which
80  * links to the different categories of libusb's functionality.
81  *
82  * One decision you will have to make is whether to use the synchronous
83  * or the asynchronous data transfer interface. The \ref io documentation
84  * provides some insight into this topic.
85  *
86  * Some example programs can be found in the libusb source distribution under
87  * the "examples" subdirectory. The libusb homepage includes a list of
88  * real-life project examples which use libusb.
89  *
90  * \section errorhandling Error handling
91  *
92  * libusb functions typically return 0 on success or a negative error code
93  * on failure. These negative error codes relate to LIBUSB_ERROR constants
94  * which are listed on the \ref misc "miscellaneous" documentation page.
95  *
96  * \section msglog Debug message logging
97  *
98  * libusb does not log any messages by default. Your application is therefore
99  * free to close stdout/stderr and those descriptors may be reused without
100  * worry.
101  *
102  * The libusb_set_debug() function can be used to enable stdout/stderr logging
103  * of certain messages. Under standard configuration, libusb doesn't really
104  * log much at all, so you are advised to use this function to enable all
105  * error/warning/informational messages. It will help you debug problems with
106  * your software.
107  *
108  * The logged messages are unstructured. There is no one-to-one correspondence
109  * between messages being logged and success or failure return codes from
110  * libusb functions. There is no format to the messages, so you should not
111  * try to capture or parse them. They are not and will not be localized.
112  * These messages are not suitable for being passed to your application user;
113  * instead, you should interpret the error codes returned from libusb functions
114  * and provide appropriate notification to the user. The messages are simply
115  * there to aid you as a programmer, and if you're confused because you're
116  * getting a strange error code from a libusb function, enabling message
117  * logging may give you a suitable explanation.
118  *
119  * The LIBUSB_DEBUG environment variable can be used to enable message logging
120  * at run-time. This environment variable should be set to a number, which is
121  * interpreted the same as the libusb_set_debug() parameter. When this
122  * environment variable is set, the message logging verbosity level is fixed
123  * and libusb_set_debug() effectively does nothing.
124  *
125  * libusb can be compiled without any logging functions, useful for embedded
126  * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
127  * variable have no effects.
128  *
129  * libusb can also be compiled with verbose debugging messages. When the
130  * library is compiled in this way, all messages of all verbosities are always
131  * logged.  libusb_set_debug() and the LIBUSB_DEBUG environment variable have
132  * no effects.
133  *
134  * \section remarks Other remarks
135  *
136  * libusb does have imperfections. The \ref caveats "caveats" page attempts
137  * to document these.
138  */
139
140 /**
141  * \page caveats Caveats
142  *
143  * \section devresets Device resets
144  *
145  * The libusb_reset_device() function allows you to reset a device. If your
146  * program has to call such a function, it should obviously be aware that
147  * the reset will cause device state to change (e.g. register values may be
148  * reset).
149  *
150  * The problem is that any other program could reset the device your program
151  * is working with, at any time. libusb does not offer a mechanism to inform
152  * you when this has happened, so if someone else resets your device it will
153  * not be clear to your own program why the device state has changed.
154  *
155  * Ultimately, this is a limitation of writing drivers in userspace.
156  * Separation from the USB stack in the underlying kernel makes it difficult
157  * for the operating system to deliver such notifications to your program.
158  * The Linux kernel USB stack allows such reset notifications to be delivered
159  * to in-kernel USB drivers, but it is not clear how such notifications could
160  * be delivered to second-class drivers that live in userspace.
161  *
162  * \section blockonly Blocking-only functionality
163  *
164  * The functionality listed below is only available through synchronous,
165  * blocking functions. There are no asynchronous/non-blocking alternatives,
166  * and no clear ways of implementing these.
167  *
168  * - Configuration activation (libusb_set_configuration())
169  * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
170  * - Releasing of interfaces (libusb_release_interface())
171  * - Clearing of halt/stall condition (libusb_clear_halt())
172  * - Device resets (libusb_reset_device())
173  *
174  * \section nohotplug No hotplugging
175  *
176  * libusb-1.0 lacks functionality for providing notifications of when devices
177  * are added or removed. This functionality is planned to be implemented
178  * for libusb-1.1.
179  *
180  * That said, there is basic disconnection handling for open device handles:
181  *  - If there are ongoing transfers, libusb's handle_events loop will detect
182  *    disconnections and complete ongoing transfers with the
183  *    LIBUSB_TRANSFER_NO_DEVICE status code.
184  *  - Many functions such as libusb_set_configuration() return the special
185  *    LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected.
186  *
187  * \section configsel Configuration selection and handling
188  *
189  * When libusb presents a device handle to an application, there is a chance
190  * that the corresponding device may be in unconfigured state. For devices
191  * with multiple configurations, there is also a chance that the configuration
192  * currently selected is not the one that the application wants to use.
193  *
194  * The obvious solution is to add a call to libusb_set_configuration() early
195  * on during your device initialization routines, but there are caveats to
196  * be aware of:
197  * -# If the device is already in the desired configuration, calling
198  *    libusb_set_configuration() using the same configuration value will cause
199  *    a lightweight device reset. This may not be desirable behaviour.
200  * -# libusb will be unable to change configuration if the device is in
201  *    another configuration and other programs or drivers have claimed
202  *    interfaces under that configuration.
203  * -# In the case where the desired configuration is already active, libusb
204  *    may not even be able to perform a lightweight device reset. For example,
205  *    take my USB keyboard with fingerprint reader: I'm interested in driving
206  *    the fingerprint reader interface through libusb, but the kernel's
207  *    USB-HID driver will almost always have claimed the keyboard interface.
208  *    Because the kernel has claimed an interface, it is not even possible to
209  *    perform the lightweight device reset, so libusb_set_configuration() will
210  *    fail. (Luckily the device in question only has a single configuration.)
211  *
212  * One solution to some of the above problems is to consider the currently
213  * active configuration. If the configuration we want is already active, then
214  * we don't have to select any configuration:
215 \code
216 cfg = libusb_get_configuration(dev);
217 if (cfg != desired)
218         libusb_set_configuration(dev, desired);
219 \endcode
220  *
221  * This is probably suitable for most scenarios, but is inherently racy:
222  * another application or driver may change the selected configuration
223  * <em>after</em> the libusb_get_configuration() call.
224  *
225  * Even in cases where libusb_set_configuration() succeeds, consider that other
226  * applications or drivers may change configuration after your application
227  * calls libusb_set_configuration().
228  *
229  * One possible way to lock your device into a specific configuration is as
230  * follows:
231  * -# Set the desired configuration (or use the logic above to realise that
232  *    it is already in the desired configuration)
233  * -# Claim the interface that you wish to use
234  * -# Check that the currently active configuration is the one that you want
235  *    to use.
236  *
237  * The above method works because once an interface is claimed, no application
238  * or driver is able to select another configuration.
239  */
240
241 /**
242  * \page contexts Contexts
243  *
244  * It is possible that libusb may be used simultaneously from two independent
245  * libraries linked into the same executable. For example, if your application
246  * has a plugin-like system which allows the user to dynamically load a range
247  * of modules into your program, it is feasible that two independently
248  * developed modules may both use libusb.
249  *
250  * libusb is written to allow for these multiple user scenarios. The two
251  * "instances" of libusb will not interfere: libusb_set_debug() calls
252  * from one user will not affect the same settings for other users, other
253  * users can continue using libusb after one of them calls libusb_exit(), etc.
254  *
255  * This is made possible through libusb's <em>context</em> concept. When you
256  * call libusb_init(), you are (optionally) given a context. You can then pass
257  * this context pointer back into future libusb functions.
258  *
259  * In order to keep things simple for more simplistic applications, it is
260  * legal to pass NULL to all functions requiring a context pointer (as long as
261  * you're sure no other code will attempt to use libusb from the same process).
262  * When you pass NULL, the default context will be used. The default context
263  * is created the first time a process calls libusb_init() when no other
264  * context is alive. Contexts are destroyed during libusb_exit().
265  *
266  * You may be wondering why only a subset of libusb functions require a
267  * context pointer in their function definition. Internally, libusb stores
268  * context pointers in other objects (e.g. libusb_device instances) and hence
269  * can infer the context from those objects.
270  */
271
272 /**
273  * @defgroup lib Library initialization/deinitialization
274  * This page details how to initialize and deinitialize libusb. Initialization
275  * must be performed before using any libusb functionality, and similarly you
276  * must not call any libusb functions after deinitialization.
277  */
278
279 /**
280  * @defgroup dev Device handling and enumeration
281  * The functionality documented below is designed to help with the following
282  * operations:
283  * - Enumerating the USB devices currently attached to the system
284  * - Choosing a device to operate from your software
285  * - Opening and closing the chosen device
286  *
287  * \section nutshell In a nutshell...
288  *
289  * The description below really makes things sound more complicated than they
290  * actually are. The following sequence of function calls will be suitable
291  * for almost all scenarios and does not require you to have such a deep
292  * understanding of the resource management issues:
293  * \code
294 // discover devices
295 libusb_device **list;
296 libusb_device *found = NULL;
297 size_t cnt = libusb_get_device_list(NULL, &list);
298 size_t i = 0;
299 int err = 0;
300 if (cnt < 0)
301         error();
302
303 for (i = 0; i < cnt; i++) {
304         libusb_device *device = list[i];
305         if (is_interesting(device)) {
306                 found = device;
307                 break;
308         }
309 }
310
311 if (found) {
312         libusb_device_handle *handle;
313
314         err = libusb_open(found, &handle);
315         if (err)
316                 error();
317         // etc
318 }
319
320 libusb_free_device_list(list, 1);
321 \endcode
322  *
323  * The two important points:
324  * - You asked libusb_free_device_list() to unreference the devices (2nd
325  *   parameter)
326  * - You opened the device before freeing the list and unreferencing the
327  *   devices
328  *
329  * If you ended up with a handle, you can now proceed to perform I/O on the
330  * device.
331  *
332  * \section devshandles Devices and device handles
333  * libusb has a concept of a USB device, represented by the
334  * \ref libusb_device opaque type. A device represents a USB device that
335  * is currently or was previously connected to the system. Using a reference
336  * to a device, you can determine certain information about the device (e.g.
337  * you can read the descriptor data).
338  *
339  * The libusb_get_device_list() function can be used to obtain a list of
340  * devices currently connected to the system. This is known as device
341  * discovery.
342  *
343  * Just because you have a reference to a device does not mean it is
344  * necessarily usable. The device may have been unplugged, you may not have
345  * permission to operate such device, or another program or driver may be
346  * using the device.
347  *
348  * When you've found a device that you'd like to operate, you must ask
349  * libusb to open the device using the libusb_open() function. Assuming
350  * success, libusb then returns you a <em>device handle</em>
351  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
352  * operate on the handle rather than the original device pointer.
353  *
354  * \section devref Device discovery and reference counting
355  *
356  * Device discovery (i.e. calling libusb_get_device_list()) returns a
357  * freshly-allocated list of devices. The list itself must be freed when
358  * you are done with it. libusb also needs to know when it is OK to free
359  * the contents of the list - the devices themselves.
360  *
361  * To handle these issues, libusb provides you with two separate items:
362  * - A function to free the list itself
363  * - A reference counting system for the devices inside
364  *
365  * New devices presented by the libusb_get_device_list() function all have a
366  * reference count of 1. You can increase and decrease reference count using
367  * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
368  * its reference count reaches 0.
369  *
370  * With the above information in mind, the process of opening a device can
371  * be viewed as follows:
372  * -# Discover devices using libusb_get_device_list().
373  * -# Choose the device that you want to operate, and call libusb_open().
374  * -# Unref all devices in the discovered device list.
375  * -# Free the discovered device list.
376  *
377  * The order is important - you must not unreference the device before
378  * attempting to open it, because unreferencing it may destroy the device.
379  *
380  * For convenience, the libusb_free_device_list() function includes a
381  * parameter to optionally unreference all the devices in the list before
382  * freeing the list itself. This combines steps 3 and 4 above.
383  *
384  * As an implementation detail, libusb_open() actually adds a reference to
385  * the device in question. This is because the device remains available
386  * through the handle via libusb_get_device(). The reference is deleted during
387  * libusb_close().
388  */
389
390 /** @defgroup misc Miscellaneous */
391
392 /* we traverse usbfs without knowing how many devices we are going to find.
393  * so we create this discovered_devs model which is similar to a linked-list
394  * which grows when required. it can be freed once discovery has completed,
395  * eliminating the need for a list node in the libusb_device structure
396  * itself. */
397 #define DISCOVERED_DEVICES_SIZE_STEP 8
398
399 static struct discovered_devs *discovered_devs_alloc(void)
400 {
401         struct discovered_devs *ret =
402                 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
403
404         if (ret) {
405                 ret->len = 0;
406                 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
407         }
408         return ret;
409 }
410
411 /* append a device to the discovered devices collection. may realloc itself,
412  * returning new discdevs. returns NULL on realloc failure. */
413 struct discovered_devs *discovered_devs_append(
414         struct discovered_devs *discdevs, struct libusb_device *dev)
415 {
416         size_t len = discdevs->len;
417         size_t capacity;
418
419         /* if there is space, just append the device */
420         if (len < discdevs->capacity) {
421                 discdevs->devices[len] = libusb_ref_device(dev);
422                 discdevs->len++;
423                 return discdevs;
424         }
425
426         /* exceeded capacity, need to grow */
427         usbi_dbg("need to increase capacity");
428         capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
429         discdevs = realloc(discdevs,
430                 sizeof(*discdevs) + (sizeof(void *) * capacity));
431         if (discdevs) {
432                 discdevs->capacity = capacity;
433                 discdevs->devices[len] = libusb_ref_device(dev);
434                 discdevs->len++;
435         }
436
437         return discdevs;
438 }
439
440 static void discovered_devs_free(struct discovered_devs *discdevs)
441 {
442         size_t i;
443
444         for (i = 0; i < discdevs->len; i++)
445                 libusb_unref_device(discdevs->devices[i]);
446
447         free(discdevs);
448 }
449
450 /* Allocate a new device with a specific session ID. The returned device has
451  * a reference count of 1. */
452 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
453         unsigned long session_id)
454 {
455         size_t priv_size = usbi_backend->device_priv_size;
456         struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
457         int r;
458
459         if (!dev)
460                 return NULL;
461
462         r = pthread_mutex_init(&dev->lock, NULL);
463         if (r)
464                 return NULL;
465
466         dev->ctx = ctx;
467         dev->refcnt = 1;
468         dev->session_data = session_id;
469         memset(&dev->os_priv, 0, priv_size);
470
471         pthread_mutex_lock(&ctx->usb_devs_lock);
472         list_add(&dev->list, &ctx->usb_devs);
473         pthread_mutex_unlock(&ctx->usb_devs_lock);
474         return dev;
475 }
476
477 /* Perform some final sanity checks on a newly discovered device. If this
478  * function fails (negative return code), the device should not be added
479  * to the discovered device list. */
480 int usbi_sanitize_device(struct libusb_device *dev)
481 {
482         int r;
483         unsigned char raw_desc[DEVICE_DESC_LENGTH];
484         uint8_t num_configurations;
485         int host_endian;
486
487         r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
488         if (r < 0)
489                 return r;
490
491         num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
492         if (num_configurations > USB_MAXCONFIG) {
493                 usbi_err(DEVICE_CTX(dev), "too many configurations");
494                 return LIBUSB_ERROR_IO;
495         } else if (num_configurations < 1) {
496                 usbi_dbg("no configurations?");
497                 return LIBUSB_ERROR_IO;
498         }
499
500         dev->num_configurations = num_configurations;
501         return 0;
502 }
503
504 /* Examine libusb's internal list of known devices, looking for one with
505  * a specific session ID. Returns the matching device if it was found, and
506  * NULL otherwise. */
507 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
508         unsigned long session_id)
509 {
510         struct libusb_device *dev;
511         struct libusb_device *ret = NULL;
512
513         pthread_mutex_lock(&ctx->usb_devs_lock);
514         list_for_each_entry(dev, &ctx->usb_devs, list)
515                 if (dev->session_data == session_id) {
516                         ret = dev;
517                         break;
518                 }
519         pthread_mutex_unlock(&ctx->usb_devs_lock);
520
521         return ret;
522 }
523
524 /** @ingroup dev
525  * Returns a list of USB devices currently attached to the system. This is
526  * your entry point into finding a USB device to operate.
527  *
528  * You are expected to unreference all the devices when you are done with
529  * them, and then free the list with libusb_free_device_list(). Note that
530  * libusb_free_device_list() can unref all the devices for you. Be careful
531  * not to unreference a device you are about to open until after you have
532  * opened it.
533  *
534  * This return value of this function indicates the number of devices in
535  * the resultant list. The list is actually one element larger, as it is
536  * NULL-terminated.
537  *
538  * \param ctx the context to operate on, or NULL for the default context
539  * \param list output location for a list of devices. Must be later freed with
540  * libusb_free_device_list().
541  * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
542  * on memory allocation failure.
543  */
544 API_EXPORTED ssize_t libusb_get_device_list(libusb_context *ctx,
545         libusb_device ***list)
546 {
547         struct discovered_devs *discdevs = discovered_devs_alloc();
548         struct libusb_device **ret;
549         int r = 0;
550         size_t i;
551         ssize_t len;
552         USBI_GET_CONTEXT(ctx);
553         usbi_dbg("");
554
555         if (!discdevs)
556                 return LIBUSB_ERROR_NO_MEM;
557
558         r = usbi_backend->get_device_list(ctx, &discdevs);
559         if (r < 0) {
560                 len = r;
561                 goto out;
562         }
563
564         /* convert discovered_devs into a list */
565         len = discdevs->len;
566         ret = malloc(sizeof(void *) * (len + 1));
567         if (!ret) {
568                 len = LIBUSB_ERROR_NO_MEM;
569                 goto out;
570         }
571
572         ret[len] = NULL;
573         for (i = 0; i < len; i++) {
574                 struct libusb_device *dev = discdevs->devices[i];
575                 ret[i] = libusb_ref_device(dev);
576         }
577         *list = ret;
578
579 out:
580         discovered_devs_free(discdevs);
581         return len;
582 }
583
584 /** \ingroup dev
585  * Frees a list of devices previously discovered using
586  * libusb_get_device_list(). If the unref_devices parameter is set, the
587  * reference count of each device in the list is decremented by 1.
588  * \param list the list to free
589  * \param unref_devices whether to unref the devices in the list
590  */
591 API_EXPORTED void libusb_free_device_list(libusb_device **list,
592         int unref_devices)
593 {
594         if (!list)
595                 return;
596
597         if (unref_devices) {
598                 int i = 0;
599                 struct libusb_device *dev;
600
601                 while ((dev = list[i++]) != NULL)
602                         libusb_unref_device(dev);
603         }
604         free(list);
605 }
606
607 /** \ingroup dev
608  * Get the number of the bus that a device is connected to.
609  * \param dev a device
610  * \returns the bus number
611  */
612 API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev)
613 {
614         return dev->bus_number;
615 }
616
617 /** \ingroup dev
618  * Get the address of the device on the bus it is connected to.
619  * \param dev a device
620  * \returns the device address
621  */
622 API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev)
623 {
624         return dev->device_address;
625 }
626
627 /** \ingroup dev
628  * Convenience function to retrieve the wMaxPacketSize value for a particular
629  * endpoint in the active device configuration. This is useful for setting up
630  * isochronous transfers.
631  *
632  * \param dev a device
633  * \param endpoint address of the endpoint in question
634  * \returns the wMaxPacketSize value
635  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
636  * \returns LIBUSB_ERROR_OTHER on other failure
637  */
638 API_EXPORTED int libusb_get_max_packet_size(libusb_device *dev,
639         unsigned char endpoint)
640 {
641         int iface_idx;
642         struct libusb_config_descriptor *config;
643         int r;
644         
645         r = libusb_get_active_config_descriptor(dev, &config);
646         if (r < 0) {
647                 usbi_err(DEVICE_CTX(dev),
648                         "could not retrieve active config descriptor");
649                 return LIBUSB_ERROR_OTHER;
650         }
651
652         r = LIBUSB_ERROR_NOT_FOUND;
653         for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
654                 const struct libusb_interface *iface = &config->interface[iface_idx];
655                 int altsetting_idx;
656
657                 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
658                                 altsetting_idx++) {
659                         const struct libusb_interface_descriptor *altsetting
660                                 = &iface->altsetting[altsetting_idx];
661                         int ep_idx;
662
663                         for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
664                                 const struct libusb_endpoint_descriptor *ep =
665                                         &altsetting->endpoint[ep_idx];
666                                 if (ep->bEndpointAddress == endpoint) {
667                                         r = ep->wMaxPacketSize;
668                                         goto out;
669                                 }
670                         }
671                 }
672         }
673
674 out:
675         libusb_free_config_descriptor(config);
676         return r;
677 }
678
679 /** \ingroup dev
680  * Increment the reference count of a device.
681  * \param dev the device to reference
682  * \returns the same device
683  */
684 API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev)
685 {
686         pthread_mutex_lock(&dev->lock);
687         dev->refcnt++;
688         pthread_mutex_unlock(&dev->lock);
689         return dev;
690 }
691
692 /** \ingroup dev
693  * Decrement the reference count of a device. If the decrement operation
694  * causes the reference count to reach zero, the device shall be destroyed.
695  * \param dev the device to unreference
696  */
697 API_EXPORTED void libusb_unref_device(libusb_device *dev)
698 {
699         int refcnt;
700
701         if (!dev)
702                 return;
703
704         pthread_mutex_lock(&dev->lock);
705         refcnt = --dev->refcnt;
706         pthread_mutex_unlock(&dev->lock);
707
708         if (refcnt == 0) {
709                 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
710
711                 if (usbi_backend->destroy_device)
712                         usbi_backend->destroy_device(dev);
713
714                 pthread_mutex_lock(&dev->ctx->usb_devs_lock);
715                 list_del(&dev->list);
716                 pthread_mutex_unlock(&dev->ctx->usb_devs_lock);
717
718                 free(dev);
719         }
720 }
721
722 /** \ingroup dev
723  * Open a device and obtain a device handle. A handle allows you to perform
724  * I/O on the device in question.
725  *
726  * Internally, this function adds a reference to the device and makes it
727  * available to you through libusb_get_device(). This reference is removed
728  * during libusb_close().
729  *
730  * This is a non-blocking function; no requests are sent over the bus.
731  *
732  * \param dev the device to open
733  * \param handle output location for the returned device handle pointer. Only
734  * populated when the return code is 0.
735  * \returns 0 on success
736  * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
737  * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
738  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
739  * \returns another LIBUSB_ERROR code on other failure
740  */
741 API_EXPORTED int libusb_open(libusb_device *dev, libusb_device_handle **handle)
742 {
743         struct libusb_context *ctx = DEVICE_CTX(dev);
744         struct libusb_device_handle *_handle;
745         size_t priv_size = usbi_backend->device_handle_priv_size;
746         unsigned char dummy = 1;
747         int r;
748         usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
749
750         _handle = malloc(sizeof(*_handle) + priv_size);
751         if (!_handle)
752                 return LIBUSB_ERROR_NO_MEM;
753
754         r = pthread_mutex_init(&_handle->lock, NULL);
755         if (r)
756                 return LIBUSB_ERROR_OTHER;
757
758         _handle->dev = libusb_ref_device(dev);
759         _handle->claimed_interfaces = 0;
760         memset(&_handle->os_priv, 0, priv_size);
761
762         r = usbi_backend->open(_handle);
763         if (r < 0) {
764                 libusb_unref_device(dev);
765                 free(_handle);
766                 return r;
767         }
768
769         pthread_mutex_lock(&ctx->open_devs_lock);
770         list_add(&_handle->list, &ctx->open_devs);
771         pthread_mutex_unlock(&ctx->open_devs_lock);
772         *handle = _handle;
773
774
775         /* At this point, we want to interrupt any existing event handlers so
776          * that they realise the addition of the new device's poll fd. One
777          * example when this is desirable is if the user is running a separate
778          * dedicated libusb events handling thread, which is running with a long
779          * or infinite timeout. We want to interrupt that iteration of the loop,
780          * so that it picks up the new fd, and then continues. */
781
782         /* record that we are messing with poll fds */
783         pthread_mutex_lock(&ctx->pollfd_modify_lock);
784         ctx->pollfd_modify++;
785         pthread_mutex_unlock(&ctx->pollfd_modify_lock);
786
787         /* write some data on control pipe to interrupt event handlers */
788         r = write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
789         if (r <= 0) {
790                 usbi_warn(ctx, "internal signalling write failed");
791                 pthread_mutex_lock(&ctx->pollfd_modify_lock);
792                 ctx->pollfd_modify--;
793                 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
794                 return 0;
795         }
796
797         /* take event handling lock */
798         libusb_lock_events(ctx);
799
800         /* read the dummy data */
801         r = read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
802         if (r <= 0)
803                 usbi_warn(ctx, "internal signalling read failed");
804
805         /* we're done with modifying poll fds */
806         pthread_mutex_lock(&ctx->pollfd_modify_lock);
807         ctx->pollfd_modify--;
808         pthread_mutex_unlock(&ctx->pollfd_modify_lock);
809
810         /* Release event handling lock and wake up event waiters */
811         libusb_unlock_events(ctx);
812
813         return 0;
814 }
815
816 /** \ingroup dev
817  * Convenience function for finding a device with a particular
818  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
819  * for those scenarios where you are using libusb to knock up a quick test
820  * application - it allows you to avoid calling libusb_get_device_list() and
821  * worrying about traversing/freeing the list.
822  *
823  * This function has limitations and is hence not intended for use in real
824  * applications: if multiple devices have the same IDs it will only
825  * give you the first one, etc.
826  *
827  * \param ctx the context to operate on, or NULL for the default context
828  * \param vendor_id the idVendor value to search for
829  * \param product_id the idProduct value to search for
830  * \returns a handle for the first found device, or NULL on error or if the
831  * device could not be found. */
832 API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid(
833         libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
834 {
835         struct libusb_device **devs;
836         struct libusb_device *found = NULL;
837         struct libusb_device *dev;
838         struct libusb_device_handle *handle = NULL;
839         size_t i = 0;
840         int r;
841
842         if (libusb_get_device_list(ctx, &devs) < 0)
843                 return NULL;
844
845         while ((dev = devs[i++]) != NULL) {
846                 struct libusb_device_descriptor desc;
847                 r = libusb_get_device_descriptor(dev, &desc);
848                 if (r < 0)
849                         goto out;
850                 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
851                         found = dev;
852                         break;
853                 }
854         }
855
856         if (found) {
857                 r = libusb_open(found, &handle);
858                 if (r < 0)
859                         handle = NULL;
860         }
861
862 out:
863         libusb_free_device_list(devs, 1);
864         return handle;
865 }
866
867 static void do_close(struct libusb_context *ctx,
868         struct libusb_device_handle *dev_handle)
869 {
870         pthread_mutex_lock(&ctx->open_devs_lock);
871         list_del(&dev_handle->list);
872         pthread_mutex_unlock(&ctx->open_devs_lock);
873
874         usbi_backend->close(dev_handle);
875         libusb_unref_device(dev_handle->dev);
876         free(dev_handle);
877 }
878
879 /** \ingroup dev
880  * Close a device handle. Should be called on all open handles before your
881  * application exits.
882  *
883  * Internally, this function destroys the reference that was added by
884  * libusb_open() on the given device.
885  *
886  * This is a non-blocking function; no requests are sent over the bus.
887  *
888  * \param dev_handle the handle to close
889  */
890 API_EXPORTED void libusb_close(libusb_device_handle *dev_handle)
891 {
892         struct libusb_context *ctx;
893         unsigned char dummy = 1;
894         ssize_t r;
895
896         if (!dev_handle)
897                 return;
898         usbi_dbg("");
899
900         ctx = HANDLE_CTX(dev_handle);
901
902         /* Similarly to libusb_open(), we want to interrupt all event handlers
903          * at this point. More importantly, we want to perform the actual close of
904          * the device while holding the event handling lock (preventing any other
905          * thread from doing event handling) because we will be removing a file
906          * descriptor from the polling loop. */
907
908         /* record that we are messing with poll fds */
909         pthread_mutex_lock(&ctx->pollfd_modify_lock);
910         ctx->pollfd_modify++;
911         pthread_mutex_unlock(&ctx->pollfd_modify_lock);
912
913         /* write some data on control pipe to interrupt event handlers */
914         r = write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
915         if (r <= 0) {
916                 usbi_warn(ctx, "internal signalling write failed, closing anyway");
917                 do_close(ctx, dev_handle);
918                 pthread_mutex_lock(&ctx->pollfd_modify_lock);
919                 ctx->pollfd_modify--;
920                 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
921                 return;
922         }
923
924         /* take event handling lock */
925         libusb_lock_events(ctx);
926
927         /* read the dummy data */
928         r = read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
929         if (r <= 0)
930                 usbi_warn(ctx, "internal signalling read failed, closing anyway");
931
932         /* Close the device */
933         do_close(ctx, dev_handle);
934
935         /* we're done with modifying poll fds */
936         pthread_mutex_lock(&ctx->pollfd_modify_lock);
937         ctx->pollfd_modify--;
938         pthread_mutex_unlock(&ctx->pollfd_modify_lock);
939
940         /* Release event handling lock and wake up event waiters */
941         libusb_unlock_events(ctx);
942 }
943
944 /** \ingroup dev
945  * Get the underlying device for a handle. This function does not modify
946  * the reference count of the returned device, so do not feel compelled to
947  * unreference it when you are done.
948  * \param dev_handle a device handle
949  * \returns the underlying device
950  */
951 API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle)
952 {
953         return dev_handle->dev;
954 }
955
956 /** \ingroup dev
957  * Determine the bConfigurationValue of the currently active configuration.
958  *
959  * You could formulate your own control request to obtain this information,
960  * but this function has the advantage that it may be able to retrieve the
961  * information from operating system caches (no I/O involved).
962  *
963  * If the OS does not cache this information, then this function will block
964  * while a control transfer is submitted to retrieve the information.
965  *
966  * This function will return a value of 0 in the <tt>config</tt> output
967  * parameter if the device is in unconfigured state.
968  *
969  * \param dev a device handle
970  * \param config output location for the bConfigurationValue of the active
971  * configuration (only valid for return code 0)
972  * \returns 0 on success
973  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
974  * \returns another LIBUSB_ERROR code on other failure
975  */
976 API_EXPORTED int libusb_get_configuration(libusb_device_handle *dev,
977         int *config)
978 {
979         int r = LIBUSB_ERROR_NOT_SUPPORTED;
980
981         usbi_dbg("");
982         if (usbi_backend->get_configuration)
983                 r = usbi_backend->get_configuration(dev, config);
984
985         if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
986                 uint8_t tmp = 0;
987                 usbi_dbg("falling back to control message");
988                 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
989                         LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
990                 if (r == 0) {
991                         usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
992                         r = LIBUSB_ERROR_IO;
993                 } else if (r == 1) {
994                         r = 0;
995                         *config = tmp;
996                 } else {
997                         usbi_dbg("control failed, error %d", r);
998                 }
999         }
1000
1001         if (r == 0)
1002                 usbi_dbg("active config %d", *config);
1003
1004         return r;
1005 }
1006
1007 /** \ingroup dev
1008  * Set the active configuration for a device.
1009  *
1010  * The operating system may or may not have already set an active
1011  * configuration on the device. It is up to your application to ensure the
1012  * correct configuration is selected before you attempt to claim interfaces
1013  * and perform other operations.
1014  * 
1015  * If you call this function on a device already configured with the selected
1016  * configuration, then this function will act as a lightweight device reset:
1017  * it will issue a SET_CONFIGURATION request using the current configuration,
1018  * causing most USB-related device state to be reset (altsetting reset to zero,
1019  * endpoint halts cleared, toggles reset).
1020  *
1021  * You cannot change/reset configuration if your application has claimed
1022  * interfaces - you should free them with libusb_release_interface() first.
1023  * You cannot change/reset configuration if other applications or drivers have
1024  * claimed interfaces.
1025  *
1026  * A configuration value of -1 will put the device in unconfigured state.
1027  * The USB specifications state that a configuration value of 0 does this,
1028  * however buggy devices exist which actually have a configuration 0.
1029  *
1030  * You should always use this function rather than formulating your own
1031  * SET_CONFIGURATION control request. This is because the underlying operating
1032  * system needs to know when such changes happen.
1033  *
1034  * This is a blocking function.
1035  *
1036  * \param dev a device handle
1037  * \param configuration the bConfigurationValue of the configuration you
1038  * wish to activate, or -1 if you wish to put the device in unconfigured state
1039  * \returns 0 on success
1040  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1041  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1042  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1043  * \returns another LIBUSB_ERROR code on other failure
1044  */
1045 API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev,
1046         int configuration)
1047 {
1048         usbi_dbg("configuration %d", configuration);
1049         return usbi_backend->set_configuration(dev, configuration);
1050 }
1051
1052 /** \ingroup dev
1053  * Claim an interface on a given device handle. You must claim the interface
1054  * you wish to use before you can perform I/O on any of its endpoints.
1055  *
1056  * It is legal to attempt to claim an already-claimed interface, in which
1057  * case libusb just returns 0 without doing anything.
1058  *
1059  * Claiming of interfaces is a purely logical operation; it does not cause
1060  * any requests to be sent over the bus. Interface claiming is used to
1061  * instruct the underlying operating system that your application wishes
1062  * to take ownership of the interface.
1063  *
1064  * This is a non-blocking function.
1065  *
1066  * \param dev a device handle
1067  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1068  * wish to claim
1069  * \returns 0 on success
1070  * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1071  * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1072  * interface
1073  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1074  * \returns a LIBUSB_ERROR code on other failure
1075  */
1076 API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev,
1077         int interface_number)
1078 {
1079         int r = 0;
1080
1081         usbi_dbg("interface %d", interface_number);
1082         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1083                 return LIBUSB_ERROR_INVALID_PARAM;
1084
1085         pthread_mutex_lock(&dev->lock);
1086         if (dev->claimed_interfaces & (1 << interface_number))
1087                 goto out;
1088
1089         r = usbi_backend->claim_interface(dev, interface_number);
1090         if (r == 0)
1091                 dev->claimed_interfaces |= 1 << interface_number;
1092
1093 out:
1094         pthread_mutex_unlock(&dev->lock);
1095         return r;
1096 }
1097
1098 /** \ingroup dev
1099  * Release an interface previously claimed with libusb_claim_interface(). You
1100  * should release all claimed interfaces before closing a device handle.
1101  *
1102  * This is a blocking function. A SET_INTERFACE control request will be sent
1103  * to the device, resetting interface state to the first alternate setting.
1104  *
1105  * \param dev a device handle
1106  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1107  * previously-claimed interface
1108  * \returns 0 on success
1109  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1110  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1111  * \returns another LIBUSB_ERROR code on other failure
1112  */
1113 API_EXPORTED int libusb_release_interface(libusb_device_handle *dev,
1114         int interface_number)
1115 {
1116         int r;
1117
1118         usbi_dbg("interface %d", interface_number);
1119         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1120                 return LIBUSB_ERROR_INVALID_PARAM;
1121
1122         pthread_mutex_lock(&dev->lock);
1123         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1124                 r = LIBUSB_ERROR_NOT_FOUND;
1125                 goto out;
1126         }
1127
1128         r = usbi_backend->release_interface(dev, interface_number);
1129         if (r == 0)
1130                 dev->claimed_interfaces &= ~(1 << interface_number);
1131
1132 out:
1133         pthread_mutex_unlock(&dev->lock);
1134         return r;
1135 }
1136
1137 /** \ingroup dev
1138  * Activate an alternate setting for an interface. The interface must have
1139  * been previously claimed with libusb_claim_interface().
1140  *
1141  * You should always use this function rather than formulating your own
1142  * SET_INTERFACE control request. This is because the underlying operating
1143  * system needs to know when such changes happen.
1144  *
1145  * This is a blocking function.
1146  *
1147  * \param dev a device handle
1148  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1149  * previously-claimed interface
1150  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1151  * setting to activate
1152  * \returns 0 on success
1153  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1154  * requested alternate setting does not exist
1155  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1156  * \returns another LIBUSB_ERROR code on other failure
1157  */
1158 API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev,
1159         int interface_number, int alternate_setting)
1160 {
1161         usbi_dbg("interface %d altsetting %d",
1162                 interface_number, alternate_setting);
1163         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1164                 return LIBUSB_ERROR_INVALID_PARAM;
1165
1166         pthread_mutex_lock(&dev->lock);
1167         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1168                 pthread_mutex_unlock(&dev->lock);       
1169                 return LIBUSB_ERROR_NOT_FOUND;
1170         }
1171         pthread_mutex_unlock(&dev->lock);
1172
1173         return usbi_backend->set_interface_altsetting(dev, interface_number,
1174                 alternate_setting);
1175 }
1176
1177 /** \ingroup dev
1178  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1179  * are unable to receive or transmit data until the halt condition is stalled.
1180  *
1181  * You should cancel all pending transfers before attempting to clear the halt
1182  * condition.
1183  *
1184  * This is a blocking function.
1185  *
1186  * \param dev a device handle
1187  * \param endpoint the endpoint to clear halt status
1188  * \returns 0 on success
1189  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1190  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1191  * \returns another LIBUSB_ERROR code on other failure
1192  */
1193 API_EXPORTED int libusb_clear_halt(libusb_device_handle *dev,
1194         unsigned char endpoint)
1195 {
1196         usbi_dbg("endpoint %x", endpoint);
1197         return usbi_backend->clear_halt(dev, endpoint);
1198 }
1199
1200 /** \ingroup dev
1201  * Perform a USB port reset to reinitialize a device. The system will attempt
1202  * to restore the previous configuration and alternate settings after the
1203  * reset has completed.
1204  *
1205  * If the reset fails, the descriptors change, or the previous state cannot be
1206  * restored, the device will appear to be disconnected and reconnected. This
1207  * means that the device handle is no longer valid (you should close it) and
1208  * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1209  * when this is the case.
1210  *
1211  * This is a blocking function which usually incurs a noticeable delay.
1212  *
1213  * \param dev a handle of the device to reset
1214  * \returns 0 on success
1215  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1216  * device has been disconnected
1217  * \returns another LIBUSB_ERROR code on other failure
1218  */
1219 API_EXPORTED int libusb_reset_device(libusb_device_handle *dev)
1220 {
1221         usbi_dbg("");
1222         return usbi_backend->reset_device(dev);
1223 }
1224
1225 /** \ingroup dev
1226  * Determine if a kernel driver is active on an interface. If a kernel driver
1227  * is active, you cannot claim the interface, and libusb will be unable to
1228  * perform I/O.
1229  *
1230  * \param dev a device handle
1231  * \param interface the interface to check
1232  * \returns 0 if no kernel driver is active
1233  * \returns 1 if a kernel driver is active
1234  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1235  * \returns another LIBUSB_ERROR code on other failure
1236  * \see libusb_detach_kernel_driver()
1237  */
1238 API_EXPORTED int libusb_kernel_driver_active(libusb_device_handle *dev,
1239         int interface)
1240 {
1241         usbi_dbg("interface %d", interface);
1242         if (usbi_backend->kernel_driver_active)
1243                 return usbi_backend->kernel_driver_active(dev, interface);
1244         else
1245                 return LIBUSB_ERROR_NOT_SUPPORTED;
1246 }
1247
1248 /** \ingroup dev
1249  * Detach a kernel driver from an interface. If successful, you will then be
1250  * able to claim the interface and perform I/O.
1251  *
1252  * \param dev a device handle
1253  * \param interface the interface to detach the driver from
1254  * \returns 0 on success
1255  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1256  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1257  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1258  * \returns another LIBUSB_ERROR code on other failure
1259  * \see libusb_kernel_driver_active()
1260  */
1261 API_EXPORTED int libusb_detach_kernel_driver(libusb_device_handle *dev,
1262         int interface)
1263 {
1264         usbi_dbg("interface %d", interface);
1265         if (usbi_backend->detach_kernel_driver)
1266                 return usbi_backend->detach_kernel_driver(dev, interface);
1267         else
1268                 return LIBUSB_ERROR_NOT_SUPPORTED;
1269 }
1270
1271 /** \ingroup dev
1272  * Re-attach an interface's kernel driver, which was previously detached
1273  * using libusb_detach_kernel_driver().
1274  *
1275  * \param dev a device handle
1276  * \param interface the interface to attach the driver from
1277  * \returns 0 on success
1278  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1279  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1280  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1281  * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1282  * interface is claimed by a program or driver
1283  * \returns another LIBUSB_ERROR code on other failure
1284  * \see libusb_kernel_driver_active()
1285  */
1286 API_EXPORTED int libusb_attach_kernel_driver(libusb_device_handle *dev,
1287         int interface)
1288 {
1289         usbi_dbg("interface %d", interface);
1290         if (usbi_backend->attach_kernel_driver)
1291                 return usbi_backend->attach_kernel_driver(dev, interface);
1292         else
1293                 return LIBUSB_ERROR_NOT_SUPPORTED;
1294 }
1295
1296 /** \ingroup lib
1297  * Set message verbosity.
1298  *  - Level 0: no messages ever printed by the library (default)
1299  *  - Level 1: error messages are printed to stderr
1300  *  - Level 2: warning and error messages are printed to stderr
1301  *  - Level 3: informational messages are printed to stdout, warning and error
1302  *    messages are printed to stderr
1303  *
1304  * The default level is 0, which means no messages are ever printed. If you
1305  * choose to increase the message verbosity level, ensure that your
1306  * application does not close the stdout/stderr file descriptors.
1307  *
1308  * You are advised to set level 3. libusb is conservative with its message
1309  * logging and most of the time, will only log messages that explain error
1310  * conditions and other oddities. This will help you debug your software.
1311  *
1312  * If the LIBUSB_DEBUG environment variable was set when libusb was
1313  * initialized, this function does nothing: the message verbosity is fixed
1314  * to the value in the environment variable.
1315  *
1316  * If libusb was compiled without any message logging, this function does
1317  * nothing: you'll never get any messages.
1318  *
1319  * If libusb was compiled with verbose debug message logging, this function
1320  * does nothing: you'll always get messages from all levels.
1321  *
1322  * \param ctx the context to operate on, or NULL for the default context
1323  * \param level debug level to set
1324  */
1325 API_EXPORTED void libusb_set_debug(libusb_context *ctx, int level)
1326 {
1327         USBI_GET_CONTEXT(ctx);
1328         if (!ctx->debug_fixed)
1329                 ctx->debug = level;
1330 }
1331
1332 /** \ingroup lib
1333  * Initialize libusb. This function must be called before calling any other
1334  * libusb function.
1335  * \param context Optional output location for context pointer.
1336  * Only valid on return code 0.
1337  * \returns 0 on success, or a LIBUSB_ERROR code on failure
1338  */
1339 API_EXPORTED int libusb_init(libusb_context **context)
1340 {
1341         char *dbg = getenv("LIBUSB_DEBUG");
1342         struct libusb_context *ctx = malloc(sizeof(*ctx));
1343         int r;
1344
1345         if (!ctx)
1346                 return LIBUSB_ERROR_NO_MEM;
1347         memset(ctx, 0, sizeof(*ctx));
1348
1349         if (dbg) {
1350                 ctx->debug = atoi(dbg);
1351                 if (ctx->debug)
1352                         ctx->debug_fixed = 1;
1353         }
1354
1355         usbi_dbg("");
1356
1357         if (usbi_backend->init) {
1358                 r = usbi_backend->init(ctx);
1359                 if (r)
1360                         goto err;
1361         }
1362
1363         pthread_mutex_init(&ctx->usb_devs_lock, NULL);
1364         pthread_mutex_init(&ctx->open_devs_lock, NULL);
1365         list_init(&ctx->usb_devs);
1366         list_init(&ctx->open_devs);
1367
1368         r = usbi_io_init(ctx);
1369         if (r < 0) {
1370                 if (usbi_backend->exit)
1371                         usbi_backend->exit();
1372                 goto err;
1373         }
1374
1375         pthread_mutex_lock(&default_context_lock);
1376         if (!usbi_default_context) {
1377                 usbi_dbg("created default context");
1378                 usbi_default_context = ctx;
1379         }
1380         pthread_mutex_unlock(&default_context_lock);
1381
1382         if (context)
1383                 *context = ctx;
1384         return 0;
1385
1386 err:
1387         free(ctx);
1388         return r;
1389 }
1390
1391 /** \ingroup lib
1392  * Deinitialize libusb. Should be called after closing all open devices and
1393  * before your application terminates.
1394  * \param ctx the context to deinitialize, or NULL for the default context
1395  */
1396 API_EXPORTED void libusb_exit(struct libusb_context *ctx)
1397 {
1398         USBI_GET_CONTEXT(ctx);
1399         usbi_dbg("");
1400
1401         /* a little sanity check. doesn't bother with open_devs locking because
1402          * unless there is an application bug, nobody will be accessing this. */
1403         if (!list_empty(&ctx->open_devs))
1404                 usbi_warn(ctx, "application left some devices open");
1405
1406         usbi_io_exit(ctx);
1407         if (usbi_backend->exit)
1408                 usbi_backend->exit();
1409
1410         pthread_mutex_lock(&default_context_lock);
1411         if (ctx == usbi_default_context) {
1412                 usbi_dbg("freeing default context");
1413                 usbi_default_context = NULL;
1414         }
1415         pthread_mutex_unlock(&default_context_lock);
1416
1417         free(ctx);
1418 }
1419
1420 void usbi_log(struct libusb_context *ctx, enum usbi_log_level level,
1421         const char *function, const char *format, ...)
1422 {
1423         va_list args;
1424         FILE *stream = stdout;
1425         const char *prefix;
1426
1427 #ifndef ENABLE_DEBUG_LOGGING
1428         USBI_GET_CONTEXT(ctx);
1429         if (!ctx->debug)
1430                 return;
1431         if (level == LOG_LEVEL_WARNING && ctx->debug < 2)
1432                 return;
1433         if (level == LOG_LEVEL_INFO && ctx->debug < 3)
1434                 return;
1435 #endif
1436
1437         switch (level) {
1438         case LOG_LEVEL_INFO:
1439                 prefix = "info";
1440                 break;
1441         case LOG_LEVEL_WARNING:
1442                 stream = stderr;
1443                 prefix = "warning";
1444                 break;
1445         case LOG_LEVEL_ERROR:
1446                 stream = stderr;
1447                 prefix = "error";
1448                 break;
1449         case LOG_LEVEL_DEBUG:
1450                 stream = stderr;
1451                 prefix = "debug";
1452                 break;
1453         default:
1454                 stream = stderr;
1455                 prefix = "unknown";
1456                 break;
1457         }
1458
1459         fprintf(stream, "libusb:%s [%s] ", prefix, function);
1460
1461         va_start (args, format);
1462         vfprintf(stream, format, args);
1463         va_end (args);
1464
1465         fprintf(stream, "\n");
1466 }
1467