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>
36 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
37 #elif defined(OS_DARWIN)
38 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
40 #error "Unsupported OS"
43 struct libusb_context *usbi_default_context = NULL;
44 static pthread_mutex_t default_context_lock = PTHREAD_MUTEX_INITIALIZER;
47 * \mainpage libusb-1.0 API Reference
49 * \section intro Introduction
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>.
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
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.
68 * \section features Library features
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
79 * \section gettingstarted Getting Started
81 * To begin reading the API documentation, start with the Modules page which
82 * links to the different categories of libusb's functionality.
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.
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.
92 * \section errorhandling Error handling
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.
98 * \section msglog Debug message logging
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
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
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.
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.
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.
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
136 * \section remarks Other remarks
138 * libusb does have imperfections. The \ref caveats "caveats" page attempts
143 * \page caveats Caveats
145 * \section devresets Device resets
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
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.
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.
164 * \section blockonly Blocking-only functionality
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.
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())
176 * \section nohotplug No hotplugging
178 * libusb-1.0 lacks functionality for providing notifications of when devices
179 * are added or removed. This functionality is planned to be implemented
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.
189 * \section configsel Configuration selection and handling
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.
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
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.)
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:
218 cfg = libusb_get_configuration(dev);
220 libusb_set_configuration(dev, desired);
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.
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().
231 * One possible way to lock your device into a specific configuration is as
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
239 * The above method works because once an interface is claimed, no application
240 * or driver is able to select another configuration.
244 * \page contexts Contexts
246 * It is possible that libusb may be used simultaneously from two independent
247 * libraries linked into the same executable. For example, if your application
248 * has a plugin-like system which allows the user to dynamically load a range
249 * of modules into your program, it is feasible that two independently
250 * developed modules may both use libusb.
252 * libusb is written to allow for these multiple user scenarios. The two
253 * "instances" of libusb will not interfere: libusb_set_debug() calls
254 * from one user will not affect the same settings for other users, other
255 * users can continue using libusb after one of them calls libusb_exit(), etc.
257 * This is made possible through libusb's <em>context</em> concept. When you
258 * call libusb_init(), you are (optionally) given a context. You can then pass
259 * this context pointer back into future libusb functions.
261 * In order to keep things simple for more simplistic applications, it is
262 * legal to pass NULL to all functions requiring a context pointer (as long as
263 * you're sure no other code will attempt to use libusb from the same process).
264 * When you pass NULL, the default context will be used. The default context
265 * is created the first time a process calls libusb_init() when no other
266 * context is alive. Contexts are destroyed during libusb_exit().
268 * You may be wondering why only a subset of libusb functions require a
269 * context pointer in their function definition. Internally, libusb stores
270 * context pointers in other objects (e.g. libusb_device instances) and hence
271 * can infer the context from those objects.
275 * @defgroup lib Library initialization/deinitialization
276 * This page details how to initialize and deinitialize libusb. Initialization
277 * must be performed before using any libusb functionality, and similarly you
278 * must not call any libusb functions after deinitialization.
282 * @defgroup dev Device handling and enumeration
283 * The functionality documented below is designed to help with the following
285 * - Enumerating the USB devices currently attached to the system
286 * - Choosing a device to operate from your software
287 * - Opening and closing the chosen device
289 * \section nutshell In a nutshell...
291 * The description below really makes things sound more complicated than they
292 * actually are. The following sequence of function calls will be suitable
293 * for almost all scenarios and does not require you to have such a deep
294 * understanding of the resource management issues:
297 libusb_device **list;
298 libusb_device *found = NULL;
299 ssize_t cnt = libusb_get_device_list(NULL, &list);
305 for (i = 0; i < cnt; i++) {
306 libusb_device *device = list[i];
307 if (is_interesting(device)) {
314 libusb_device_handle *handle;
316 err = libusb_open(found, &handle);
322 libusb_free_device_list(list, 1);
325 * The two important points:
326 * - You asked libusb_free_device_list() to unreference the devices (2nd
328 * - You opened the device before freeing the list and unreferencing the
331 * If you ended up with a handle, you can now proceed to perform I/O on the
334 * \section devshandles Devices and device handles
335 * libusb has a concept of a USB device, represented by the
336 * \ref libusb_device opaque type. A device represents a USB device that
337 * is currently or was previously connected to the system. Using a reference
338 * to a device, you can determine certain information about the device (e.g.
339 * you can read the descriptor data).
341 * The libusb_get_device_list() function can be used to obtain a list of
342 * devices currently connected to the system. This is known as device
345 * Just because you have a reference to a device does not mean it is
346 * necessarily usable. The device may have been unplugged, you may not have
347 * permission to operate such device, or another program or driver may be
350 * When you've found a device that you'd like to operate, you must ask
351 * libusb to open the device using the libusb_open() function. Assuming
352 * success, libusb then returns you a <em>device handle</em>
353 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
354 * operate on the handle rather than the original device pointer.
356 * \section devref Device discovery and reference counting
358 * Device discovery (i.e. calling libusb_get_device_list()) returns a
359 * freshly-allocated list of devices. The list itself must be freed when
360 * you are done with it. libusb also needs to know when it is OK to free
361 * the contents of the list - the devices themselves.
363 * To handle these issues, libusb provides you with two separate items:
364 * - A function to free the list itself
365 * - A reference counting system for the devices inside
367 * New devices presented by the libusb_get_device_list() function all have a
368 * reference count of 1. You can increase and decrease reference count using
369 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
370 * its reference count reaches 0.
372 * With the above information in mind, the process of opening a device can
373 * be viewed as follows:
374 * -# Discover devices using libusb_get_device_list().
375 * -# Choose the device that you want to operate, and call libusb_open().
376 * -# Unref all devices in the discovered device list.
377 * -# Free the discovered device list.
379 * The order is important - you must not unreference the device before
380 * attempting to open it, because unreferencing it may destroy the device.
382 * For convenience, the libusb_free_device_list() function includes a
383 * parameter to optionally unreference all the devices in the list before
384 * freeing the list itself. This combines steps 3 and 4 above.
386 * As an implementation detail, libusb_open() actually adds a reference to
387 * the device in question. This is because the device remains available
388 * through the handle via libusb_get_device(). The reference is deleted during
392 /** @defgroup misc Miscellaneous */
394 /* we traverse usbfs without knowing how many devices we are going to find.
395 * so we create this discovered_devs model which is similar to a linked-list
396 * which grows when required. it can be freed once discovery has completed,
397 * eliminating the need for a list node in the libusb_device structure
399 #define DISCOVERED_DEVICES_SIZE_STEP 8
401 static struct discovered_devs *discovered_devs_alloc(void)
403 struct discovered_devs *ret =
404 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
408 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
413 /* append a device to the discovered devices collection. may realloc itself,
414 * returning new discdevs. returns NULL on realloc failure. */
415 struct discovered_devs *discovered_devs_append(
416 struct discovered_devs *discdevs, struct libusb_device *dev)
418 size_t len = discdevs->len;
421 /* if there is space, just append the device */
422 if (len < discdevs->capacity) {
423 discdevs->devices[len] = libusb_ref_device(dev);
428 /* exceeded capacity, need to grow */
429 usbi_dbg("need to increase capacity");
430 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
431 discdevs = realloc(discdevs,
432 sizeof(*discdevs) + (sizeof(void *) * capacity));
434 discdevs->capacity = capacity;
435 discdevs->devices[len] = libusb_ref_device(dev);
442 static void discovered_devs_free(struct discovered_devs *discdevs)
446 for (i = 0; i < discdevs->len; i++)
447 libusb_unref_device(discdevs->devices[i]);
452 /* Allocate a new device with a specific session ID. The returned device has
453 * a reference count of 1. */
454 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
455 unsigned long session_id)
457 size_t priv_size = usbi_backend->device_priv_size;
458 struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
464 r = pthread_mutex_init(&dev->lock, NULL);
470 dev->session_data = session_id;
471 memset(&dev->os_priv, 0, priv_size);
473 pthread_mutex_lock(&ctx->usb_devs_lock);
474 list_add(&dev->list, &ctx->usb_devs);
475 pthread_mutex_unlock(&ctx->usb_devs_lock);
479 /* Perform some final sanity checks on a newly discovered device. If this
480 * function fails (negative return code), the device should not be added
481 * to the discovered device list. */
482 int usbi_sanitize_device(struct libusb_device *dev)
485 unsigned char raw_desc[DEVICE_DESC_LENGTH];
486 uint8_t num_configurations;
489 r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
493 num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
494 if (num_configurations > USB_MAXCONFIG) {
495 usbi_err(DEVICE_CTX(dev), "too many configurations");
496 return LIBUSB_ERROR_IO;
497 } else if (num_configurations < 1) {
498 usbi_dbg("no configurations?");
499 return LIBUSB_ERROR_IO;
502 dev->num_configurations = num_configurations;
506 /* Examine libusb's internal list of known devices, looking for one with
507 * a specific session ID. Returns the matching device if it was found, and
509 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
510 unsigned long session_id)
512 struct libusb_device *dev;
513 struct libusb_device *ret = NULL;
515 pthread_mutex_lock(&ctx->usb_devs_lock);
516 list_for_each_entry(dev, &ctx->usb_devs, list)
517 if (dev->session_data == session_id) {
521 pthread_mutex_unlock(&ctx->usb_devs_lock);
527 * Returns a list of USB devices currently attached to the system. This is
528 * your entry point into finding a USB device to operate.
530 * You are expected to unreference all the devices when you are done with
531 * them, and then free the list with libusb_free_device_list(). Note that
532 * libusb_free_device_list() can unref all the devices for you. Be careful
533 * not to unreference a device you are about to open until after you have
536 * This return value of this function indicates the number of devices in
537 * the resultant list. The list is actually one element larger, as it is
540 * \param ctx the context to operate on, or NULL for the default context
541 * \param list output location for a list of devices. Must be later freed with
542 * libusb_free_device_list().
543 * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
544 * on memory allocation failure.
546 API_EXPORTED ssize_t libusb_get_device_list(libusb_context *ctx,
547 libusb_device ***list)
549 struct discovered_devs *discdevs = discovered_devs_alloc();
550 struct libusb_device **ret;
554 USBI_GET_CONTEXT(ctx);
558 return LIBUSB_ERROR_NO_MEM;
560 r = usbi_backend->get_device_list(ctx, &discdevs);
566 /* convert discovered_devs into a list */
568 ret = malloc(sizeof(void *) * (len + 1));
570 len = LIBUSB_ERROR_NO_MEM;
575 for (i = 0; i < len; i++) {
576 struct libusb_device *dev = discdevs->devices[i];
577 ret[i] = libusb_ref_device(dev);
582 discovered_devs_free(discdevs);
587 * Frees a list of devices previously discovered using
588 * libusb_get_device_list(). If the unref_devices parameter is set, the
589 * reference count of each device in the list is decremented by 1.
590 * \param list the list to free
591 * \param unref_devices whether to unref the devices in the list
593 API_EXPORTED void libusb_free_device_list(libusb_device **list,
601 struct libusb_device *dev;
603 while ((dev = list[i++]) != NULL)
604 libusb_unref_device(dev);
610 * Get the number of the bus that a device is connected to.
611 * \param dev a device
612 * \returns the bus number
614 API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev)
616 return dev->bus_number;
620 * Get the address of the device on the bus it is connected to.
621 * \param dev a device
622 * \returns the device address
624 API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev)
626 return dev->device_address;
629 static const struct libusb_endpoint_descriptor *find_endpoint(
630 struct libusb_config_descriptor *config, unsigned char endpoint)
633 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
634 const struct libusb_interface *iface = &config->interface[iface_idx];
637 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
639 const struct libusb_interface_descriptor *altsetting
640 = &iface->altsetting[altsetting_idx];
643 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
644 const struct libusb_endpoint_descriptor *ep =
645 &altsetting->endpoint[ep_idx];
646 if (ep->bEndpointAddress == endpoint)
655 * Convenience function to retrieve the wMaxPacketSize value for a particular
656 * endpoint in the active device configuration.
658 * This function was originally intended to be of assistance when setting up
659 * isochronous transfers, but a design mistake resulted in this function
660 * instead. It simply returns the wMaxPacketSize value without considering
661 * its contents. If you're dealing with isochronous transfers, you probably
662 * want libusb_get_max_iso_packet_size() instead.
664 * \param dev a device
665 * \param endpoint address of the endpoint in question
666 * \returns the wMaxPacketSize value
667 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
668 * \returns LIBUSB_ERROR_OTHER on other failure
670 API_EXPORTED int libusb_get_max_packet_size(libusb_device *dev,
671 unsigned char endpoint)
673 struct libusb_config_descriptor *config;
674 const struct libusb_endpoint_descriptor *ep;
677 r = libusb_get_active_config_descriptor(dev, &config);
679 usbi_err(DEVICE_CTX(dev),
680 "could not retrieve active config descriptor");
681 return LIBUSB_ERROR_OTHER;
684 ep = find_endpoint(config, endpoint);
686 return LIBUSB_ERROR_NOT_FOUND;
688 r = ep->wMaxPacketSize;
689 libusb_free_config_descriptor(config);
694 * Calculate the maximum packet size which a specific endpoint is capable is
695 * sending or receiving in the duration of 1 microframe
697 * Only the active configution is examined. The calculation is based on the
698 * wMaxPacketSize field in the endpoint descriptor as described in section
699 * 9.6.6 in the USB 2.0 specifications.
701 * If acting on an isochronous or interrupt endpoint, this function will
702 * multiply the value found in bits 0:10 by the number of transactions per
703 * microframe (determined by bits 11:12). Otherwise, this function just
704 * returns the numeric value found in bits 0:10.
706 * This function is useful for setting up isochronous transfers, for example
707 * you might pass the return value from this function to
708 * libusb_set_iso_packet_lengths() in order to set the length field of every
709 * isochronous packet in a transfer.
713 * \param dev a device
714 * \param endpoint address of the endpoint in question
715 * \returns the maximum packet size which can be sent/received on this endpoint
716 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
717 * \returns LIBUSB_ERROR_OTHER on other failure
719 API_EXPORTED int libusb_get_max_iso_packet_size(libusb_device *dev,
720 unsigned char endpoint)
722 struct libusb_config_descriptor *config;
723 const struct libusb_endpoint_descriptor *ep;
724 enum libusb_transfer_type ep_type;
728 r = libusb_get_active_config_descriptor(dev, &config);
730 usbi_err(DEVICE_CTX(dev),
731 "could not retrieve active config descriptor");
732 return LIBUSB_ERROR_OTHER;
735 ep = find_endpoint(config, endpoint);
737 return LIBUSB_ERROR_NOT_FOUND;
739 val = ep->wMaxPacketSize;
740 ep_type = ep->bmAttributes & 0x3;
741 libusb_free_config_descriptor(config);
744 if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
745 || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
746 r *= (1 + ((val >> 11) & 3));
751 * Increment the reference count of a device.
752 * \param dev the device to reference
753 * \returns the same device
755 API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev)
757 pthread_mutex_lock(&dev->lock);
759 pthread_mutex_unlock(&dev->lock);
764 * Decrement the reference count of a device. If the decrement operation
765 * causes the reference count to reach zero, the device shall be destroyed.
766 * \param dev the device to unreference
768 API_EXPORTED void libusb_unref_device(libusb_device *dev)
775 pthread_mutex_lock(&dev->lock);
776 refcnt = --dev->refcnt;
777 pthread_mutex_unlock(&dev->lock);
780 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
782 if (usbi_backend->destroy_device)
783 usbi_backend->destroy_device(dev);
785 pthread_mutex_lock(&dev->ctx->usb_devs_lock);
786 list_del(&dev->list);
787 pthread_mutex_unlock(&dev->ctx->usb_devs_lock);
794 * Open a device and obtain a device handle. A handle allows you to perform
795 * I/O on the device in question.
797 * Internally, this function adds a reference to the device and makes it
798 * available to you through libusb_get_device(). This reference is removed
799 * during libusb_close().
801 * This is a non-blocking function; no requests are sent over the bus.
803 * \param dev the device to open
804 * \param handle output location for the returned device handle pointer. Only
805 * populated when the return code is 0.
806 * \returns 0 on success
807 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
808 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
809 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
810 * \returns another LIBUSB_ERROR code on other failure
812 API_EXPORTED int libusb_open(libusb_device *dev, libusb_device_handle **handle)
814 struct libusb_context *ctx = DEVICE_CTX(dev);
815 struct libusb_device_handle *_handle;
816 size_t priv_size = usbi_backend->device_handle_priv_size;
817 unsigned char dummy = 1;
819 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
821 _handle = malloc(sizeof(*_handle) + priv_size);
823 return LIBUSB_ERROR_NO_MEM;
825 r = pthread_mutex_init(&_handle->lock, NULL);
827 return LIBUSB_ERROR_OTHER;
829 _handle->dev = libusb_ref_device(dev);
830 _handle->claimed_interfaces = 0;
831 memset(&_handle->os_priv, 0, priv_size);
833 r = usbi_backend->open(_handle);
835 libusb_unref_device(dev);
840 pthread_mutex_lock(&ctx->open_devs_lock);
841 list_add(&_handle->list, &ctx->open_devs);
842 pthread_mutex_unlock(&ctx->open_devs_lock);
846 /* At this point, we want to interrupt any existing event handlers so
847 * that they realise the addition of the new device's poll fd. One
848 * example when this is desirable is if the user is running a separate
849 * dedicated libusb events handling thread, which is running with a long
850 * or infinite timeout. We want to interrupt that iteration of the loop,
851 * so that it picks up the new fd, and then continues. */
853 /* record that we are messing with poll fds */
854 pthread_mutex_lock(&ctx->pollfd_modify_lock);
855 ctx->pollfd_modify++;
856 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
858 /* write some data on control pipe to interrupt event handlers */
859 r = write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
861 usbi_warn(ctx, "internal signalling write failed");
862 pthread_mutex_lock(&ctx->pollfd_modify_lock);
863 ctx->pollfd_modify--;
864 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
868 /* take event handling lock */
869 libusb_lock_events(ctx);
871 /* read the dummy data */
872 r = read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
874 usbi_warn(ctx, "internal signalling read failed");
876 /* we're done with modifying poll fds */
877 pthread_mutex_lock(&ctx->pollfd_modify_lock);
878 ctx->pollfd_modify--;
879 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
881 /* Release event handling lock and wake up event waiters */
882 libusb_unlock_events(ctx);
888 * Convenience function for finding a device with a particular
889 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
890 * for those scenarios where you are using libusb to knock up a quick test
891 * application - it allows you to avoid calling libusb_get_device_list() and
892 * worrying about traversing/freeing the list.
894 * This function has limitations and is hence not intended for use in real
895 * applications: if multiple devices have the same IDs it will only
896 * give you the first one, etc.
898 * \param ctx the context to operate on, or NULL for the default context
899 * \param vendor_id the idVendor value to search for
900 * \param product_id the idProduct value to search for
901 * \returns a handle for the first found device, or NULL on error or if the
902 * device could not be found. */
903 API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid(
904 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
906 struct libusb_device **devs;
907 struct libusb_device *found = NULL;
908 struct libusb_device *dev;
909 struct libusb_device_handle *handle = NULL;
913 if (libusb_get_device_list(ctx, &devs) < 0)
916 while ((dev = devs[i++]) != NULL) {
917 struct libusb_device_descriptor desc;
918 r = libusb_get_device_descriptor(dev, &desc);
921 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
928 r = libusb_open(found, &handle);
934 libusb_free_device_list(devs, 1);
938 static void do_close(struct libusb_context *ctx,
939 struct libusb_device_handle *dev_handle)
941 pthread_mutex_lock(&ctx->open_devs_lock);
942 list_del(&dev_handle->list);
943 pthread_mutex_unlock(&ctx->open_devs_lock);
945 usbi_backend->close(dev_handle);
946 libusb_unref_device(dev_handle->dev);
951 * Close a device handle. Should be called on all open handles before your
954 * Internally, this function destroys the reference that was added by
955 * libusb_open() on the given device.
957 * This is a non-blocking function; no requests are sent over the bus.
959 * \param dev_handle the handle to close
961 API_EXPORTED void libusb_close(libusb_device_handle *dev_handle)
963 struct libusb_context *ctx;
964 unsigned char dummy = 1;
971 ctx = HANDLE_CTX(dev_handle);
973 /* Similarly to libusb_open(), we want to interrupt all event handlers
974 * at this point. More importantly, we want to perform the actual close of
975 * the device while holding the event handling lock (preventing any other
976 * thread from doing event handling) because we will be removing a file
977 * descriptor from the polling loop. */
979 /* record that we are messing with poll fds */
980 pthread_mutex_lock(&ctx->pollfd_modify_lock);
981 ctx->pollfd_modify++;
982 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
984 /* write some data on control pipe to interrupt event handlers */
985 r = write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
987 usbi_warn(ctx, "internal signalling write failed, closing anyway");
988 do_close(ctx, dev_handle);
989 pthread_mutex_lock(&ctx->pollfd_modify_lock);
990 ctx->pollfd_modify--;
991 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
995 /* take event handling lock */
996 libusb_lock_events(ctx);
998 /* read the dummy data */
999 r = read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1001 usbi_warn(ctx, "internal signalling read failed, closing anyway");
1003 /* Close the device */
1004 do_close(ctx, dev_handle);
1006 /* we're done with modifying poll fds */
1007 pthread_mutex_lock(&ctx->pollfd_modify_lock);
1008 ctx->pollfd_modify--;
1009 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
1011 /* Release event handling lock and wake up event waiters */
1012 libusb_unlock_events(ctx);
1016 * Get the underlying device for a handle. This function does not modify
1017 * the reference count of the returned device, so do not feel compelled to
1018 * unreference it when you are done.
1019 * \param dev_handle a device handle
1020 * \returns the underlying device
1022 API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle)
1024 return dev_handle->dev;
1028 * Determine the bConfigurationValue of the currently active configuration.
1030 * You could formulate your own control request to obtain this information,
1031 * but this function has the advantage that it may be able to retrieve the
1032 * information from operating system caches (no I/O involved).
1034 * If the OS does not cache this information, then this function will block
1035 * while a control transfer is submitted to retrieve the information.
1037 * This function will return a value of 0 in the <tt>config</tt> output
1038 * parameter if the device is in unconfigured state.
1040 * \param dev a device handle
1041 * \param config output location for the bConfigurationValue of the active
1042 * configuration (only valid for return code 0)
1043 * \returns 0 on success
1044 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1045 * \returns another LIBUSB_ERROR code on other failure
1047 API_EXPORTED int libusb_get_configuration(libusb_device_handle *dev,
1050 int r = LIBUSB_ERROR_NOT_SUPPORTED;
1053 if (usbi_backend->get_configuration)
1054 r = usbi_backend->get_configuration(dev, config);
1056 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1058 usbi_dbg("falling back to control message");
1059 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1060 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1062 usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
1063 r = LIBUSB_ERROR_IO;
1064 } else if (r == 1) {
1068 usbi_dbg("control failed, error %d", r);
1073 usbi_dbg("active config %d", *config);
1079 * Set the active configuration for a device.
1081 * The operating system may or may not have already set an active
1082 * configuration on the device. It is up to your application to ensure the
1083 * correct configuration is selected before you attempt to claim interfaces
1084 * and perform other operations.
1086 * If you call this function on a device already configured with the selected
1087 * configuration, then this function will act as a lightweight device reset:
1088 * it will issue a SET_CONFIGURATION request using the current configuration,
1089 * causing most USB-related device state to be reset (altsetting reset to zero,
1090 * endpoint halts cleared, toggles reset).
1092 * You cannot change/reset configuration if your application has claimed
1093 * interfaces - you should free them with libusb_release_interface() first.
1094 * You cannot change/reset configuration if other applications or drivers have
1095 * claimed interfaces.
1097 * A configuration value of -1 will put the device in unconfigured state.
1098 * The USB specifications state that a configuration value of 0 does this,
1099 * however buggy devices exist which actually have a configuration 0.
1101 * You should always use this function rather than formulating your own
1102 * SET_CONFIGURATION control request. This is because the underlying operating
1103 * system needs to know when such changes happen.
1105 * This is a blocking function.
1107 * \param dev a device handle
1108 * \param configuration the bConfigurationValue of the configuration you
1109 * wish to activate, or -1 if you wish to put the device in unconfigured state
1110 * \returns 0 on success
1111 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1112 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1113 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1114 * \returns another LIBUSB_ERROR code on other failure
1116 API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev,
1119 usbi_dbg("configuration %d", configuration);
1120 return usbi_backend->set_configuration(dev, configuration);
1124 * Claim an interface on a given device handle. You must claim the interface
1125 * you wish to use before you can perform I/O on any of its endpoints.
1127 * It is legal to attempt to claim an already-claimed interface, in which
1128 * case libusb just returns 0 without doing anything.
1130 * Claiming of interfaces is a purely logical operation; it does not cause
1131 * any requests to be sent over the bus. Interface claiming is used to
1132 * instruct the underlying operating system that your application wishes
1133 * to take ownership of the interface.
1135 * This is a non-blocking function.
1137 * \param dev a device handle
1138 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1140 * \returns 0 on success
1141 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1142 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1144 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1145 * \returns a LIBUSB_ERROR code on other failure
1147 API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev,
1148 int interface_number)
1152 usbi_dbg("interface %d", interface_number);
1153 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1154 return LIBUSB_ERROR_INVALID_PARAM;
1156 pthread_mutex_lock(&dev->lock);
1157 if (dev->claimed_interfaces & (1 << interface_number))
1160 r = usbi_backend->claim_interface(dev, interface_number);
1162 dev->claimed_interfaces |= 1 << interface_number;
1165 pthread_mutex_unlock(&dev->lock);
1170 * Release an interface previously claimed with libusb_claim_interface(). You
1171 * should release all claimed interfaces before closing a device handle.
1173 * This is a blocking function. A SET_INTERFACE control request will be sent
1174 * to the device, resetting interface state to the first alternate setting.
1176 * \param dev a device handle
1177 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1178 * previously-claimed interface
1179 * \returns 0 on success
1180 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1181 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1182 * \returns another LIBUSB_ERROR code on other failure
1184 API_EXPORTED int libusb_release_interface(libusb_device_handle *dev,
1185 int interface_number)
1189 usbi_dbg("interface %d", interface_number);
1190 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1191 return LIBUSB_ERROR_INVALID_PARAM;
1193 pthread_mutex_lock(&dev->lock);
1194 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1195 r = LIBUSB_ERROR_NOT_FOUND;
1199 r = usbi_backend->release_interface(dev, interface_number);
1201 dev->claimed_interfaces &= ~(1 << interface_number);
1204 pthread_mutex_unlock(&dev->lock);
1209 * Activate an alternate setting for an interface. The interface must have
1210 * been previously claimed with libusb_claim_interface().
1212 * You should always use this function rather than formulating your own
1213 * SET_INTERFACE control request. This is because the underlying operating
1214 * system needs to know when such changes happen.
1216 * This is a blocking function.
1218 * \param dev a device handle
1219 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1220 * previously-claimed interface
1221 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1222 * setting to activate
1223 * \returns 0 on success
1224 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1225 * requested alternate setting does not exist
1226 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1227 * \returns another LIBUSB_ERROR code on other failure
1229 API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev,
1230 int interface_number, int alternate_setting)
1232 usbi_dbg("interface %d altsetting %d",
1233 interface_number, alternate_setting);
1234 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1235 return LIBUSB_ERROR_INVALID_PARAM;
1237 pthread_mutex_lock(&dev->lock);
1238 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1239 pthread_mutex_unlock(&dev->lock);
1240 return LIBUSB_ERROR_NOT_FOUND;
1242 pthread_mutex_unlock(&dev->lock);
1244 return usbi_backend->set_interface_altsetting(dev, interface_number,
1249 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1250 * are unable to receive or transmit data until the halt condition is stalled.
1252 * You should cancel all pending transfers before attempting to clear the halt
1255 * This is a blocking function.
1257 * \param dev a device handle
1258 * \param endpoint the endpoint to clear halt status
1259 * \returns 0 on success
1260 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1261 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1262 * \returns another LIBUSB_ERROR code on other failure
1264 API_EXPORTED int libusb_clear_halt(libusb_device_handle *dev,
1265 unsigned char endpoint)
1267 usbi_dbg("endpoint %x", endpoint);
1268 return usbi_backend->clear_halt(dev, endpoint);
1272 * Perform a USB port reset to reinitialize a device. The system will attempt
1273 * to restore the previous configuration and alternate settings after the
1274 * reset has completed.
1276 * If the reset fails, the descriptors change, or the previous state cannot be
1277 * restored, the device will appear to be disconnected and reconnected. This
1278 * means that the device handle is no longer valid (you should close it) and
1279 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1280 * when this is the case.
1282 * This is a blocking function which usually incurs a noticeable delay.
1284 * \param dev a handle of the device to reset
1285 * \returns 0 on success
1286 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1287 * device has been disconnected
1288 * \returns another LIBUSB_ERROR code on other failure
1290 API_EXPORTED int libusb_reset_device(libusb_device_handle *dev)
1293 return usbi_backend->reset_device(dev);
1297 * Determine if a kernel driver is active on an interface. If a kernel driver
1298 * is active, you cannot claim the interface, and libusb will be unable to
1301 * \param dev a device handle
1302 * \param interface the interface to check
1303 * \returns 0 if no kernel driver is active
1304 * \returns 1 if a kernel driver is active
1305 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1306 * \returns another LIBUSB_ERROR code on other failure
1307 * \see libusb_detach_kernel_driver()
1309 API_EXPORTED int libusb_kernel_driver_active(libusb_device_handle *dev,
1312 usbi_dbg("interface %d", interface);
1313 if (usbi_backend->kernel_driver_active)
1314 return usbi_backend->kernel_driver_active(dev, interface);
1316 return LIBUSB_ERROR_NOT_SUPPORTED;
1320 * Detach a kernel driver from an interface. If successful, you will then be
1321 * able to claim the interface and perform I/O.
1323 * \param dev a device handle
1324 * \param interface the interface to detach the driver from
1325 * \returns 0 on success
1326 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1327 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1328 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1329 * \returns another LIBUSB_ERROR code on other failure
1330 * \see libusb_kernel_driver_active()
1332 API_EXPORTED int libusb_detach_kernel_driver(libusb_device_handle *dev,
1335 usbi_dbg("interface %d", interface);
1336 if (usbi_backend->detach_kernel_driver)
1337 return usbi_backend->detach_kernel_driver(dev, interface);
1339 return LIBUSB_ERROR_NOT_SUPPORTED;
1343 * Re-attach an interface's kernel driver, which was previously detached
1344 * using libusb_detach_kernel_driver().
1346 * \param dev a device handle
1347 * \param interface the interface to attach the driver from
1348 * \returns 0 on success
1349 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1350 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1351 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1352 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1353 * interface is claimed by a program or driver
1354 * \returns another LIBUSB_ERROR code on other failure
1355 * \see libusb_kernel_driver_active()
1357 API_EXPORTED int libusb_attach_kernel_driver(libusb_device_handle *dev,
1360 usbi_dbg("interface %d", interface);
1361 if (usbi_backend->attach_kernel_driver)
1362 return usbi_backend->attach_kernel_driver(dev, interface);
1364 return LIBUSB_ERROR_NOT_SUPPORTED;
1368 * Set message verbosity.
1369 * - Level 0: no messages ever printed by the library (default)
1370 * - Level 1: error messages are printed to stderr
1371 * - Level 2: warning and error messages are printed to stderr
1372 * - Level 3: informational messages are printed to stdout, warning and error
1373 * messages are printed to stderr
1375 * The default level is 0, which means no messages are ever printed. If you
1376 * choose to increase the message verbosity level, ensure that your
1377 * application does not close the stdout/stderr file descriptors.
1379 * You are advised to set level 3. libusb is conservative with its message
1380 * logging and most of the time, will only log messages that explain error
1381 * conditions and other oddities. This will help you debug your software.
1383 * If the LIBUSB_DEBUG environment variable was set when libusb was
1384 * initialized, this function does nothing: the message verbosity is fixed
1385 * to the value in the environment variable.
1387 * If libusb was compiled without any message logging, this function does
1388 * nothing: you'll never get any messages.
1390 * If libusb was compiled with verbose debug message logging, this function
1391 * does nothing: you'll always get messages from all levels.
1393 * \param ctx the context to operate on, or NULL for the default context
1394 * \param level debug level to set
1396 API_EXPORTED void libusb_set_debug(libusb_context *ctx, int level)
1398 USBI_GET_CONTEXT(ctx);
1399 if (!ctx->debug_fixed)
1404 * Initialize libusb. This function must be called before calling any other
1406 * \param context Optional output location for context pointer.
1407 * Only valid on return code 0.
1408 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1410 API_EXPORTED int libusb_init(libusb_context **context)
1412 char *dbg = getenv("LIBUSB_DEBUG");
1413 struct libusb_context *ctx = malloc(sizeof(*ctx));
1417 return LIBUSB_ERROR_NO_MEM;
1418 memset(ctx, 0, sizeof(*ctx));
1421 ctx->debug = atoi(dbg);
1423 ctx->debug_fixed = 1;
1428 if (usbi_backend->init) {
1429 r = usbi_backend->init(ctx);
1434 pthread_mutex_init(&ctx->usb_devs_lock, NULL);
1435 pthread_mutex_init(&ctx->open_devs_lock, NULL);
1436 list_init(&ctx->usb_devs);
1437 list_init(&ctx->open_devs);
1439 r = usbi_io_init(ctx);
1441 if (usbi_backend->exit)
1442 usbi_backend->exit();
1446 pthread_mutex_lock(&default_context_lock);
1447 if (!usbi_default_context) {
1448 usbi_dbg("created default context");
1449 usbi_default_context = ctx;
1451 pthread_mutex_unlock(&default_context_lock);
1463 * Deinitialize libusb. Should be called after closing all open devices and
1464 * before your application terminates.
1465 * \param ctx the context to deinitialize, or NULL for the default context
1467 API_EXPORTED void libusb_exit(struct libusb_context *ctx)
1469 USBI_GET_CONTEXT(ctx);
1472 /* a little sanity check. doesn't bother with open_devs locking because
1473 * unless there is an application bug, nobody will be accessing this. */
1474 if (!list_empty(&ctx->open_devs))
1475 usbi_warn(ctx, "application left some devices open");
1478 if (usbi_backend->exit)
1479 usbi_backend->exit();
1481 pthread_mutex_lock(&default_context_lock);
1482 if (ctx == usbi_default_context) {
1483 usbi_dbg("freeing default context");
1484 usbi_default_context = NULL;
1486 pthread_mutex_unlock(&default_context_lock);
1491 void usbi_log(struct libusb_context *ctx, enum usbi_log_level level,
1492 const char *function, const char *format, ...)
1495 FILE *stream = stdout;
1498 #ifndef ENABLE_DEBUG_LOGGING
1499 USBI_GET_CONTEXT(ctx);
1502 if (level == LOG_LEVEL_WARNING && ctx->debug < 2)
1504 if (level == LOG_LEVEL_INFO && ctx->debug < 3)
1509 case LOG_LEVEL_INFO:
1512 case LOG_LEVEL_WARNING:
1516 case LOG_LEVEL_ERROR:
1520 case LOG_LEVEL_DEBUG:
1530 fprintf(stream, "libusb:%s [%s] ", prefix, function);
1532 va_start (args, format);
1533 vfprintf(stream, format, args);
1536 fprintf(stream, "\n");