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