2 * Core functions for libusb
3 * Copyright (C) 2007-2008 Daniel Drake <dsd@gentoo.org>
4 * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
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.
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.
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
29 #include <sys/types.h>
35 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
37 #error "Unsupported OS"
40 struct libusb_context *usbi_default_context = NULL;
41 static pthread_mutex_t default_context_lock = PTHREAD_MUTEX_INITIALIZER;
44 * \mainpage libusb-1.0 API Reference
46 * \section intro Introduction
48 * libusb is an open source library that allows you to communicate with USB
49 * devices from userspace. For more info, see the
50 * <a href="http://libusb.sourceforge.net">libusb homepage</a>.
52 * This documentation is aimed at application developers wishing to
53 * communicate with USB peripherals from their own software. After reviewing
54 * this documentation, feedback and questions can be sent to the
55 * <a href="http://sourceforge.net/mail/?group_id=1674">libusb-devel mailing
58 * This documentation assumes knowledge of how to operate USB devices from
59 * a software standpoint (descriptors, configurations, interfaces, endpoints,
60 * control/bulk/interrupt/isochronous transfers, etc). Full information
61 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 2.0
62 * Specification</a> which is available for free download. You can probably
63 * find less verbose introductions by searching the web.
65 * \section features Library features
67 * - All transfer types supported (control/bulk/interrupt/isochronous)
68 * - 2 transfer interfaces:
69 * -# Synchronous (simple)
70 * -# Asynchronous (more complicated, but more powerful)
71 * - Thread safe (although the asynchronous interface means that you
72 * usually won't need to thread)
73 * - Lightweight with lean API
74 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
76 * \section gettingstarted Getting Started
78 * To begin reading the API documentation, start with the Modules page which
79 * links to the different categories of libusb's functionality.
81 * One decision you will have to make is whether to use the synchronous
82 * or the asynchronous data transfer interface. The \ref io documentation
83 * provides some insight into this topic.
85 * Some example programs can be found in the libusb source distribution under
86 * the "examples" subdirectory. The libusb homepage includes a list of
87 * real-life project examples which use libusb.
89 * \section errorhandling Error handling
91 * libusb functions typically return 0 on success or a negative error code
92 * on failure. These negative error codes relate to LIBUSB_ERROR constants
93 * which are listed on the \ref misc "miscellaneous" documentation page.
95 * \section msglog Debug message logging
97 * libusb does not log any messages by default. Your application is therefore
98 * free to close stdout/stderr and those descriptors may be reused without
101 * The libusb_set_debug() function can be used to enable stdout/stderr logging
102 * of certain messages. Under standard configuration, libusb doesn't really
103 * log much at all, so you are advised to use this function to enable all
104 * error/warning/informational messages. It will help you debug problems with
107 * The logged messages are unstructured. There is no one-to-one correspondence
108 * between messages being logged and success or failure return codes from
109 * libusb functions. There is no format to the messages, so you should not
110 * try to capture or parse them. They are not and will not be localized.
111 * These messages are not suitable for being passed to your application user;
112 * instead, you should interpret the error codes returned from libusb functions
113 * and provide appropriate notification to the user. The messages are simply
114 * there to aid you as a programmer, and if you're confused because you're
115 * getting a strange error code from a libusb function, enabling message
116 * logging may give you a suitable explanation.
118 * The LIBUSB_DEBUG environment variable can be used to enable message logging
119 * at run-time. This environment variable should be set to a number, which is
120 * interpreted the same as the libusb_set_debug() parameter. When this
121 * environment variable is set, the message logging verbosity level is fixed
122 * and libusb_set_debug() effectively does nothing.
124 * libusb can be compiled without any logging functions, useful for embedded
125 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
126 * variable have no effects.
128 * libusb can also be compiled with verbose debugging messages. When the
129 * library is compiled in this way, all messages of all verbosities are always
130 * logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable have
133 * \section remarks Other remarks
135 * libusb does have imperfections. The \ref caveats "caveats" page attempts
140 * \page caveats Caveats
142 * \section devresets Device resets
144 * The libusb_reset_device() function allows you to reset a device. If your
145 * program has to call such a function, it should obviously be aware that
146 * the reset will cause device state to change (e.g. register values may be
149 * The problem is that any other program could reset the device your program
150 * is working with, at any time. libusb does not offer a mechanism to inform
151 * you when this has happened, so if someone else resets your device it will
152 * not be clear to your own program why the device state has changed.
154 * Ultimately, this is a limitation of writing drivers in userspace.
155 * Separation from the USB stack in the underlying kernel makes it difficult
156 * for the operating system to deliver such notifications to your program.
157 * The Linux kernel USB stack allows such reset notifications to be delivered
158 * to in-kernel USB drivers, but it is not clear how such notifications could
159 * be delivered to second-class drivers that live in userspace.
161 * \section blockonly Blocking-only functionality
163 * The functionality listed below is only available through synchronous,
164 * blocking functions. There are no asynchronous/non-blocking alternatives,
165 * and no clear ways of implementing these.
167 * - Configuration activation (libusb_set_configuration())
168 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
169 * - Releasing of interfaces (libusb_release_interface())
170 * - Clearing of halt/stall condition (libusb_clear_halt())
171 * - Device resets (libusb_reset_device())
173 * \section nohotplug No hotplugging
175 * libusb-1.0 lacks functionality for providing notifications of when devices
176 * are added or removed. This functionality is planned to be implemented
179 * That said, there is basic disconnection handling for open device handles:
180 * - If there are ongoing transfers, libusb's handle_events loop will detect
181 * disconnections and complete ongoing transfers with the
182 * LIBUSB_TRANSFER_NO_DEVICE status code.
183 * - Many functions such as libusb_set_configuration() return the special
184 * LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected.
186 * \section configsel Configuration selection and handling
188 * When libusb presents a device handle to an application, there is a chance
189 * that the corresponding device may be in unconfigured state. For devices
190 * with multiple configurations, there is also a chance that the configuration
191 * currently selected is not the one that the application wants to use.
193 * The obvious solution is to add a call to libusb_set_configuration() early
194 * on during your device initialization routines, but there are caveats to
196 * -# If the device is already in the desired configuration, calling
197 * libusb_set_configuration() using the same configuration value will cause
198 * a lightweight device reset. This may not be desirable behaviour.
199 * -# libusb will be unable to change configuration if the device is in
200 * another configuration and other programs or drivers have claimed
201 * interfaces under that configuration.
202 * -# In the case where the desired configuration is already active, libusb
203 * may not even be able to perform a lightweight device reset. For example,
204 * take my USB keyboard with fingerprint reader: I'm interested in driving
205 * the fingerprint reader interface through libusb, but the kernel's
206 * USB-HID driver will almost always have claimed the keyboard interface.
207 * Because the kernel has claimed an interface, it is not even possible to
208 * perform the lightweight device reset, so libusb_set_configuration() will
209 * fail. (Luckily the device in question only has a single configuration.)
211 * One solution to some of the above problems is to consider the currently
212 * active configuration. If the configuration we want is already active, then
213 * we don't have to select any configuration:
215 cfg = libusb_get_configuration(dev);
217 libusb_set_configuration(dev, desired);
220 * This is probably suitable for most scenarios, but is inherently racy:
221 * another application or driver may change the selected configuration
222 * <em>after</em> the libusb_get_configuration() call.
224 * Even in cases where libusb_set_configuration() succeeds, consider that other
225 * applications or drivers may change configuration after your application
226 * calls libusb_set_configuration().
228 * One possible way to lock your device into a specific configuration is as
230 * -# Set the desired configuration (or use the logic above to realise that
231 * it is already in the desired configuration)
232 * -# Claim the interface that you wish to use
233 * -# Check that the currently active configuration is the one that you want
236 * The above method works because once an interface is claimed, no application
237 * or driver is able to select another configuration.
241 * \page contexts Contexts
243 * It is possible that libusb may be used simultaneously from two independent
244 * libraries linked into the same executable. For example, if your application
245 * has a plugin-like system which allows the user to dynamically load a range
246 * of modules into your program, it is feasible that two independently
247 * developed modules may both use libusb.
249 * libusb is written to allow for these multiple user scenarios. The two
250 * "instances" of libusb will not interfere: libusb_set_debug() calls
251 * from one user will not affect the same settings for other users, other
252 * users can continue using libusb after one of them calls libusb_exit(), etc.
254 * This is made possible through libusb's <em>context</em> concept. When you
255 * call libusb_init(), you are (optionally) given a context. You can then pass
256 * this context pointer back into future libusb functions.
258 * In order to keep things simple for more simplistic applications, it is
259 * legal to pass NULL to all functions requiring a context pointer (as long as
260 * you're sure no other code will attempt to use libusb from the same process).
261 * When you pass NULL, the default context will be used. The default context
262 * is created the first time a process calls libusb_init() when no other
263 * context is alive. Contexts are destroyed during libusb_exit().
265 * You may be wondering why only a subset of libusb functions require a
266 * context pointer in their function definition. Internally, libusb stores
267 * context pointers in other objects (e.g. libusb_device instances) and hence
268 * can infer the context from those objects.
272 * @defgroup lib Library initialization/deinitialization
273 * This page details how to initialize and deinitialize libusb. Initialization
274 * must be performed before using any libusb functionality, and similarly you
275 * must not call any libusb functions after deinitialization.
279 * @defgroup dev Device handling and enumeration
280 * The functionality documented below is designed to help with the following
282 * - Enumerating the USB devices currently attached to the system
283 * - Choosing a device to operate from your software
284 * - Opening and closing the chosen device
286 * \section nutshell In a nutshell...
288 * The description below really makes things sound more complicated than they
289 * actually are. The following sequence of function calls will be suitable
290 * for almost all scenarios and does not require you to have such a deep
291 * understanding of the resource management issues:
294 libusb_device **list;
295 libusb_device *found = NULL;
296 size_t cnt = libusb_get_device_list(NULL, &list);
302 for (i = 0; i < cnt; i++) {
303 libusb_device *device = list[i];
304 if (is_interesting(device)) {
311 libusb_device_handle *handle;
313 err = libusb_open(found, &handle);
319 libusb_free_device_list(list, 1);
322 * The two important points:
323 * - You asked libusb_free_device_list() to unreference the devices (2nd
325 * - You opened the device before freeing the list and unreferencing the
328 * If you ended up with a handle, you can now proceed to perform I/O on the
331 * \section devshandles Devices and device handles
332 * libusb has a concept of a USB device, represented by the
333 * \ref libusb_device opaque type. A device represents a USB device that
334 * is currently or was previously connected to the system. Using a reference
335 * to a device, you can determine certain information about the device (e.g.
336 * you can read the descriptor data).
338 * The libusb_get_device_list() function can be used to obtain a list of
339 * devices currently connected to the system. This is known as device
342 * Just because you have a reference to a device does not mean it is
343 * necessarily usable. The device may have been unplugged, you may not have
344 * permission to operate such device, or another program or driver may be
347 * When you've found a device that you'd like to operate, you must ask
348 * libusb to open the device using the libusb_open() function. Assuming
349 * success, libusb then returns you a <em>device handle</em>
350 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
351 * operate on the handle rather than the original device pointer.
353 * \section devref Device discovery and reference counting
355 * Device discovery (i.e. calling libusb_get_device_list()) returns a
356 * freshly-allocated list of devices. The list itself must be freed when
357 * you are done with it. libusb also needs to know when it is OK to free
358 * the contents of the list - the devices themselves.
360 * To handle these issues, libusb provides you with two separate items:
361 * - A function to free the list itself
362 * - A reference counting system for the devices inside
364 * New devices presented by the libusb_get_device_list() function all have a
365 * reference count of 1. You can increase and decrease reference count using
366 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
367 * it's reference count reaches 0.
369 * With the above information in mind, the process of opening a device can
370 * be viewed as follows:
371 * -# Discover devices using libusb_get_device_list().
372 * -# Choose the device that you want to operate, and call libusb_open().
373 * -# Unref all devices in the discovered device list.
374 * -# Free the discovered device list.
376 * The order is important - you must not unreference the device before
377 * attempting to open it, because unreferencing it may destroy the device.
379 * For convenience, the libusb_free_device_list() function includes a
380 * parameter to optionally unreference all the devices in the list before
381 * freeing the list itself. This combines steps 3 and 4 above.
383 * As an implementation detail, libusb_open() actually adds a reference to
384 * the device in question. This is because the device remains available
385 * through the handle via libusb_get_device(). The reference is deleted during
389 /** @defgroup misc Miscellaneous */
391 /* we traverse usbfs without knowing how many devices we are going to find.
392 * so we create this discovered_devs model which is similar to a linked-list
393 * which grows when required. it can be freed once discovery has completed,
394 * eliminating the need for a list node in the libusb_device structure
396 #define DISCOVERED_DEVICES_SIZE_STEP 8
398 static struct discovered_devs *discovered_devs_alloc(void)
400 struct discovered_devs *ret =
401 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
405 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
410 /* append a device to the discovered devices collection. may realloc itself,
411 * returning new discdevs. returns NULL on realloc failure. */
412 struct discovered_devs *discovered_devs_append(
413 struct discovered_devs *discdevs, struct libusb_device *dev)
415 size_t len = discdevs->len;
418 /* if there is space, just append the device */
419 if (len < discdevs->capacity) {
420 discdevs->devices[len] = libusb_ref_device(dev);
425 /* exceeded capacity, need to grow */
426 usbi_dbg("need to increase capacity");
427 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
428 discdevs = realloc(discdevs,
429 sizeof(*discdevs) + (sizeof(void *) * capacity));
431 discdevs->capacity = capacity;
432 discdevs->devices[len] = libusb_ref_device(dev);
439 static void discovered_devs_free(struct discovered_devs *discdevs)
443 for (i = 0; i < discdevs->len; i++)
444 libusb_unref_device(discdevs->devices[i]);
449 /* Allocate a new device with a specific session ID. The returned device has
450 * a reference count of 1. */
451 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
452 unsigned long session_id)
454 size_t priv_size = usbi_backend->device_priv_size;
455 struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
461 r = pthread_mutex_init(&dev->lock, NULL);
467 dev->session_data = session_id;
468 memset(&dev->os_priv, 0, priv_size);
470 pthread_mutex_lock(&ctx->usb_devs_lock);
471 list_add(&dev->list, &ctx->usb_devs);
472 pthread_mutex_unlock(&ctx->usb_devs_lock);
476 /* Perform some final sanity checks on a newly discovered device. If this
477 * function fails (negative return code), the device should not be added
478 * to the discovered device list. */
479 int usbi_sanitize_device(struct libusb_device *dev)
482 unsigned char raw_desc[DEVICE_DESC_LENGTH];
483 uint8_t num_configurations;
486 r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
490 num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
491 if (num_configurations > USB_MAXCONFIG) {
492 usbi_err(DEVICE_CTX(dev), "too many configurations");
493 return LIBUSB_ERROR_IO;
494 } else if (num_configurations < 1) {
495 usbi_dbg("no configurations?");
496 return LIBUSB_ERROR_IO;
499 dev->num_configurations = num_configurations;
503 /* Examine libusb's internal list of known devices, looking for one with
504 * a specific session ID. Returns the matching device if it was found, and
506 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
507 unsigned long session_id)
509 struct libusb_device *dev;
510 struct libusb_device *ret = NULL;
512 pthread_mutex_lock(&ctx->usb_devs_lock);
513 list_for_each_entry(dev, &ctx->usb_devs, list)
514 if (dev->session_data == session_id) {
518 pthread_mutex_unlock(&ctx->usb_devs_lock);
524 * Returns a list of USB devices currently attached to the system. This is
525 * your entry point into finding a USB device to operate.
527 * You are expected to unreference all the devices when you are done with
528 * them, and then free the list with libusb_free_device_list(). Note that
529 * libusb_free_device_list() can unref all the devices for you. Be careful
530 * not to unreference a device you are about to open until after you have
533 * This return value of this function indicates the number of devices in
534 * the resultant list. The list is actually one element larger, as it is
537 * \param ctx the context to operate on, or NULL for the default context
538 * \param list output location for a list of devices. Must be later freed with
539 * libusb_free_device_list().
540 * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
541 * on memory allocation failure.
543 API_EXPORTED ssize_t libusb_get_device_list(libusb_context *ctx,
544 libusb_device ***list)
546 struct discovered_devs *discdevs = discovered_devs_alloc();
547 struct libusb_device **ret;
551 USBI_GET_CONTEXT(ctx);
555 return LIBUSB_ERROR_NO_MEM;
557 r = usbi_backend->get_device_list(ctx, &discdevs);
563 /* convert discovered_devs into a list */
565 ret = malloc(sizeof(void *) * (len + 1));
567 len = LIBUSB_ERROR_NO_MEM;
572 for (i = 0; i < len; i++) {
573 struct libusb_device *dev = discdevs->devices[i];
574 ret[i] = libusb_ref_device(dev);
579 discovered_devs_free(discdevs);
584 * Frees a list of devices previously discovered using
585 * libusb_get_device_list(). If the unref_devices parameter is set, the
586 * reference count of each device in the list is decremented by 1.
587 * \param list the list to free
588 * \param unref_devices whether to unref the devices in the list
590 API_EXPORTED void libusb_free_device_list(libusb_device **list,
598 struct libusb_device *dev;
600 while ((dev = list[i++]) != NULL)
601 libusb_unref_device(dev);
607 * Get the number of the bus that a device is connected to.
608 * \param dev a device
609 * \returns the bus number
611 API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev)
613 return dev->bus_number;
617 * Get the address of the device on the bus it is connected to.
618 * \param dev a device
619 * \returns the device address
621 API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev)
623 return dev->device_address;
627 * Convenience function to retrieve the wMaxPacketSize value for a particular
628 * endpoint in the active device configuration. This is useful for setting up
629 * isochronous transfers.
631 * \param dev a device
632 * \param endpoint address of the endpoint in question
633 * \returns the wMaxPacketSize value
634 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
635 * \returns LIBUSB_ERROR_OTHER on other failure
637 API_EXPORTED int libusb_get_max_packet_size(libusb_device *dev,
638 unsigned char endpoint)
641 struct libusb_config_descriptor *config;
644 r = libusb_get_active_config_descriptor(dev, &config);
646 usbi_err(DEVICE_CTX(dev),
647 "could not retrieve active config descriptor");
648 return LIBUSB_ERROR_OTHER;
651 r = LIBUSB_ERROR_NOT_FOUND;
652 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
653 const struct libusb_interface *iface = &config->interface[iface_idx];
656 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
658 const struct libusb_interface_descriptor *altsetting
659 = &iface->altsetting[altsetting_idx];
662 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
663 const struct libusb_endpoint_descriptor *ep =
664 &altsetting->endpoint[ep_idx];
665 if (ep->bEndpointAddress == endpoint) {
666 r = ep->wMaxPacketSize;
674 libusb_free_config_descriptor(config);
679 * Increment the reference count of a device.
680 * \param dev the device to reference
681 * \returns the same device
683 API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev)
685 pthread_mutex_lock(&dev->lock);
687 pthread_mutex_unlock(&dev->lock);
692 * Decrement the reference count of a device. If the decrement operation
693 * causes the reference count to reach zero, the device shall be destroyed.
694 * \param dev the device to unreference
696 API_EXPORTED void libusb_unref_device(libusb_device *dev)
703 pthread_mutex_lock(&dev->lock);
704 refcnt = --dev->refcnt;
705 pthread_mutex_unlock(&dev->lock);
708 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
710 if (usbi_backend->destroy_device)
711 usbi_backend->destroy_device(dev);
713 pthread_mutex_lock(&dev->ctx->usb_devs_lock);
714 list_del(&dev->list);
715 pthread_mutex_unlock(&dev->ctx->usb_devs_lock);
722 * Open a device and obtain a device handle. A handle allows you to perform
723 * I/O on the device in question.
725 * Internally, this function adds a reference to the device and makes it
726 * available to you through libusb_get_device(). This reference is removed
727 * during libusb_close().
729 * This is a non-blocking function; no requests are sent over the bus.
731 * \param dev the device to open
732 * \param handle output location for the returned device handle pointer. Only
733 * populated when the return code is 0.
734 * \returns 0 on success
735 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
736 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
737 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
738 * \returns another LIBUSB_ERROR code on other failure
740 API_EXPORTED int libusb_open(libusb_device *dev, libusb_device_handle **handle)
742 struct libusb_device_handle *_handle;
743 size_t priv_size = usbi_backend->device_handle_priv_size;
745 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
747 _handle = malloc(sizeof(*_handle) + priv_size);
749 return LIBUSB_ERROR_NO_MEM;
751 r = pthread_mutex_init(&_handle->lock, NULL);
753 return LIBUSB_ERROR_OTHER;
755 _handle->dev = libusb_ref_device(dev);
756 _handle->claimed_interfaces = 0;
757 memset(&_handle->os_priv, 0, priv_size);
759 r = usbi_backend->open(_handle);
761 libusb_unref_device(dev);
766 pthread_mutex_lock(&dev->ctx->open_devs_lock);
767 list_add(&_handle->list, &dev->ctx->open_devs);
768 pthread_mutex_unlock(&dev->ctx->open_devs_lock);
774 * Convenience function for finding a device with a particular
775 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
776 * for those scenarios where you are using libusb to knock up a quick test
777 * application - it allows you to avoid calling libusb_get_device_list() and
778 * worrying about traversing/freeing the list.
780 * This function has limitations and is hence not intended for use in real
781 * applications: if multiple devices have the same IDs it will only
782 * give you the first one, etc.
784 * \param ctx the context to operate on, or NULL for the default context
785 * \param vendor_id the idVendor value to search for
786 * \param product_id the idProduct value to search for
787 * \returns a handle for the first found device, or NULL on error or if the
788 * device could not be found. */
789 API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid(
790 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
792 struct libusb_device **devs;
793 struct libusb_device *found = NULL;
794 struct libusb_device *dev;
795 struct libusb_device_handle *handle = NULL;
799 if (libusb_get_device_list(ctx, &devs) < 0)
802 while ((dev = devs[i++]) != NULL) {
803 struct libusb_device_descriptor desc;
804 r = libusb_get_device_descriptor(dev, &desc);
807 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
814 r = libusb_open(found, &handle);
820 libusb_free_device_list(devs, 1);
824 static void do_close(struct libusb_device_handle *dev_handle)
826 usbi_backend->close(dev_handle);
827 libusb_unref_device(dev_handle->dev);
831 * Close a device handle. Should be called on all open handles before your
834 * Internally, this function destroys the reference that was added by
835 * libusb_open() on the given device.
837 * This is a non-blocking function; no requests are sent over the bus.
839 * \param dev_handle the handle to close
841 API_EXPORTED void libusb_close(libusb_device_handle *dev_handle)
847 pthread_mutex_lock(&HANDLE_CTX(dev_handle)->open_devs_lock);
848 list_del(&dev_handle->list);
849 pthread_mutex_unlock(&HANDLE_CTX(dev_handle)->open_devs_lock);
851 do_close(dev_handle);
856 * Get the underlying device for a handle. This function does not modify
857 * the reference count of the returned device, so do not feel compelled to
858 * unreference it when you are done.
859 * \param dev_handle a device handle
860 * \returns the underlying device
862 API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle)
864 return dev_handle->dev;
868 * Determine the bConfigurationValue of the currently active configuration.
870 * You could formulate your own control request to obtain this information,
871 * but this function has the advantage that it may be able to retrieve the
872 * information from operating system caches (no I/O involved).
874 * If the OS does not cache this information, then this function will block
875 * while a control transfer is submitted to retrieve the information.
877 * This function will return a value of 0 in the <tt>config</tt> output
878 * parameter if the device is in unconfigured state.
880 * \param dev a device handle
881 * \param config output location for the bConfigurationValue of the active
882 * configuration (only valid for return code 0)
883 * \returns 0 on success
884 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
885 * \returns another LIBUSB_ERROR code on other failure
887 API_EXPORTED int libusb_get_configuration(libusb_device_handle *dev,
890 int r = LIBUSB_ERROR_NOT_SUPPORTED;
893 if (usbi_backend->get_configuration)
894 r = usbi_backend->get_configuration(dev, config);
896 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
898 usbi_dbg("falling back to control message");
899 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
900 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
902 usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
908 usbi_dbg("control failed, error %d", r);
913 usbi_dbg("active config %d", *config);
919 * Set the active configuration for a device.
921 * The operating system may or may not have already set an active
922 * configuration on the device. It is up to your application to ensure the
923 * correct configuration is selected before you attempt to claim interfaces
924 * and perform other operations.
926 * If you call this function on a device already configured with the selected
927 * configuration, then this function will act as a lightweight device reset:
928 * it will issue a SET_CONFIGURATION request using the current configuration,
929 * causing most USB-related device state to be reset (altsetting reset to zero,
930 * endpoint halts cleared, toggles reset).
932 * You cannot change/reset configuration if your application has claimed
933 * interfaces - you should free them with libusb_release_interface() first.
934 * You cannot change/reset configuration if other applications or drivers have
935 * claimed interfaces.
937 * A configuration value of -1 will put the device in unconfigured state.
938 * The USB specifications state that a configuration value of 0 does this,
939 * however buggy devices exist which actually have a configuration 0.
941 * You should always use this function rather than formulating your own
942 * SET_CONFIGURATION control request. This is because the underlying operating
943 * system needs to know when such changes happen.
945 * This is a blocking function.
947 * \param dev a device handle
948 * \param configuration the bConfigurationValue of the configuration you
949 * wish to activate, or -1 if you wish to put the device in unconfigured state
950 * \returns 0 on success
951 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
952 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
953 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
954 * \returns another LIBUSB_ERROR code on other failure
956 API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev,
959 usbi_dbg("configuration %d", configuration);
960 return usbi_backend->set_configuration(dev, configuration);
964 * Claim an interface on a given device handle. You must claim the interface
965 * you wish to use before you can perform I/O on any of its endpoints.
967 * It is legal to attempt to claim an already-claimed interface, in which
968 * case libusb just returns 0 without doing anything.
970 * Claiming of interfaces is a purely logical operation; it does not cause
971 * any requests to be sent over the bus. Interface claiming is used to
972 * instruct the underlying operating system that your application wishes
973 * to take ownership of the interface.
975 * This is a non-blocking function.
977 * \param dev a device handle
978 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
980 * \returns 0 on success
981 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
982 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
984 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
985 * \returns a LIBUSB_ERROR code on other failure
987 API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev,
988 int interface_number)
992 usbi_dbg("interface %d", interface_number);
993 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
994 return LIBUSB_ERROR_INVALID_PARAM;
996 pthread_mutex_lock(&dev->lock);
997 if (dev->claimed_interfaces & (1 << interface_number))
1000 r = usbi_backend->claim_interface(dev, interface_number);
1002 dev->claimed_interfaces |= 1 << interface_number;
1005 pthread_mutex_unlock(&dev->lock);
1010 * Release an interface previously claimed with libusb_claim_interface(). You
1011 * should release all claimed interfaces before closing a device handle.
1013 * This is a blocking function. A SET_INTERFACE control request will be sent
1014 * to the device, resetting interface state to the first alternate setting.
1016 * \param dev a device handle
1017 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1018 * previously-claimed interface
1019 * \returns 0 on success
1020 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1021 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1022 * \returns another LIBUSB_ERROR code on other failure
1024 API_EXPORTED int libusb_release_interface(libusb_device_handle *dev,
1025 int interface_number)
1029 usbi_dbg("interface %d", interface_number);
1030 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1031 return LIBUSB_ERROR_INVALID_PARAM;
1033 pthread_mutex_lock(&dev->lock);
1034 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1035 r = LIBUSB_ERROR_NOT_FOUND;
1039 r = usbi_backend->release_interface(dev, interface_number);
1041 dev->claimed_interfaces &= ~(1 << interface_number);
1044 pthread_mutex_unlock(&dev->lock);
1049 * Activate an alternate setting for an interface. The interface must have
1050 * been previously claimed with libusb_claim_interface().
1052 * You should always use this function rather than formulating your own
1053 * SET_INTERFACE control request. This is because the underlying operating
1054 * system needs to know when such changes happen.
1056 * This is a blocking function.
1058 * \param dev a device handle
1059 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1060 * previously-claimed interface
1061 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1062 * setting to activate
1063 * \returns 0 on success
1064 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1065 * requested alternate setting does not exist
1066 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1067 * \returns another LIBUSB_ERROR code on other failure
1069 API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev,
1070 int interface_number, int alternate_setting)
1072 usbi_dbg("interface %d altsetting %d",
1073 interface_number, alternate_setting);
1074 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1075 return LIBUSB_ERROR_INVALID_PARAM;
1077 pthread_mutex_lock(&dev->lock);
1078 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1079 pthread_mutex_unlock(&dev->lock);
1080 return LIBUSB_ERROR_NOT_FOUND;
1082 pthread_mutex_unlock(&dev->lock);
1084 return usbi_backend->set_interface_altsetting(dev, interface_number,
1089 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1090 * are unable to receive or transmit data until the halt condition is stalled.
1092 * You should cancel all pending transfers before attempting to clear the halt
1095 * This is a blocking function.
1097 * \param dev a device handle
1098 * \param endpoint the endpoint to clear halt status
1099 * \returns 0 on success
1100 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1101 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1102 * \returns another LIBUSB_ERROR code on other failure
1104 API_EXPORTED int libusb_clear_halt(libusb_device_handle *dev,
1105 unsigned char endpoint)
1107 usbi_dbg("endpoint %x", endpoint);
1108 return usbi_backend->clear_halt(dev, endpoint);
1112 * Perform a USB port reset to reinitialize a device. The system will attempt
1113 * to restore the previous configuration and alternate settings after the
1114 * reset has completed.
1116 * If the reset fails, the descriptors change, or the previous state cannot be
1117 * restored, the device will appear to be disconnected and reconnected. This
1118 * means that the device handle is no longer valid (you should close it) and
1119 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1120 * when this is the case.
1122 * This is a blocking function which usually incurs a noticeable delay.
1124 * \param dev a handle of the device to reset
1125 * \returns 0 on success
1126 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1127 * device has been disconnected
1128 * \returns another LIBUSB_ERROR code on other failure
1130 API_EXPORTED int libusb_reset_device(libusb_device_handle *dev)
1133 return usbi_backend->reset_device(dev);
1137 * Determine if a kernel driver is active on an interface. If a kernel driver
1138 * is active, you cannot claim the interface, and libusb will be unable to
1141 * \param dev a device handle
1142 * \param interface the interface to check
1143 * \returns 0 if no kernel driver is active
1144 * \returns 1 if a kernel driver is active
1145 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1146 * \returns another LIBUSB_ERROR code on other failure
1147 * \see libusb_detach_kernel_driver()
1149 API_EXPORTED int libusb_kernel_driver_active(libusb_device_handle *dev,
1152 usbi_dbg("interface %d", interface);
1153 if (usbi_backend->kernel_driver_active)
1154 return usbi_backend->kernel_driver_active(dev, interface);
1156 return LIBUSB_ERROR_NOT_SUPPORTED;
1160 * Detach a kernel driver from an interface. If successful, you will then be
1161 * able to claim the interface and perform I/O.
1163 * \param dev a device handle
1164 * \param interface the interface to detach the driver from
1165 * \returns 0 on success
1166 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1167 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1168 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1169 * \returns another LIBUSB_ERROR code on other failure
1170 * \see libusb_kernel_driver_active()
1172 API_EXPORTED int libusb_detach_kernel_driver(libusb_device_handle *dev,
1175 usbi_dbg("interface %d", interface);
1176 if (usbi_backend->detach_kernel_driver)
1177 return usbi_backend->detach_kernel_driver(dev, interface);
1179 return LIBUSB_ERROR_NOT_SUPPORTED;
1183 * Set message verbosity.
1184 * - Level 0: no messages ever printed by the library (default)
1185 * - Level 1: error messages are printed to stderr
1186 * - Level 2: warning and error messages are printed to stderr
1187 * - Level 3: informational messages are printed to stdout, warning and error
1188 * messages are printed to stderr
1190 * The default level is 0, which means no messages are ever printed. If you
1191 * choose to increase the message verbosity level, ensure that your
1192 * application does not close the stdout/stderr file descriptors.
1194 * You are advised to set level 3. libusb is conservative with it's message
1195 * logging and most of the time, will only log messages that explain error
1196 * conditions and other oddities. This will help you debug your software.
1198 * If the LIBUSB_DEBUG environment variable was set when libusb was
1199 * initialized, this function does nothing: the message verbosity is fixed
1200 * to the value in the environment variable.
1202 * If libusb was compiled without any message logging, this function does
1203 * nothing: you'll never get any messages.
1205 * If libusb was compiled with verbose debug message logging, this function
1206 * does nothing: you'll always get messages from all levels.
1208 * \param ctx the context to operate on, or NULL for the default context
1209 * \param level debug level to set
1211 API_EXPORTED void libusb_set_debug(libusb_context *ctx, int level)
1213 USBI_GET_CONTEXT(ctx);
1214 if (!ctx->debug_fixed)
1219 * Initialize libusb. This function must be called before calling any other
1221 * \param context Optional output location for context pointer.
1222 * Only valid on return code 0.
1223 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1225 API_EXPORTED int libusb_init(libusb_context **context)
1227 char *dbg = getenv("LIBUSB_DEBUG");
1228 struct libusb_context *ctx = malloc(sizeof(*ctx));
1231 return LIBUSB_ERROR_NO_MEM;
1232 memset(ctx, 0, sizeof(*ctx));
1235 ctx->debug = atoi(dbg);
1237 ctx->debug_fixed = 1;
1241 if (usbi_backend->init) {
1242 int r = usbi_backend->init(ctx);
1249 pthread_mutex_init(&ctx->usb_devs_lock, NULL);
1250 pthread_mutex_init(&ctx->open_devs_lock, NULL);
1251 list_init(&ctx->usb_devs);
1252 list_init(&ctx->open_devs);
1255 pthread_mutex_lock(&default_context_lock);
1256 if (!usbi_default_context) {
1257 usbi_dbg("created default context");
1258 usbi_default_context = ctx;
1260 pthread_mutex_unlock(&default_context_lock);
1268 * Deinitialize libusb. Should be called after closing all open devices and
1269 * before your application terminates.
1270 * \param ctx the context to deinitialize, or NULL for the default context
1272 API_EXPORTED void libusb_exit(struct libusb_context *ctx)
1274 USBI_GET_CONTEXT(ctx);
1277 pthread_mutex_lock(&ctx->open_devs_lock);
1278 if (!list_empty(&ctx->open_devs)) {
1279 struct libusb_device_handle *devh;
1280 struct libusb_device_handle *tmp;
1282 usbi_dbg("naughty app left some devices open!");
1283 list_for_each_entry_safe(devh, tmp, &ctx->open_devs, list) {
1284 list_del(&devh->list);
1289 pthread_mutex_unlock(&ctx->open_devs_lock);
1291 if (usbi_backend->exit)
1292 usbi_backend->exit();
1294 pthread_mutex_lock(&default_context_lock);
1295 if (ctx == usbi_default_context) {
1296 usbi_dbg("freeing default context");
1297 usbi_default_context = NULL;
1299 pthread_mutex_unlock(&default_context_lock);
1304 void usbi_log(struct libusb_context *ctx, enum usbi_log_level level,
1305 const char *function, const char *format, ...)
1308 FILE *stream = stdout;
1311 #ifndef ENABLE_DEBUG_LOGGING
1312 USBI_GET_CONTEXT(ctx);
1315 if (level == LOG_LEVEL_WARNING && ctx->debug < 2)
1317 if (level == LOG_LEVEL_INFO && ctx->debug < 3)
1322 case LOG_LEVEL_INFO:
1325 case LOG_LEVEL_WARNING:
1329 case LOG_LEVEL_ERROR:
1333 case LOG_LEVEL_DEBUG:
1343 fprintf(stream, "libusb:%s [%s] ", prefix, function);
1345 va_start (args, format);
1346 vfprintf(stream, format, args);
1349 fprintf(stream, "\n");