5834bea459907a019d32b8e145c3ed87c66c37af
[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 <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/types.h>
29
30 #include "libusbi.h"
31
32 #if defined(OS_LINUX)
33 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
34 #elif defined(OS_DARWIN)
35 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
36 #elif defined(OS_WINDOWS)
37 const struct usbi_os_backend * const usbi_backend = &windows_backend;
38 #else
39 #error "Unsupported OS"
40 #endif
41
42 struct libusb_context *usbi_default_context = NULL;
43 static int default_context_refcnt = 0;
44 static usbi_mutex_static_t default_context_lock = USBI_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 earlycomp Early transfer completion
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  * When a transfer completes early (i.e. when less data is received/sent in
248  * any one packet than the transfer buffer allows for) then libusb is designed
249  * to terminate the transfer immediately, not transferring or receiving any
250  * more data unless other transfers have been queued by the user.
251  *
252  * On legacy platforms, libusb is unable to do this in all situations. After
253  * the incomplete packet occurs, "surplus" data may be transferred. Prior to
254  * libusb v1.0.2, this information was lost (and for device-to-host transfers,
255  * the corresponding data was discarded). As of libusb v1.0.3, this information
256  * is kept (the data length of the transfer is updated) and, for device-to-host
257  * transfers, any surplus data was added to the buffer. Still, this is not
258  * a nice solution because it loses the information about the end of the short
259  * packet, and the user probably wanted that surplus data to arrive in the next
260  * logical transfer.
261  *
262  * A previous workaround was to only ever submit transfers of size 16kb or
263  * less.
264  *
265  * As of libusb v1.0.4 and Linux v2.6.32, this is fixed. A technical
266  * explanation of this issue follows.
267  *
268  * When you ask libusb to submit a bulk transfer larger than 16kb in size,
269  * libusb breaks it up into a number of smaller subtransfers. This is because
270  * the usbfs kernel interface only accepts transfers of up to 16kb in size.
271  * The subtransfers are submitted all at once so that the kernel can queue
272  * them at the hardware level, therefore maximizing bus throughput.
273  *
274  * On legacy platforms, this caused problems when transfers completed early.
275  * Upon this event, the kernel would terminate all further packets in that
276  * subtransfer (but not any following ones). libusb would note this event and
277  * immediately cancel any following subtransfers that had been queued,
278  * but often libusb was not fast enough, and the following subtransfers had
279  * started before libusb got around to cancelling them.
280  *
281  * Thanks to an API extension to usbfs, this is fixed with recent kernel and
282  * libusb releases. The solution was to allow libusb to communicate to the
283  * kernel where boundaries occur between logical libusb-level transfers. When
284  * a short transfer (or other error) occurs, the kernel will cancel all the
285  * subtransfers until the boundary without allowing those transfers to start.
286  */
287
288 /**
289  * \page contexts Contexts
290  *
291  * It is possible that libusb may be used simultaneously from two independent
292  * libraries linked into the same executable. For example, if your application
293  * has a plugin-like system which allows the user to dynamically load a range
294  * of modules into your program, it is feasible that two independently
295  * developed modules may both use libusb.
296  *
297  * libusb is written to allow for these multiple user scenarios. The two
298  * "instances" of libusb will not interfere: libusb_set_debug() calls
299  * from one user will not affect the same settings for other users, other
300  * users can continue using libusb after one of them calls libusb_exit(), etc.
301  *
302  * This is made possible through libusb's <em>context</em> concept. When you
303  * call libusb_init(), you are (optionally) given a context. You can then pass
304  * this context pointer back into future libusb functions.
305  *
306  * In order to keep things simple for more simplistic applications, it is
307  * legal to pass NULL to all functions requiring a context pointer (as long as
308  * you're sure no other code will attempt to use libusb from the same process).
309  * When you pass NULL, the default context will be used. The default context
310  * is created the first time a process calls libusb_init() when no other
311  * context is alive. Contexts are destroyed during libusb_exit().
312  *
313  * The default context is reference-counted and can be shared. That means that
314  * if libusb_init(NULL) is called twice within the same process, the two
315  * users end up sharing the same context. The deinitialization and freeing of
316  * the default context will only happen when the last user calls libusb_exit().
317  * In other words, the default context is created and initialized when its
318  * reference count goes from 0 to 1, and is deinitialized and destroyed when
319  * its reference count goes from 1 to 0.
320  *
321  * You may be wondering why only a subset of libusb functions require a
322  * context pointer in their function definition. Internally, libusb stores
323  * context pointers in other objects (e.g. libusb_device instances) and hence
324  * can infer the context from those objects.
325  */
326
327 /**
328  * @defgroup lib Library initialization/deinitialization
329  * This page details how to initialize and deinitialize libusb. Initialization
330  * must be performed before using any libusb functionality, and similarly you
331  * must not call any libusb functions after deinitialization.
332  */
333
334 /**
335  * @defgroup dev Device handling and enumeration
336  * The functionality documented below is designed to help with the following
337  * operations:
338  * - Enumerating the USB devices currently attached to the system
339  * - Choosing a device to operate from your software
340  * - Opening and closing the chosen device
341  *
342  * \section nutshell In a nutshell...
343  *
344  * The description below really makes things sound more complicated than they
345  * actually are. The following sequence of function calls will be suitable
346  * for almost all scenarios and does not require you to have such a deep
347  * understanding of the resource management issues:
348  * \code
349 // discover devices
350 libusb_device **list;
351 libusb_device *found = NULL;
352 ssize_t cnt = libusb_get_device_list(NULL, &list);
353 ssize_t i = 0;
354 int err = 0;
355 if (cnt < 0)
356         error();
357
358 for (i = 0; i < cnt; i++) {
359         libusb_device *device = list[i];
360         if (is_interesting(device)) {
361                 found = device;
362                 break;
363         }
364 }
365
366 if (found) {
367         libusb_device_handle *handle;
368
369         err = libusb_open(found, &handle);
370         if (err)
371                 error();
372         // etc
373 }
374
375 libusb_free_device_list(list, 1);
376 \endcode
377  *
378  * The two important points:
379  * - You asked libusb_free_device_list() to unreference the devices (2nd
380  *   parameter)
381  * - You opened the device before freeing the list and unreferencing the
382  *   devices
383  *
384  * If you ended up with a handle, you can now proceed to perform I/O on the
385  * device.
386  *
387  * \section devshandles Devices and device handles
388  * libusb has a concept of a USB device, represented by the
389  * \ref libusb_device opaque type. A device represents a USB device that
390  * is currently or was previously connected to the system. Using a reference
391  * to a device, you can determine certain information about the device (e.g.
392  * you can read the descriptor data).
393  *
394  * The libusb_get_device_list() function can be used to obtain a list of
395  * devices currently connected to the system. This is known as device
396  * discovery.
397  *
398  * Just because you have a reference to a device does not mean it is
399  * necessarily usable. The device may have been unplugged, you may not have
400  * permission to operate such device, or another program or driver may be
401  * using the device.
402  *
403  * When you've found a device that you'd like to operate, you must ask
404  * libusb to open the device using the libusb_open() function. Assuming
405  * success, libusb then returns you a <em>device handle</em>
406  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
407  * operate on the handle rather than the original device pointer.
408  *
409  * \section devref Device discovery and reference counting
410  *
411  * Device discovery (i.e. calling libusb_get_device_list()) returns a
412  * freshly-allocated list of devices. The list itself must be freed when
413  * you are done with it. libusb also needs to know when it is OK to free
414  * the contents of the list - the devices themselves.
415  *
416  * To handle these issues, libusb provides you with two separate items:
417  * - A function to free the list itself
418  * - A reference counting system for the devices inside
419  *
420  * New devices presented by the libusb_get_device_list() function all have a
421  * reference count of 1. You can increase and decrease reference count using
422  * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
423  * its reference count reaches 0.
424  *
425  * With the above information in mind, the process of opening a device can
426  * be viewed as follows:
427  * -# Discover devices using libusb_get_device_list().
428  * -# Choose the device that you want to operate, and call libusb_open().
429  * -# Unref all devices in the discovered device list.
430  * -# Free the discovered device list.
431  *
432  * The order is important - you must not unreference the device before
433  * attempting to open it, because unreferencing it may destroy the device.
434  *
435  * For convenience, the libusb_free_device_list() function includes a
436  * parameter to optionally unreference all the devices in the list before
437  * freeing the list itself. This combines steps 3 and 4 above.
438  *
439  * As an implementation detail, libusb_open() actually adds a reference to
440  * the device in question. This is because the device remains available
441  * through the handle via libusb_get_device(). The reference is deleted during
442  * libusb_close().
443  */
444
445 /** @defgroup misc Miscellaneous */
446
447 /* we traverse usbfs without knowing how many devices we are going to find.
448  * so we create this discovered_devs model which is similar to a linked-list
449  * which grows when required. it can be freed once discovery has completed,
450  * eliminating the need for a list node in the libusb_device structure
451  * itself. */
452 #define DISCOVERED_DEVICES_SIZE_STEP 8
453
454 static struct discovered_devs *discovered_devs_alloc(void)
455 {
456         struct discovered_devs *ret =
457                 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
458
459         if (ret) {
460                 ret->len = 0;
461                 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
462         }
463         return ret;
464 }
465
466 /* append a device to the discovered devices collection. may realloc itself,
467  * returning new discdevs. returns NULL on realloc failure. */
468 struct discovered_devs *discovered_devs_append(
469         struct discovered_devs *discdevs, struct libusb_device *dev)
470 {
471         size_t len = discdevs->len;
472         size_t capacity;
473
474         /* if there is space, just append the device */
475         if (len < discdevs->capacity) {
476                 discdevs->devices[len] = libusb_ref_device(dev);
477                 discdevs->len++;
478                 return discdevs;
479         }
480
481         /* exceeded capacity, need to grow */
482         usbi_dbg("need to increase capacity");
483         capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
484         discdevs = realloc(discdevs,
485                 sizeof(*discdevs) + (sizeof(void *) * capacity));
486         if (discdevs) {
487                 discdevs->capacity = capacity;
488                 discdevs->devices[len] = libusb_ref_device(dev);
489                 discdevs->len++;
490         }
491
492         return discdevs;
493 }
494
495 static void discovered_devs_free(struct discovered_devs *discdevs)
496 {
497         size_t i;
498
499         for (i = 0; i < discdevs->len; i++)
500                 libusb_unref_device(discdevs->devices[i]);
501
502         free(discdevs);
503 }
504
505 /* Allocate a new device with a specific session ID. The returned device has
506  * a reference count of 1. */
507 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
508         unsigned long session_id)
509 {
510         size_t priv_size = usbi_backend->device_priv_size;
511         struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
512         int r;
513
514         if (!dev)
515                 return NULL;
516
517         r = usbi_mutex_init(&dev->lock, NULL);
518         if (r) {
519                 free(dev);
520                 return NULL;
521         }
522
523         dev->ctx = ctx;
524         dev->refcnt = 1;
525         dev->session_data = session_id;
526         dev->speed = LIBUSB_SPEED_UNKNOWN;
527         memset(&dev->os_priv, 0, priv_size);
528
529         usbi_mutex_lock(&ctx->usb_devs_lock);
530         list_add(&dev->list, &ctx->usb_devs);
531         usbi_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 (0 == num_configurations)
554                 usbi_dbg("zero configurations, maybe an unauthorized device");
555
556         dev->num_configurations = num_configurations;
557         return 0;
558 }
559
560 /* Examine libusb's internal list of known devices, looking for one with
561  * a specific session ID. Returns the matching device if it was found, and
562  * NULL otherwise. */
563 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
564         unsigned long session_id)
565 {
566         struct libusb_device *dev;
567         struct libusb_device *ret = NULL;
568
569         usbi_mutex_lock(&ctx->usb_devs_lock);
570         list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
571                 if (dev->session_data == session_id) {
572                         ret = dev;
573                         break;
574                 }
575         usbi_mutex_unlock(&ctx->usb_devs_lock);
576
577         return ret;
578 }
579
580 /** @ingroup dev
581  * Returns a list of USB devices currently attached to the system. This is
582  * your entry point into finding a USB device to operate.
583  *
584  * You are expected to unreference all the devices when you are done with
585  * them, and then free the list with libusb_free_device_list(). Note that
586  * libusb_free_device_list() can unref all the devices for you. Be careful
587  * not to unreference a device you are about to open until after you have
588  * opened it.
589  *
590  * This return value of this function indicates the number of devices in
591  * the resultant list. The list is actually one element larger, as it is
592  * NULL-terminated.
593  *
594  * \param ctx the context to operate on, or NULL for the default context
595  * \param list output location for a list of devices. Must be later freed with
596  * libusb_free_device_list().
597  * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
598  * on memory allocation failure.
599  */
600 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
601         libusb_device ***list)
602 {
603         struct discovered_devs *discdevs = discovered_devs_alloc();
604         struct libusb_device **ret;
605         int r = 0;
606         ssize_t i, len;
607         USBI_GET_CONTEXT(ctx);
608         usbi_dbg("");
609
610         if (!discdevs)
611                 return LIBUSB_ERROR_NO_MEM;
612
613         r = usbi_backend->get_device_list(ctx, &discdevs);
614         if (r < 0) {
615                 len = r;
616                 goto out;
617         }
618
619         /* convert discovered_devs into a list */
620         len = discdevs->len;
621         ret = malloc(sizeof(void *) * (len + 1));
622         if (!ret) {
623                 len = LIBUSB_ERROR_NO_MEM;
624                 goto out;
625         }
626
627         ret[len] = NULL;
628         for (i = 0; i < len; i++) {
629                 struct libusb_device *dev = discdevs->devices[i];
630                 ret[i] = libusb_ref_device(dev);
631         }
632         *list = ret;
633
634 out:
635         discovered_devs_free(discdevs);
636         return len;
637 }
638
639 /** \ingroup dev
640  * Frees a list of devices previously discovered using
641  * libusb_get_device_list(). If the unref_devices parameter is set, the
642  * reference count of each device in the list is decremented by 1.
643  * \param list the list to free
644  * \param unref_devices whether to unref the devices in the list
645  */
646 void API_EXPORTED libusb_free_device_list(libusb_device **list,
647         int unref_devices)
648 {
649         if (!list)
650                 return;
651
652         if (unref_devices) {
653                 int i = 0;
654                 struct libusb_device *dev;
655
656                 while ((dev = list[i++]) != NULL)
657                         libusb_unref_device(dev);
658         }
659         free(list);
660 }
661
662 /** \ingroup dev
663  * Get the number of the bus that a device is connected to.
664  * \param dev a device
665  * \returns the bus number
666  */
667 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
668 {
669         return dev->bus_number;
670 }
671
672 /** \ingroup dev
673  * Get the address of the device on the bus it is connected to.
674  * \param dev a device
675  * \returns the device address
676  */
677 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
678 {
679         return dev->device_address;
680 }
681
682 /** \ingroup dev
683  * Get the negotiated connection speed for a device.
684  * \param dev a device
685  * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
686  * the OS doesn't know or doesn't support returning the negotiated speed.
687  */
688 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
689 {
690         return dev->speed;
691 }
692
693 static const struct libusb_endpoint_descriptor *find_endpoint(
694         struct libusb_config_descriptor *config, unsigned char endpoint)
695 {
696         int iface_idx;
697         for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
698                 const struct libusb_interface *iface = &config->interface[iface_idx];
699                 int altsetting_idx;
700
701                 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
702                                 altsetting_idx++) {
703                         const struct libusb_interface_descriptor *altsetting
704                                 = &iface->altsetting[altsetting_idx];
705                         int ep_idx;
706
707                         for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
708                                 const struct libusb_endpoint_descriptor *ep =
709                                         &altsetting->endpoint[ep_idx];
710                                 if (ep->bEndpointAddress == endpoint)
711                                         return ep;
712                         }
713                 }
714         }
715         return NULL;
716 }
717
718 /** \ingroup dev
719  * Convenience function to retrieve the wMaxPacketSize value for a particular
720  * endpoint in the active device configuration.
721  *
722  * This function was originally intended to be of assistance when setting up
723  * isochronous transfers, but a design mistake resulted in this function
724  * instead. It simply returns the wMaxPacketSize value without considering
725  * its contents. If you're dealing with isochronous transfers, you probably
726  * want libusb_get_max_iso_packet_size() instead.
727  *
728  * \param dev a device
729  * \param endpoint address of the endpoint in question
730  * \returns the wMaxPacketSize value
731  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
732  * \returns LIBUSB_ERROR_OTHER on other failure
733  */
734 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
735         unsigned char endpoint)
736 {
737         struct libusb_config_descriptor *config;
738         const struct libusb_endpoint_descriptor *ep;
739         int r;
740
741         r = libusb_get_active_config_descriptor(dev, &config);
742         if (r < 0) {
743                 usbi_err(DEVICE_CTX(dev),
744                         "could not retrieve active config descriptor");
745                 return LIBUSB_ERROR_OTHER;
746         }
747
748         ep = find_endpoint(config, endpoint);
749         if (!ep)
750                 return LIBUSB_ERROR_NOT_FOUND;
751
752         r = ep->wMaxPacketSize;
753         libusb_free_config_descriptor(config);
754         return r;
755 }
756
757 /** \ingroup dev
758  * Calculate the maximum packet size which a specific endpoint is capable is
759  * sending or receiving in the duration of 1 microframe
760  *
761  * Only the active configution is examined. The calculation is based on the
762  * wMaxPacketSize field in the endpoint descriptor as described in section
763  * 9.6.6 in the USB 2.0 specifications.
764  *
765  * If acting on an isochronous or interrupt endpoint, this function will
766  * multiply the value found in bits 0:10 by the number of transactions per
767  * microframe (determined by bits 11:12). Otherwise, this function just
768  * returns the numeric value found in bits 0:10.
769  *
770  * This function is useful for setting up isochronous transfers, for example
771  * you might pass the return value from this function to
772  * libusb_set_iso_packet_lengths() in order to set the length field of every
773  * isochronous packet in a transfer.
774  *
775  * Since v1.0.3.
776  *
777  * \param dev a device
778  * \param endpoint address of the endpoint in question
779  * \returns the maximum packet size which can be sent/received on this endpoint
780  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
781  * \returns LIBUSB_ERROR_OTHER on other failure
782  */
783 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
784         unsigned char endpoint)
785 {
786         struct libusb_config_descriptor *config;
787         const struct libusb_endpoint_descriptor *ep;
788         enum libusb_transfer_type ep_type;
789         uint16_t val;
790         int r;
791
792         r = libusb_get_active_config_descriptor(dev, &config);
793         if (r < 0) {
794                 usbi_err(DEVICE_CTX(dev),
795                         "could not retrieve active config descriptor");
796                 return LIBUSB_ERROR_OTHER;
797         }
798
799         ep = find_endpoint(config, endpoint);
800         if (!ep)
801                 return LIBUSB_ERROR_NOT_FOUND;
802
803         val = ep->wMaxPacketSize;
804         ep_type = ep->bmAttributes & 0x3;
805         libusb_free_config_descriptor(config);
806
807         r = val & 0x07ff;
808         if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
809                         || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
810                 r *= (1 + ((val >> 11) & 3));
811         return r;
812 }
813
814 /** \ingroup dev
815  * Increment the reference count of a device.
816  * \param dev the device to reference
817  * \returns the same device
818  */
819 DEFAULT_VISIBILITY
820 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
821 {
822         usbi_mutex_lock(&dev->lock);
823         dev->refcnt++;
824         usbi_mutex_unlock(&dev->lock);
825         return dev;
826 }
827
828 /** \ingroup dev
829  * Decrement the reference count of a device. If the decrement operation
830  * causes the reference count to reach zero, the device shall be destroyed.
831  * \param dev the device to unreference
832  */
833 void API_EXPORTED libusb_unref_device(libusb_device *dev)
834 {
835         int refcnt;
836
837         if (!dev)
838                 return;
839
840         usbi_mutex_lock(&dev->lock);
841         refcnt = --dev->refcnt;
842         usbi_mutex_unlock(&dev->lock);
843
844         if (refcnt == 0) {
845                 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
846
847                 if (usbi_backend->destroy_device)
848                         usbi_backend->destroy_device(dev);
849
850                 usbi_mutex_lock(&dev->ctx->usb_devs_lock);
851                 list_del(&dev->list);
852                 usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
853
854                 usbi_mutex_destroy(&dev->lock);
855                 free(dev);
856         }
857 }
858
859 /*
860  * Interrupt the iteration of the event handling thread, so that it picks
861  * up the new fd.
862  */
863 void usbi_fd_notification(struct libusb_context *ctx)
864 {
865         unsigned char dummy = 1;
866         ssize_t r;
867
868         if (ctx == NULL)
869                 return;
870
871         /* record that we are messing with poll fds */
872         usbi_mutex_lock(&ctx->pollfd_modify_lock);
873         ctx->pollfd_modify++;
874         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
875
876         /* write some data on control pipe to interrupt event handlers */
877         r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
878         if (r <= 0) {
879                 usbi_warn(ctx, "internal signalling write failed");
880                 usbi_mutex_lock(&ctx->pollfd_modify_lock);
881                 ctx->pollfd_modify--;
882                 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
883                 return;
884         }
885
886         /* take event handling lock */
887         libusb_lock_events(ctx);
888
889         /* read the dummy data */
890         r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
891         if (r <= 0)
892                 usbi_warn(ctx, "internal signalling read failed");
893
894         /* we're done with modifying poll fds */
895         usbi_mutex_lock(&ctx->pollfd_modify_lock);
896         ctx->pollfd_modify--;
897         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
898
899         /* Release event handling lock and wake up event waiters */
900         libusb_unlock_events(ctx);
901 }
902
903 /** \ingroup dev
904  * Open a device and obtain a device handle. A handle allows you to perform
905  * I/O on the device in question.
906  *
907  * Internally, this function adds a reference to the device and makes it
908  * available to you through libusb_get_device(). This reference is removed
909  * during libusb_close().
910  *
911  * This is a non-blocking function; no requests are sent over the bus.
912  *
913  * \param dev the device to open
914  * \param handle output location for the returned device handle pointer. Only
915  * populated when the return code is 0.
916  * \returns 0 on success
917  * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
918  * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
919  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
920  * \returns another LIBUSB_ERROR code on other failure
921  */
922 int API_EXPORTED libusb_open(libusb_device *dev,
923         libusb_device_handle **handle)
924 {
925         struct libusb_context *ctx = DEVICE_CTX(dev);
926         struct libusb_device_handle *_handle;
927         size_t priv_size = usbi_backend->device_handle_priv_size;
928         int r;
929         usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
930
931         _handle = malloc(sizeof(*_handle) + priv_size);
932         if (!_handle)
933                 return LIBUSB_ERROR_NO_MEM;
934
935         r = usbi_mutex_init(&_handle->lock, NULL);
936         if (r) {
937                 free(_handle);
938                 return LIBUSB_ERROR_OTHER;
939         }
940
941         _handle->dev = libusb_ref_device(dev);
942         _handle->claimed_interfaces = 0;
943         memset(&_handle->os_priv, 0, priv_size);
944
945         r = usbi_backend->open(_handle);
946         if (r < 0) {
947                 usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
948                 libusb_unref_device(dev);
949                 usbi_mutex_destroy(&_handle->lock);
950                 free(_handle);
951                 return r;
952         }
953
954         usbi_mutex_lock(&ctx->open_devs_lock);
955         list_add(&_handle->list, &ctx->open_devs);
956         usbi_mutex_unlock(&ctx->open_devs_lock);
957         *handle = _handle;
958
959         /* At this point, we want to interrupt any existing event handlers so
960          * that they realise the addition of the new device's poll fd. One
961          * example when this is desirable is if the user is running a separate
962          * dedicated libusb events handling thread, which is running with a long
963          * or infinite timeout. We want to interrupt that iteration of the loop,
964          * so that it picks up the new fd, and then continues. */
965         usbi_fd_notification(ctx);
966
967         return 0;
968 }
969
970 /** \ingroup dev
971  * Convenience function for finding a device with a particular
972  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
973  * for those scenarios where you are using libusb to knock up a quick test
974  * application - it allows you to avoid calling libusb_get_device_list() and
975  * worrying about traversing/freeing the list.
976  *
977  * This function has limitations and is hence not intended for use in real
978  * applications: if multiple devices have the same IDs it will only
979  * give you the first one, etc.
980  *
981  * \param ctx the context to operate on, or NULL for the default context
982  * \param vendor_id the idVendor value to search for
983  * \param product_id the idProduct value to search for
984  * \returns a handle for the first found device, or NULL on error or if the
985  * device could not be found. */
986 DEFAULT_VISIBILITY
987 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
988         libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
989 {
990         struct libusb_device **devs;
991         struct libusb_device *found = NULL;
992         struct libusb_device *dev;
993         struct libusb_device_handle *handle = NULL;
994         size_t i = 0;
995         int r;
996
997         if (libusb_get_device_list(ctx, &devs) < 0)
998                 return NULL;
999
1000         while ((dev = devs[i++]) != NULL) {
1001                 struct libusb_device_descriptor desc;
1002                 r = libusb_get_device_descriptor(dev, &desc);
1003                 if (r < 0)
1004                         goto out;
1005                 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1006                         found = dev;
1007                         break;
1008                 }
1009         }
1010
1011         if (found) {
1012                 r = libusb_open(found, &handle);
1013                 if (r < 0)
1014                         handle = NULL;
1015         }
1016
1017 out:
1018         libusb_free_device_list(devs, 1);
1019         return handle;
1020 }
1021
1022 static void do_close(struct libusb_context *ctx,
1023         struct libusb_device_handle *dev_handle)
1024 {
1025         struct usbi_transfer *itransfer;
1026         struct usbi_transfer *tmp;
1027
1028         libusb_lock_events(ctx);
1029
1030         /* remove any transfers in flight that are for this device */
1031         usbi_mutex_lock(&ctx->flying_transfers_lock);
1032
1033         /* safe iteration because transfers may be being deleted */
1034         list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
1035                 struct libusb_transfer *transfer =
1036                         USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1037
1038                 if (transfer->dev_handle != dev_handle)
1039                         continue;
1040
1041                 if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1042                         usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1043
1044                         if (itransfer->flags & USBI_TRANSFER_CANCELLING)
1045                                 usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1046                         else
1047                                 usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1048                 }
1049
1050                 /* remove from the list of in-flight transfers and make sure
1051                  * we don't accidentally use the device handle in the future
1052                  * (or that such accesses will be easily caught and identified as a crash)
1053                  */
1054                 usbi_mutex_lock(&itransfer->lock);
1055                 list_del(&itransfer->list);
1056                 transfer->dev_handle = NULL;
1057                 usbi_mutex_unlock(&itransfer->lock);
1058
1059                 /* it is up to the user to free up the actual transfer struct.  this is
1060                  * just making sure that we don't attempt to process the transfer after
1061                  * the device handle is invalid
1062                  */
1063                 usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
1064                          transfer, dev_handle);
1065         }
1066         usbi_mutex_unlock(&ctx->flying_transfers_lock);
1067
1068         libusb_unlock_events(ctx);
1069
1070         usbi_mutex_lock(&ctx->open_devs_lock);
1071         list_del(&dev_handle->list);
1072         usbi_mutex_unlock(&ctx->open_devs_lock);
1073
1074         usbi_backend->close(dev_handle);
1075         libusb_unref_device(dev_handle->dev);
1076         usbi_mutex_destroy(&dev_handle->lock);
1077         free(dev_handle);
1078 }
1079
1080 /** \ingroup dev
1081  * Close a device handle. Should be called on all open handles before your
1082  * application exits.
1083  *
1084  * Internally, this function destroys the reference that was added by
1085  * libusb_open() on the given device.
1086  *
1087  * This is a non-blocking function; no requests are sent over the bus.
1088  *
1089  * \param dev_handle the handle to close
1090  */
1091 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1092 {
1093         struct libusb_context *ctx;
1094         unsigned char dummy = 1;
1095         ssize_t r;
1096
1097         if (!dev_handle)
1098                 return;
1099         usbi_dbg("");
1100
1101         ctx = HANDLE_CTX(dev_handle);
1102
1103         /* Similarly to libusb_open(), we want to interrupt all event handlers
1104          * at this point. More importantly, we want to perform the actual close of
1105          * the device while holding the event handling lock (preventing any other
1106          * thread from doing event handling) because we will be removing a file
1107          * descriptor from the polling loop. */
1108
1109         /* record that we are messing with poll fds */
1110         usbi_mutex_lock(&ctx->pollfd_modify_lock);
1111         ctx->pollfd_modify++;
1112         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1113
1114         /* write some data on control pipe to interrupt event handlers */
1115         r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1116         if (r <= 0) {
1117                 usbi_warn(ctx, "internal signalling write failed, closing anyway");
1118                 do_close(ctx, dev_handle);
1119                 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1120                 ctx->pollfd_modify--;
1121                 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1122                 return;
1123         }
1124
1125         /* take event handling lock */
1126         libusb_lock_events(ctx);
1127
1128         /* read the dummy data */
1129         r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1130         if (r <= 0)
1131                 usbi_warn(ctx, "internal signalling read failed, closing anyway");
1132
1133         /* Close the device */
1134         do_close(ctx, dev_handle);
1135
1136         /* we're done with modifying poll fds */
1137         usbi_mutex_lock(&ctx->pollfd_modify_lock);
1138         ctx->pollfd_modify--;
1139         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1140
1141         /* Release event handling lock and wake up event waiters */
1142         libusb_unlock_events(ctx);
1143 }
1144
1145 /** \ingroup dev
1146  * Get the underlying device for a handle. This function does not modify
1147  * the reference count of the returned device, so do not feel compelled to
1148  * unreference it when you are done.
1149  * \param dev_handle a device handle
1150  * \returns the underlying device
1151  */
1152 DEFAULT_VISIBILITY
1153 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1154 {
1155         return dev_handle->dev;
1156 }
1157
1158 /** \ingroup dev
1159  * Determine the bConfigurationValue of the currently active configuration.
1160  *
1161  * You could formulate your own control request to obtain this information,
1162  * but this function has the advantage that it may be able to retrieve the
1163  * information from operating system caches (no I/O involved).
1164  *
1165  * If the OS does not cache this information, then this function will block
1166  * while a control transfer is submitted to retrieve the information.
1167  *
1168  * This function will return a value of 0 in the <tt>config</tt> output
1169  * parameter if the device is in unconfigured state.
1170  *
1171  * \param dev a device handle
1172  * \param config output location for the bConfigurationValue of the active
1173  * configuration (only valid for return code 0)
1174  * \returns 0 on success
1175  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1176  * \returns another LIBUSB_ERROR code on other failure
1177  */
1178 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
1179         int *config)
1180 {
1181         int r = LIBUSB_ERROR_NOT_SUPPORTED;
1182
1183         usbi_dbg("");
1184         if (usbi_backend->get_configuration)
1185                 r = usbi_backend->get_configuration(dev, config);
1186
1187         if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1188                 uint8_t tmp = 0;
1189                 usbi_dbg("falling back to control message");
1190                 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1191                         LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1192                 if (r == 0) {
1193                         usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
1194                         r = LIBUSB_ERROR_IO;
1195                 } else if (r == 1) {
1196                         r = 0;
1197                         *config = tmp;
1198                 } else {
1199                         usbi_dbg("control failed, error %d", r);
1200                 }
1201         }
1202
1203         if (r == 0)
1204                 usbi_dbg("active config %d", *config);
1205
1206         return r;
1207 }
1208
1209 /** \ingroup dev
1210  * Set the active configuration for a device.
1211  *
1212  * The operating system may or may not have already set an active
1213  * configuration on the device. It is up to your application to ensure the
1214  * correct configuration is selected before you attempt to claim interfaces
1215  * and perform other operations.
1216  *
1217  * If you call this function on a device already configured with the selected
1218  * configuration, then this function will act as a lightweight device reset:
1219  * it will issue a SET_CONFIGURATION request using the current configuration,
1220  * causing most USB-related device state to be reset (altsetting reset to zero,
1221  * endpoint halts cleared, toggles reset).
1222  *
1223  * You cannot change/reset configuration if your application has claimed
1224  * interfaces - you should free them with libusb_release_interface() first.
1225  * You cannot change/reset configuration if other applications or drivers have
1226  * claimed interfaces.
1227  *
1228  * A configuration value of -1 will put the device in unconfigured state.
1229  * The USB specifications state that a configuration value of 0 does this,
1230  * however buggy devices exist which actually have a configuration 0.
1231  *
1232  * You should always use this function rather than formulating your own
1233  * SET_CONFIGURATION control request. This is because the underlying operating
1234  * system needs to know when such changes happen.
1235  *
1236  * This is a blocking function.
1237  *
1238  * \param dev a device handle
1239  * \param configuration the bConfigurationValue of the configuration you
1240  * wish to activate, or -1 if you wish to put the device in unconfigured state
1241  * \returns 0 on success
1242  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1243  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1244  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1245  * \returns another LIBUSB_ERROR code on other failure
1246  */
1247 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
1248         int configuration)
1249 {
1250         usbi_dbg("configuration %d", configuration);
1251         return usbi_backend->set_configuration(dev, configuration);
1252 }
1253
1254 /** \ingroup dev
1255  * Claim an interface on a given device handle. You must claim the interface
1256  * you wish to use before you can perform I/O on any of its endpoints.
1257  *
1258  * It is legal to attempt to claim an already-claimed interface, in which
1259  * case libusb just returns 0 without doing anything.
1260  *
1261  * Claiming of interfaces is a purely logical operation; it does not cause
1262  * any requests to be sent over the bus. Interface claiming is used to
1263  * instruct the underlying operating system that your application wishes
1264  * to take ownership of the interface.
1265  *
1266  * This is a non-blocking function.
1267  *
1268  * \param dev a device handle
1269  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1270  * wish to claim
1271  * \returns 0 on success
1272  * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1273  * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1274  * interface
1275  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1276  * \returns a LIBUSB_ERROR code on other failure
1277  */
1278 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
1279         int interface_number)
1280 {
1281         int r = 0;
1282
1283         usbi_dbg("interface %d", interface_number);
1284         if (interface_number >= USB_MAXINTERFACES)
1285                 return LIBUSB_ERROR_INVALID_PARAM;
1286
1287         usbi_mutex_lock(&dev->lock);
1288         if (dev->claimed_interfaces & (1 << interface_number))
1289                 goto out;
1290
1291         r = usbi_backend->claim_interface(dev, interface_number);
1292         if (r == 0)
1293                 dev->claimed_interfaces |= 1 << interface_number;
1294
1295 out:
1296         usbi_mutex_unlock(&dev->lock);
1297         return r;
1298 }
1299
1300 /** \ingroup dev
1301  * Release an interface previously claimed with libusb_claim_interface(). You
1302  * should release all claimed interfaces before closing a device handle.
1303  *
1304  * This is a blocking function. A SET_INTERFACE control request will be sent
1305  * to the device, resetting interface state to the first alternate setting.
1306  *
1307  * \param dev a device handle
1308  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1309  * previously-claimed interface
1310  * \returns 0 on success
1311  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1312  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1313  * \returns another LIBUSB_ERROR code on other failure
1314  */
1315 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
1316         int interface_number)
1317 {
1318         int r;
1319
1320         usbi_dbg("interface %d", interface_number);
1321         if (interface_number >= USB_MAXINTERFACES)
1322                 return LIBUSB_ERROR_INVALID_PARAM;
1323
1324         usbi_mutex_lock(&dev->lock);
1325         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1326                 r = LIBUSB_ERROR_NOT_FOUND;
1327                 goto out;
1328         }
1329
1330         r = usbi_backend->release_interface(dev, interface_number);
1331         if (r == 0)
1332                 dev->claimed_interfaces &= ~(1 << interface_number);
1333
1334 out:
1335         usbi_mutex_unlock(&dev->lock);
1336         return r;
1337 }
1338
1339 /** \ingroup dev
1340  * Activate an alternate setting for an interface. The interface must have
1341  * been previously claimed with libusb_claim_interface().
1342  *
1343  * You should always use this function rather than formulating your own
1344  * SET_INTERFACE control request. This is because the underlying operating
1345  * system needs to know when such changes happen.
1346  *
1347  * This is a blocking function.
1348  *
1349  * \param dev a device handle
1350  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1351  * previously-claimed interface
1352  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1353  * setting to activate
1354  * \returns 0 on success
1355  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1356  * requested alternate setting does not exist
1357  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1358  * \returns another LIBUSB_ERROR code on other failure
1359  */
1360 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
1361         int interface_number, int alternate_setting)
1362 {
1363         usbi_dbg("interface %d altsetting %d",
1364                 interface_number, alternate_setting);
1365         if (interface_number >= USB_MAXINTERFACES)
1366                 return LIBUSB_ERROR_INVALID_PARAM;
1367
1368         usbi_mutex_lock(&dev->lock);
1369         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1370                 usbi_mutex_unlock(&dev->lock);
1371                 return LIBUSB_ERROR_NOT_FOUND;
1372         }
1373         usbi_mutex_unlock(&dev->lock);
1374
1375         return usbi_backend->set_interface_altsetting(dev, interface_number,
1376                 alternate_setting);
1377 }
1378
1379 /** \ingroup dev
1380  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1381  * are unable to receive or transmit data until the halt condition is stalled.
1382  *
1383  * You should cancel all pending transfers before attempting to clear the halt
1384  * condition.
1385  *
1386  * This is a blocking function.
1387  *
1388  * \param dev a device handle
1389  * \param endpoint the endpoint to clear halt status
1390  * \returns 0 on success
1391  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1392  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1393  * \returns another LIBUSB_ERROR code on other failure
1394  */
1395 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
1396         unsigned char endpoint)
1397 {
1398         usbi_dbg("endpoint %x", endpoint);
1399         return usbi_backend->clear_halt(dev, endpoint);
1400 }
1401
1402 /** \ingroup dev
1403  * Perform a USB port reset to reinitialize a device. The system will attempt
1404  * to restore the previous configuration and alternate settings after the
1405  * reset has completed.
1406  *
1407  * If the reset fails, the descriptors change, or the previous state cannot be
1408  * restored, the device will appear to be disconnected and reconnected. This
1409  * means that the device handle is no longer valid (you should close it) and
1410  * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1411  * when this is the case.
1412  *
1413  * This is a blocking function which usually incurs a noticeable delay.
1414  *
1415  * \param dev a handle of the device to reset
1416  * \returns 0 on success
1417  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1418  * device has been disconnected
1419  * \returns another LIBUSB_ERROR code on other failure
1420  */
1421 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
1422 {
1423         usbi_dbg("");
1424         return usbi_backend->reset_device(dev);
1425 }
1426
1427 /** \ingroup dev
1428  * Determine if a kernel driver is active on an interface. If a kernel driver
1429  * is active, you cannot claim the interface, and libusb will be unable to
1430  * perform I/O.
1431  *
1432  * This functionality is not available on Windows.
1433  *
1434  * \param dev a device handle
1435  * \param interface_number the interface to check
1436  * \returns 0 if no kernel driver is active
1437  * \returns 1 if a kernel driver is active
1438  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1439  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1440  * is not available
1441  * \returns another LIBUSB_ERROR code on other failure
1442  * \see libusb_detach_kernel_driver()
1443  */
1444 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
1445         int interface_number)
1446 {
1447         usbi_dbg("interface %d", interface_number);
1448         if (usbi_backend->kernel_driver_active)
1449                 return usbi_backend->kernel_driver_active(dev, interface_number);
1450         else
1451                 return LIBUSB_ERROR_NOT_SUPPORTED;
1452 }
1453
1454 /** \ingroup dev
1455  * Detach a kernel driver from an interface. If successful, you will then be
1456  * able to claim the interface and perform I/O.
1457  *
1458  * This functionality is not available on Darwin or Windows.
1459  *
1460  * \param dev a device handle
1461  * \param interface_number the interface to detach the driver from
1462  * \returns 0 on success
1463  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1464  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1465  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1466  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1467  * is not available
1468  * \returns another LIBUSB_ERROR code on other failure
1469  * \see libusb_kernel_driver_active()
1470  */
1471 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
1472         int interface_number)
1473 {
1474         usbi_dbg("interface %d", interface_number);
1475         if (usbi_backend->detach_kernel_driver)
1476                 return usbi_backend->detach_kernel_driver(dev, interface_number);
1477         else
1478                 return LIBUSB_ERROR_NOT_SUPPORTED;
1479 }
1480
1481 /** \ingroup dev
1482  * Re-attach an interface's kernel driver, which was previously detached
1483  * using libusb_detach_kernel_driver(). This call is only effective on
1484  * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1485  *
1486  * This functionality is not available on Darwin or Windows.
1487  *
1488  * \param dev a device handle
1489  * \param interface_number the interface to attach the driver from
1490  * \returns 0 on success
1491  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1492  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1493  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1494  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1495  * is not available
1496  * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1497  * interface is claimed by a program or driver
1498  * \returns another LIBUSB_ERROR code on other failure
1499  * \see libusb_kernel_driver_active()
1500  */
1501 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
1502         int interface_number)
1503 {
1504         usbi_dbg("interface %d", interface_number);
1505         if (usbi_backend->attach_kernel_driver)
1506                 return usbi_backend->attach_kernel_driver(dev, interface_number);
1507         else
1508                 return LIBUSB_ERROR_NOT_SUPPORTED;
1509 }
1510
1511 /** \ingroup lib
1512  * Set message verbosity.
1513  *  - Level 0: no messages ever printed by the library (default)
1514  *  - Level 1: error messages are printed to stderr
1515  *  - Level 2: warning and error messages are printed to stderr
1516  *  - Level 3: informational messages are printed to stdout, warning and error
1517  *    messages are printed to stderr
1518  *
1519  * The default level is 0, which means no messages are ever printed. If you
1520  * choose to increase the message verbosity level, ensure that your
1521  * application does not close the stdout/stderr file descriptors.
1522  *
1523  * You are advised to set level 3. libusb is conservative with its message
1524  * logging and most of the time, will only log messages that explain error
1525  * conditions and other oddities. This will help you debug your software.
1526  *
1527  * If the LIBUSB_DEBUG environment variable was set when libusb was
1528  * initialized, this function does nothing: the message verbosity is fixed
1529  * to the value in the environment variable.
1530  *
1531  * If libusb was compiled without any message logging, this function does
1532  * nothing: you'll never get any messages.
1533  *
1534  * If libusb was compiled with verbose debug message logging, this function
1535  * does nothing: you'll always get messages from all levels.
1536  *
1537  * \param ctx the context to operate on, or NULL for the default context
1538  * \param level debug level to set
1539  */
1540 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
1541 {
1542         USBI_GET_CONTEXT(ctx);
1543         if (!ctx->debug_fixed)
1544                 ctx->debug = level;
1545 }
1546
1547 /** \ingroup lib
1548  * Initialize libusb. This function must be called before calling any other
1549  * libusb function.
1550  *
1551  * If you do not provide an output location for a context pointer, a default
1552  * context will be created. If there was already a default context, it will
1553  * be reused (and nothing will be initialized/reinitialized).
1554  *
1555  * \param context Optional output location for context pointer.
1556  * Only valid on return code 0.
1557  * \returns 0 on success, or a LIBUSB_ERROR code on failure
1558  * \see contexts
1559  */
1560 int API_EXPORTED libusb_init(libusb_context **context)
1561 {
1562         char *dbg = getenv("LIBUSB_DEBUG");
1563         struct libusb_context *ctx;
1564         int r;
1565
1566         usbi_mutex_static_lock(&default_context_lock);
1567         if (!context && usbi_default_context) {
1568                 r = 0;
1569                 usbi_dbg("reusing default context");
1570                 default_context_refcnt++;
1571                 usbi_mutex_static_unlock(&default_context_lock);
1572                 return 0;
1573         }
1574
1575         ctx = malloc(sizeof(*ctx));
1576         if (!ctx) {
1577                 r = LIBUSB_ERROR_NO_MEM;
1578                 goto err_unlock;
1579         }
1580         memset(ctx, 0, sizeof(*ctx));
1581
1582         if (dbg) {
1583                 ctx->debug = atoi(dbg);
1584                 if (ctx->debug)
1585                         ctx->debug_fixed = 1;
1586         }
1587
1588         usbi_dbg("");
1589
1590         if (usbi_backend->init) {
1591                 r = usbi_backend->init(ctx);
1592                 if (r)
1593                         goto err_free_ctx;
1594         }
1595
1596         usbi_mutex_init(&ctx->usb_devs_lock, NULL);
1597         usbi_mutex_init(&ctx->open_devs_lock, NULL);
1598         list_init(&ctx->usb_devs);
1599         list_init(&ctx->open_devs);
1600
1601         r = usbi_io_init(ctx);
1602         if (r < 0) {
1603                 if (usbi_backend->exit)
1604                         usbi_backend->exit();
1605                 goto err_destroy_mutex;
1606         }
1607
1608         if (context) {
1609                 *context = ctx;
1610         } else if (!usbi_default_context) {
1611                 usbi_dbg("created default context");
1612                 usbi_default_context = ctx;
1613                 default_context_refcnt++;
1614         }
1615         usbi_mutex_static_unlock(&default_context_lock);
1616
1617         return 0;
1618
1619 err_destroy_mutex:
1620         usbi_mutex_destroy(&ctx->open_devs_lock);
1621         usbi_mutex_destroy(&ctx->usb_devs_lock);
1622 err_free_ctx:
1623         free(ctx);
1624 err_unlock:
1625         usbi_mutex_static_unlock(&default_context_lock);
1626         return r;
1627 }
1628
1629 /** \ingroup lib
1630  * Deinitialize libusb. Should be called after closing all open devices and
1631  * before your application terminates.
1632  * \param ctx the context to deinitialize, or NULL for the default context
1633  */
1634 void API_EXPORTED libusb_exit(struct libusb_context *ctx)
1635 {
1636         usbi_dbg("");
1637         USBI_GET_CONTEXT(ctx);
1638
1639         /* if working with default context, only actually do the deinitialization
1640          * if we're the last user */
1641         if (ctx == usbi_default_context) {
1642                 usbi_mutex_static_lock(&default_context_lock);
1643                 if (--default_context_refcnt > 0) {
1644                         usbi_dbg("not destroying default context");
1645                         usbi_mutex_static_unlock(&default_context_lock);
1646                         return;
1647                 }
1648                 usbi_dbg("destroying default context");
1649                 usbi_default_context = NULL;
1650                 usbi_mutex_static_unlock(&default_context_lock);
1651         }
1652
1653         /* a little sanity check. doesn't bother with open_devs locking because
1654          * unless there is an application bug, nobody will be accessing this. */
1655         if (!list_empty(&ctx->open_devs))
1656                 usbi_warn(ctx, "application left some devices open");
1657
1658         usbi_io_exit(ctx);
1659         if (usbi_backend->exit)
1660                 usbi_backend->exit();
1661
1662         usbi_mutex_destroy(&ctx->open_devs_lock);
1663         usbi_mutex_destroy(&ctx->usb_devs_lock);
1664         free(ctx);
1665 }
1666
1667 void usbi_log_v(struct libusb_context *ctx, enum usbi_log_level level,
1668         const char *function, const char *format, va_list args)
1669 {
1670         FILE *stream = stdout;
1671         const char *prefix;
1672
1673 #ifndef ENABLE_DEBUG_LOGGING
1674         USBI_GET_CONTEXT(ctx);
1675         if (!ctx->debug)
1676                 return;
1677         if (level == LOG_LEVEL_WARNING && ctx->debug < 2)
1678                 return;
1679         if (level == LOG_LEVEL_INFO && ctx->debug < 3)
1680                 return;
1681 #endif
1682
1683         switch (level) {
1684         case LOG_LEVEL_INFO:
1685                 prefix = "info";
1686                 break;
1687         case LOG_LEVEL_WARNING:
1688                 stream = stderr;
1689                 prefix = "warning";
1690                 break;
1691         case LOG_LEVEL_ERROR:
1692                 stream = stderr;
1693                 prefix = "error";
1694                 break;
1695         case LOG_LEVEL_DEBUG:
1696                 stream = stderr;
1697                 prefix = "debug";
1698                 break;
1699         default:
1700                 stream = stderr;
1701                 prefix = "unknown";
1702                 break;
1703         }
1704
1705         fprintf(stream, "libusb:%s [%s] ", prefix, function);
1706
1707         vfprintf(stream, format, args);
1708
1709         fprintf(stream, "\n");
1710 }
1711
1712 void usbi_log(struct libusb_context *ctx, enum usbi_log_level level,
1713         const char *function, const char *format, ...)
1714 {
1715         va_list args;
1716
1717         va_start (args, format);
1718         usbi_log_v(ctx, level, function, format, args);
1719         va_end (args);
1720 }