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;
38 #error "Unsupported OS"
41 struct libusb_context *usbi_default_context = NULL;
42 static pthread_mutex_t default_context_lock = PTHREAD_MUTEX_INITIALIZER;
45 * \mainpage libusb-1.0 API Reference
47 * \section intro Introduction
49 * libusb is an open source library that allows you to communicate with USB
50 * devices from userspace. For more info, see the
51 * <a href="http://libusb.sourceforge.net">libusb homepage</a>.
53 * This documentation is aimed at application developers wishing to
54 * communicate with USB peripherals from their own software. After reviewing
55 * this documentation, feedback and questions can be sent to the
56 * <a href="http://sourceforge.net/mail/?group_id=1674">libusb-devel mailing
59 * This documentation assumes knowledge of how to operate USB devices from
60 * a software standpoint (descriptors, configurations, interfaces, endpoints,
61 * control/bulk/interrupt/isochronous transfers, etc). Full information
62 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 2.0
63 * Specification</a> which is available for free download. You can probably
64 * find less verbose introductions by searching the web.
66 * \section features Library features
68 * - All transfer types supported (control/bulk/interrupt/isochronous)
69 * - 2 transfer interfaces:
70 * -# Synchronous (simple)
71 * -# Asynchronous (more complicated, but more powerful)
72 * - Thread safe (although the asynchronous interface means that you
73 * usually won't need to thread)
74 * - Lightweight with lean API
75 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
77 * \section gettingstarted Getting Started
79 * To begin reading the API documentation, start with the Modules page which
80 * links to the different categories of libusb's functionality.
82 * One decision you will have to make is whether to use the synchronous
83 * or the asynchronous data transfer interface. The \ref io documentation
84 * provides some insight into this topic.
86 * Some example programs can be found in the libusb source distribution under
87 * the "examples" subdirectory. The libusb homepage includes a list of
88 * real-life project examples which use libusb.
90 * \section errorhandling Error handling
92 * libusb functions typically return 0 on success or a negative error code
93 * on failure. These negative error codes relate to LIBUSB_ERROR constants
94 * which are listed on the \ref misc "miscellaneous" documentation page.
96 * \section msglog Debug message logging
98 * libusb does not log any messages by default. Your application is therefore
99 * free to close stdout/stderr and those descriptors may be reused without
102 * The libusb_set_debug() function can be used to enable stdout/stderr logging
103 * of certain messages. Under standard configuration, libusb doesn't really
104 * log much at all, so you are advised to use this function to enable all
105 * error/warning/informational messages. It will help you debug problems with
108 * The logged messages are unstructured. There is no one-to-one correspondence
109 * between messages being logged and success or failure return codes from
110 * libusb functions. There is no format to the messages, so you should not
111 * try to capture or parse them. They are not and will not be localized.
112 * These messages are not suitable for being passed to your application user;
113 * instead, you should interpret the error codes returned from libusb functions
114 * and provide appropriate notification to the user. The messages are simply
115 * there to aid you as a programmer, and if you're confused because you're
116 * getting a strange error code from a libusb function, enabling message
117 * logging may give you a suitable explanation.
119 * The LIBUSB_DEBUG environment variable can be used to enable message logging
120 * at run-time. This environment variable should be set to a number, which is
121 * interpreted the same as the libusb_set_debug() parameter. When this
122 * environment variable is set, the message logging verbosity level is fixed
123 * and libusb_set_debug() effectively does nothing.
125 * libusb can be compiled without any logging functions, useful for embedded
126 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
127 * variable have no effects.
129 * libusb can also be compiled with verbose debugging messages. When the
130 * library is compiled in this way, all messages of all verbosities are always
131 * logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable have
134 * \section remarks Other remarks
136 * libusb does have imperfections. The \ref caveats "caveats" page attempts
141 * \page caveats Caveats
143 * \section devresets Device resets
145 * The libusb_reset_device() function allows you to reset a device. If your
146 * program has to call such a function, it should obviously be aware that
147 * the reset will cause device state to change (e.g. register values may be
150 * The problem is that any other program could reset the device your program
151 * is working with, at any time. libusb does not offer a mechanism to inform
152 * you when this has happened, so if someone else resets your device it will
153 * not be clear to your own program why the device state has changed.
155 * Ultimately, this is a limitation of writing drivers in userspace.
156 * Separation from the USB stack in the underlying kernel makes it difficult
157 * for the operating system to deliver such notifications to your program.
158 * The Linux kernel USB stack allows such reset notifications to be delivered
159 * to in-kernel USB drivers, but it is not clear how such notifications could
160 * be delivered to second-class drivers that live in userspace.
162 * \section blockonly Blocking-only functionality
164 * The functionality listed below is only available through synchronous,
165 * blocking functions. There are no asynchronous/non-blocking alternatives,
166 * and no clear ways of implementing these.
168 * - Configuration activation (libusb_set_configuration())
169 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
170 * - Releasing of interfaces (libusb_release_interface())
171 * - Clearing of halt/stall condition (libusb_clear_halt())
172 * - Device resets (libusb_reset_device())
174 * \section nohotplug No hotplugging
176 * libusb-1.0 lacks functionality for providing notifications of when devices
177 * are added or removed. This functionality is planned to be implemented
180 * That said, there is basic disconnection handling for open device handles:
181 * - If there are ongoing transfers, libusb's handle_events loop will detect
182 * disconnections and complete ongoing transfers with the
183 * LIBUSB_TRANSFER_NO_DEVICE status code.
184 * - Many functions such as libusb_set_configuration() return the special
185 * LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected.
187 * \section configsel Configuration selection and handling
189 * When libusb presents a device handle to an application, there is a chance
190 * that the corresponding device may be in unconfigured state. For devices
191 * with multiple configurations, there is also a chance that the configuration
192 * currently selected is not the one that the application wants to use.
194 * The obvious solution is to add a call to libusb_set_configuration() early
195 * on during your device initialization routines, but there are caveats to
197 * -# If the device is already in the desired configuration, calling
198 * libusb_set_configuration() using the same configuration value will cause
199 * a lightweight device reset. This may not be desirable behaviour.
200 * -# libusb will be unable to change configuration if the device is in
201 * another configuration and other programs or drivers have claimed
202 * interfaces under that configuration.
203 * -# In the case where the desired configuration is already active, libusb
204 * may not even be able to perform a lightweight device reset. For example,
205 * take my USB keyboard with fingerprint reader: I'm interested in driving
206 * the fingerprint reader interface through libusb, but the kernel's
207 * USB-HID driver will almost always have claimed the keyboard interface.
208 * Because the kernel has claimed an interface, it is not even possible to
209 * perform the lightweight device reset, so libusb_set_configuration() will
210 * fail. (Luckily the device in question only has a single configuration.)
212 * One solution to some of the above problems is to consider the currently
213 * active configuration. If the configuration we want is already active, then
214 * we don't have to select any configuration:
216 cfg = libusb_get_configuration(dev);
218 libusb_set_configuration(dev, desired);
221 * This is probably suitable for most scenarios, but is inherently racy:
222 * another application or driver may change the selected configuration
223 * <em>after</em> the libusb_get_configuration() call.
225 * Even in cases where libusb_set_configuration() succeeds, consider that other
226 * applications or drivers may change configuration after your application
227 * calls libusb_set_configuration().
229 * One possible way to lock your device into a specific configuration is as
231 * -# Set the desired configuration (or use the logic above to realise that
232 * it is already in the desired configuration)
233 * -# Claim the interface that you wish to use
234 * -# Check that the currently active configuration is the one that you want
237 * The above method works because once an interface is claimed, no application
238 * or driver is able to select another configuration.
242 * \page contexts Contexts
244 * It is possible that libusb may be used simultaneously from two independent
245 * libraries linked into the same executable. For example, if your application
246 * has a plugin-like system which allows the user to dynamically load a range
247 * of modules into your program, it is feasible that two independently
248 * developed modules may both use libusb.
250 * libusb is written to allow for these multiple user scenarios. The two
251 * "instances" of libusb will not interfere: libusb_set_debug() calls
252 * from one user will not affect the same settings for other users, other
253 * users can continue using libusb after one of them calls libusb_exit(), etc.
255 * This is made possible through libusb's <em>context</em> concept. When you
256 * call libusb_init(), you are (optionally) given a context. You can then pass
257 * this context pointer back into future libusb functions.
259 * In order to keep things simple for more simplistic applications, it is
260 * legal to pass NULL to all functions requiring a context pointer (as long as
261 * you're sure no other code will attempt to use libusb from the same process).
262 * When you pass NULL, the default context will be used. The default context
263 * is created the first time a process calls libusb_init() when no other
264 * context is alive. Contexts are destroyed during libusb_exit().
266 * You may be wondering why only a subset of libusb functions require a
267 * context pointer in their function definition. Internally, libusb stores
268 * context pointers in other objects (e.g. libusb_device instances) and hence
269 * can infer the context from those objects.
273 * @defgroup lib Library initialization/deinitialization
274 * This page details how to initialize and deinitialize libusb. Initialization
275 * must be performed before using any libusb functionality, and similarly you
276 * must not call any libusb functions after deinitialization.
280 * @defgroup dev Device handling and enumeration
281 * The functionality documented below is designed to help with the following
283 * - Enumerating the USB devices currently attached to the system
284 * - Choosing a device to operate from your software
285 * - Opening and closing the chosen device
287 * \section nutshell In a nutshell...
289 * The description below really makes things sound more complicated than they
290 * actually are. The following sequence of function calls will be suitable
291 * for almost all scenarios and does not require you to have such a deep
292 * understanding of the resource management issues:
295 libusb_device **list;
296 libusb_device *found = NULL;
297 size_t cnt = libusb_get_device_list(NULL, &list);
303 for (i = 0; i < cnt; i++) {
304 libusb_device *device = list[i];
305 if (is_interesting(device)) {
312 libusb_device_handle *handle;
314 err = libusb_open(found, &handle);
320 libusb_free_device_list(list, 1);
323 * The two important points:
324 * - You asked libusb_free_device_list() to unreference the devices (2nd
326 * - You opened the device before freeing the list and unreferencing the
329 * If you ended up with a handle, you can now proceed to perform I/O on the
332 * \section devshandles Devices and device handles
333 * libusb has a concept of a USB device, represented by the
334 * \ref libusb_device opaque type. A device represents a USB device that
335 * is currently or was previously connected to the system. Using a reference
336 * to a device, you can determine certain information about the device (e.g.
337 * you can read the descriptor data).
339 * The libusb_get_device_list() function can be used to obtain a list of
340 * devices currently connected to the system. This is known as device
343 * Just because you have a reference to a device does not mean it is
344 * necessarily usable. The device may have been unplugged, you may not have
345 * permission to operate such device, or another program or driver may be
348 * When you've found a device that you'd like to operate, you must ask
349 * libusb to open the device using the libusb_open() function. Assuming
350 * success, libusb then returns you a <em>device handle</em>
351 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
352 * operate on the handle rather than the original device pointer.
354 * \section devref Device discovery and reference counting
356 * Device discovery (i.e. calling libusb_get_device_list()) returns a
357 * freshly-allocated list of devices. The list itself must be freed when
358 * you are done with it. libusb also needs to know when it is OK to free
359 * the contents of the list - the devices themselves.
361 * To handle these issues, libusb provides you with two separate items:
362 * - A function to free the list itself
363 * - A reference counting system for the devices inside
365 * New devices presented by the libusb_get_device_list() function all have a
366 * reference count of 1. You can increase and decrease reference count using
367 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
368 * its reference count reaches 0.
370 * With the above information in mind, the process of opening a device can
371 * be viewed as follows:
372 * -# Discover devices using libusb_get_device_list().
373 * -# Choose the device that you want to operate, and call libusb_open().
374 * -# Unref all devices in the discovered device list.
375 * -# Free the discovered device list.
377 * The order is important - you must not unreference the device before
378 * attempting to open it, because unreferencing it may destroy the device.
380 * For convenience, the libusb_free_device_list() function includes a
381 * parameter to optionally unreference all the devices in the list before
382 * freeing the list itself. This combines steps 3 and 4 above.
384 * As an implementation detail, libusb_open() actually adds a reference to
385 * the device in question. This is because the device remains available
386 * through the handle via libusb_get_device(). The reference is deleted during
390 /** @defgroup misc Miscellaneous */
392 /* we traverse usbfs without knowing how many devices we are going to find.
393 * so we create this discovered_devs model which is similar to a linked-list
394 * which grows when required. it can be freed once discovery has completed,
395 * eliminating the need for a list node in the libusb_device structure
397 #define DISCOVERED_DEVICES_SIZE_STEP 8
399 static struct discovered_devs *discovered_devs_alloc(void)
401 struct discovered_devs *ret =
402 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
406 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
411 /* append a device to the discovered devices collection. may realloc itself,
412 * returning new discdevs. returns NULL on realloc failure. */
413 struct discovered_devs *discovered_devs_append(
414 struct discovered_devs *discdevs, struct libusb_device *dev)
416 size_t len = discdevs->len;
419 /* if there is space, just append the device */
420 if (len < discdevs->capacity) {
421 discdevs->devices[len] = libusb_ref_device(dev);
426 /* exceeded capacity, need to grow */
427 usbi_dbg("need to increase capacity");
428 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
429 discdevs = realloc(discdevs,
430 sizeof(*discdevs) + (sizeof(void *) * capacity));
432 discdevs->capacity = capacity;
433 discdevs->devices[len] = libusb_ref_device(dev);
440 static void discovered_devs_free(struct discovered_devs *discdevs)
444 for (i = 0; i < discdevs->len; i++)
445 libusb_unref_device(discdevs->devices[i]);
450 /* Allocate a new device with a specific session ID. The returned device has
451 * a reference count of 1. */
452 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
453 unsigned long session_id)
455 size_t priv_size = usbi_backend->device_priv_size;
456 struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
462 r = pthread_mutex_init(&dev->lock, NULL);
468 dev->session_data = session_id;
469 memset(&dev->os_priv, 0, priv_size);
471 pthread_mutex_lock(&ctx->usb_devs_lock);
472 list_add(&dev->list, &ctx->usb_devs);
473 pthread_mutex_unlock(&ctx->usb_devs_lock);
477 /* Perform some final sanity checks on a newly discovered device. If this
478 * function fails (negative return code), the device should not be added
479 * to the discovered device list. */
480 int usbi_sanitize_device(struct libusb_device *dev)
483 unsigned char raw_desc[DEVICE_DESC_LENGTH];
484 uint8_t num_configurations;
487 r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
491 num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
492 if (num_configurations > USB_MAXCONFIG) {
493 usbi_err(DEVICE_CTX(dev), "too many configurations");
494 return LIBUSB_ERROR_IO;
495 } else if (num_configurations < 1) {
496 usbi_dbg("no configurations?");
497 return LIBUSB_ERROR_IO;
500 dev->num_configurations = num_configurations;
504 /* Examine libusb's internal list of known devices, looking for one with
505 * a specific session ID. Returns the matching device if it was found, and
507 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
508 unsigned long session_id)
510 struct libusb_device *dev;
511 struct libusb_device *ret = NULL;
513 pthread_mutex_lock(&ctx->usb_devs_lock);
514 list_for_each_entry(dev, &ctx->usb_devs, list)
515 if (dev->session_data == session_id) {
519 pthread_mutex_unlock(&ctx->usb_devs_lock);
525 * Returns a list of USB devices currently attached to the system. This is
526 * your entry point into finding a USB device to operate.
528 * You are expected to unreference all the devices when you are done with
529 * them, and then free the list with libusb_free_device_list(). Note that
530 * libusb_free_device_list() can unref all the devices for you. Be careful
531 * not to unreference a device you are about to open until after you have
534 * This return value of this function indicates the number of devices in
535 * the resultant list. The list is actually one element larger, as it is
538 * \param ctx the context to operate on, or NULL for the default context
539 * \param list output location for a list of devices. Must be later freed with
540 * libusb_free_device_list().
541 * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
542 * on memory allocation failure.
544 API_EXPORTED ssize_t libusb_get_device_list(libusb_context *ctx,
545 libusb_device ***list)
547 struct discovered_devs *discdevs = discovered_devs_alloc();
548 struct libusb_device **ret;
552 USBI_GET_CONTEXT(ctx);
556 return LIBUSB_ERROR_NO_MEM;
558 r = usbi_backend->get_device_list(ctx, &discdevs);
564 /* convert discovered_devs into a list */
566 ret = malloc(sizeof(void *) * (len + 1));
568 len = LIBUSB_ERROR_NO_MEM;
573 for (i = 0; i < len; i++) {
574 struct libusb_device *dev = discdevs->devices[i];
575 ret[i] = libusb_ref_device(dev);
580 discovered_devs_free(discdevs);
585 * Frees a list of devices previously discovered using
586 * libusb_get_device_list(). If the unref_devices parameter is set, the
587 * reference count of each device in the list is decremented by 1.
588 * \param list the list to free
589 * \param unref_devices whether to unref the devices in the list
591 API_EXPORTED void libusb_free_device_list(libusb_device **list,
599 struct libusb_device *dev;
601 while ((dev = list[i++]) != NULL)
602 libusb_unref_device(dev);
608 * Get the number of the bus that a device is connected to.
609 * \param dev a device
610 * \returns the bus number
612 API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev)
614 return dev->bus_number;
618 * Get the address of the device on the bus it is connected to.
619 * \param dev a device
620 * \returns the device address
622 API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev)
624 return dev->device_address;
628 * Convenience function to retrieve the wMaxPacketSize value for a particular
629 * endpoint in the active device configuration. This is useful for setting up
630 * isochronous transfers.
632 * \param dev a device
633 * \param endpoint address of the endpoint in question
634 * \returns the wMaxPacketSize value
635 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
636 * \returns LIBUSB_ERROR_OTHER on other failure
638 API_EXPORTED int libusb_get_max_packet_size(libusb_device *dev,
639 unsigned char endpoint)
642 struct libusb_config_descriptor *config;
645 r = libusb_get_active_config_descriptor(dev, &config);
647 usbi_err(DEVICE_CTX(dev),
648 "could not retrieve active config descriptor");
649 return LIBUSB_ERROR_OTHER;
652 r = LIBUSB_ERROR_NOT_FOUND;
653 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
654 const struct libusb_interface *iface = &config->interface[iface_idx];
657 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
659 const struct libusb_interface_descriptor *altsetting
660 = &iface->altsetting[altsetting_idx];
663 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
664 const struct libusb_endpoint_descriptor *ep =
665 &altsetting->endpoint[ep_idx];
666 if (ep->bEndpointAddress == endpoint) {
667 r = ep->wMaxPacketSize;
675 libusb_free_config_descriptor(config);
680 * Increment the reference count of a device.
681 * \param dev the device to reference
682 * \returns the same device
684 API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev)
686 pthread_mutex_lock(&dev->lock);
688 pthread_mutex_unlock(&dev->lock);
693 * Decrement the reference count of a device. If the decrement operation
694 * causes the reference count to reach zero, the device shall be destroyed.
695 * \param dev the device to unreference
697 API_EXPORTED void libusb_unref_device(libusb_device *dev)
704 pthread_mutex_lock(&dev->lock);
705 refcnt = --dev->refcnt;
706 pthread_mutex_unlock(&dev->lock);
709 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
711 if (usbi_backend->destroy_device)
712 usbi_backend->destroy_device(dev);
714 pthread_mutex_lock(&dev->ctx->usb_devs_lock);
715 list_del(&dev->list);
716 pthread_mutex_unlock(&dev->ctx->usb_devs_lock);
723 * Open a device and obtain a device handle. A handle allows you to perform
724 * I/O on the device in question.
726 * Internally, this function adds a reference to the device and makes it
727 * available to you through libusb_get_device(). This reference is removed
728 * during libusb_close().
730 * This is a non-blocking function; no requests are sent over the bus.
732 * \param dev the device to open
733 * \param handle output location for the returned device handle pointer. Only
734 * populated when the return code is 0.
735 * \returns 0 on success
736 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
737 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
738 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
739 * \returns another LIBUSB_ERROR code on other failure
741 API_EXPORTED int libusb_open(libusb_device *dev, libusb_device_handle **handle)
743 struct libusb_context *ctx = DEVICE_CTX(dev);
744 struct libusb_device_handle *_handle;
745 size_t priv_size = usbi_backend->device_handle_priv_size;
746 unsigned char dummy = 1;
748 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
750 _handle = malloc(sizeof(*_handle) + priv_size);
752 return LIBUSB_ERROR_NO_MEM;
754 r = pthread_mutex_init(&_handle->lock, NULL);
756 return LIBUSB_ERROR_OTHER;
758 _handle->dev = libusb_ref_device(dev);
759 _handle->claimed_interfaces = 0;
760 memset(&_handle->os_priv, 0, priv_size);
762 r = usbi_backend->open(_handle);
764 libusb_unref_device(dev);
769 pthread_mutex_lock(&ctx->open_devs_lock);
770 list_add(&_handle->list, &ctx->open_devs);
771 pthread_mutex_unlock(&ctx->open_devs_lock);
775 /* At this point, we want to interrupt any existing event handlers so
776 * that they realise the addition of the new device's poll fd. One
777 * example when this is desirable is if the user is running a separate
778 * dedicated libusb events handling thread, which is running with a long
779 * or infinite timeout. We want to interrupt that iteration of the loop,
780 * so that it picks up the new fd, and then continues. */
782 /* record that we are messing with poll fds */
783 pthread_mutex_lock(&ctx->pollfd_modify_lock);
784 ctx->pollfd_modify++;
785 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
787 /* write some data on control pipe to interrupt event handlers */
788 r = write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
790 usbi_warn(ctx, "internal signalling write failed");
791 pthread_mutex_lock(&ctx->pollfd_modify_lock);
792 ctx->pollfd_modify--;
793 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
797 /* take event handling lock */
798 libusb_lock_events(ctx);
800 /* read the dummy data */
801 r = read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
803 usbi_warn(ctx, "internal signalling read failed");
805 /* we're done with modifying poll fds */
806 pthread_mutex_lock(&ctx->pollfd_modify_lock);
807 ctx->pollfd_modify--;
808 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
810 /* Release event handling lock and wake up event waiters */
811 libusb_unlock_events(ctx);
817 * Convenience function for finding a device with a particular
818 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
819 * for those scenarios where you are using libusb to knock up a quick test
820 * application - it allows you to avoid calling libusb_get_device_list() and
821 * worrying about traversing/freeing the list.
823 * This function has limitations and is hence not intended for use in real
824 * applications: if multiple devices have the same IDs it will only
825 * give you the first one, etc.
827 * \param ctx the context to operate on, or NULL for the default context
828 * \param vendor_id the idVendor value to search for
829 * \param product_id the idProduct value to search for
830 * \returns a handle for the first found device, or NULL on error or if the
831 * device could not be found. */
832 API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid(
833 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
835 struct libusb_device **devs;
836 struct libusb_device *found = NULL;
837 struct libusb_device *dev;
838 struct libusb_device_handle *handle = NULL;
842 if (libusb_get_device_list(ctx, &devs) < 0)
845 while ((dev = devs[i++]) != NULL) {
846 struct libusb_device_descriptor desc;
847 r = libusb_get_device_descriptor(dev, &desc);
850 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
857 r = libusb_open(found, &handle);
863 libusb_free_device_list(devs, 1);
867 static void do_close(struct libusb_context *ctx,
868 struct libusb_device_handle *dev_handle)
870 pthread_mutex_lock(&ctx->open_devs_lock);
871 list_del(&dev_handle->list);
872 pthread_mutex_unlock(&ctx->open_devs_lock);
874 usbi_backend->close(dev_handle);
875 libusb_unref_device(dev_handle->dev);
880 * Close a device handle. Should be called on all open handles before your
883 * Internally, this function destroys the reference that was added by
884 * libusb_open() on the given device.
886 * This is a non-blocking function; no requests are sent over the bus.
888 * \param dev_handle the handle to close
890 API_EXPORTED void libusb_close(libusb_device_handle *dev_handle)
892 struct libusb_context *ctx;
893 unsigned char dummy = 1;
900 ctx = HANDLE_CTX(dev_handle);
902 /* Similarly to libusb_open(), we want to interrupt all event handlers
903 * at this point. More importantly, we want to perform the actual close of
904 * the device while holding the event handling lock (preventing any other
905 * thread from doing event handling) because we will be removing a file
906 * descriptor from the polling loop. */
908 /* record that we are messing with poll fds */
909 pthread_mutex_lock(&ctx->pollfd_modify_lock);
910 ctx->pollfd_modify++;
911 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
913 /* write some data on control pipe to interrupt event handlers */
914 r = write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
916 usbi_warn(ctx, "internal signalling write failed, closing anyway");
917 do_close(ctx, dev_handle);
918 pthread_mutex_lock(&ctx->pollfd_modify_lock);
919 ctx->pollfd_modify--;
920 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
924 /* take event handling lock */
925 libusb_lock_events(ctx);
927 /* read the dummy data */
928 r = read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
930 usbi_warn(ctx, "internal signalling read failed, closing anyway");
932 /* Close the device */
933 do_close(ctx, dev_handle);
935 /* we're done with modifying poll fds */
936 pthread_mutex_lock(&ctx->pollfd_modify_lock);
937 ctx->pollfd_modify--;
938 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
940 /* Release event handling lock and wake up event waiters */
941 libusb_unlock_events(ctx);
945 * Get the underlying device for a handle. This function does not modify
946 * the reference count of the returned device, so do not feel compelled to
947 * unreference it when you are done.
948 * \param dev_handle a device handle
949 * \returns the underlying device
951 API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle)
953 return dev_handle->dev;
957 * Determine the bConfigurationValue of the currently active configuration.
959 * You could formulate your own control request to obtain this information,
960 * but this function has the advantage that it may be able to retrieve the
961 * information from operating system caches (no I/O involved).
963 * If the OS does not cache this information, then this function will block
964 * while a control transfer is submitted to retrieve the information.
966 * This function will return a value of 0 in the <tt>config</tt> output
967 * parameter if the device is in unconfigured state.
969 * \param dev a device handle
970 * \param config output location for the bConfigurationValue of the active
971 * configuration (only valid for return code 0)
972 * \returns 0 on success
973 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
974 * \returns another LIBUSB_ERROR code on other failure
976 API_EXPORTED int libusb_get_configuration(libusb_device_handle *dev,
979 int r = LIBUSB_ERROR_NOT_SUPPORTED;
982 if (usbi_backend->get_configuration)
983 r = usbi_backend->get_configuration(dev, config);
985 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
987 usbi_dbg("falling back to control message");
988 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
989 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
991 usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
997 usbi_dbg("control failed, error %d", r);
1002 usbi_dbg("active config %d", *config);
1008 * Set the active configuration for a device.
1010 * The operating system may or may not have already set an active
1011 * configuration on the device. It is up to your application to ensure the
1012 * correct configuration is selected before you attempt to claim interfaces
1013 * and perform other operations.
1015 * If you call this function on a device already configured with the selected
1016 * configuration, then this function will act as a lightweight device reset:
1017 * it will issue a SET_CONFIGURATION request using the current configuration,
1018 * causing most USB-related device state to be reset (altsetting reset to zero,
1019 * endpoint halts cleared, toggles reset).
1021 * You cannot change/reset configuration if your application has claimed
1022 * interfaces - you should free them with libusb_release_interface() first.
1023 * You cannot change/reset configuration if other applications or drivers have
1024 * claimed interfaces.
1026 * A configuration value of -1 will put the device in unconfigured state.
1027 * The USB specifications state that a configuration value of 0 does this,
1028 * however buggy devices exist which actually have a configuration 0.
1030 * You should always use this function rather than formulating your own
1031 * SET_CONFIGURATION control request. This is because the underlying operating
1032 * system needs to know when such changes happen.
1034 * This is a blocking function.
1036 * \param dev a device handle
1037 * \param configuration the bConfigurationValue of the configuration you
1038 * wish to activate, or -1 if you wish to put the device in unconfigured state
1039 * \returns 0 on success
1040 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1041 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1042 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1043 * \returns another LIBUSB_ERROR code on other failure
1045 API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev,
1048 usbi_dbg("configuration %d", configuration);
1049 return usbi_backend->set_configuration(dev, configuration);
1053 * Claim an interface on a given device handle. You must claim the interface
1054 * you wish to use before you can perform I/O on any of its endpoints.
1056 * It is legal to attempt to claim an already-claimed interface, in which
1057 * case libusb just returns 0 without doing anything.
1059 * Claiming of interfaces is a purely logical operation; it does not cause
1060 * any requests to be sent over the bus. Interface claiming is used to
1061 * instruct the underlying operating system that your application wishes
1062 * to take ownership of the interface.
1064 * This is a non-blocking function.
1066 * \param dev a device handle
1067 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1069 * \returns 0 on success
1070 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1071 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1073 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1074 * \returns a LIBUSB_ERROR code on other failure
1076 API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev,
1077 int interface_number)
1081 usbi_dbg("interface %d", interface_number);
1082 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1083 return LIBUSB_ERROR_INVALID_PARAM;
1085 pthread_mutex_lock(&dev->lock);
1086 if (dev->claimed_interfaces & (1 << interface_number))
1089 r = usbi_backend->claim_interface(dev, interface_number);
1091 dev->claimed_interfaces |= 1 << interface_number;
1094 pthread_mutex_unlock(&dev->lock);
1099 * Release an interface previously claimed with libusb_claim_interface(). You
1100 * should release all claimed interfaces before closing a device handle.
1102 * This is a blocking function. A SET_INTERFACE control request will be sent
1103 * to the device, resetting interface state to the first alternate setting.
1105 * \param dev a device handle
1106 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1107 * previously-claimed interface
1108 * \returns 0 on success
1109 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1110 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1111 * \returns another LIBUSB_ERROR code on other failure
1113 API_EXPORTED int libusb_release_interface(libusb_device_handle *dev,
1114 int interface_number)
1118 usbi_dbg("interface %d", interface_number);
1119 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1120 return LIBUSB_ERROR_INVALID_PARAM;
1122 pthread_mutex_lock(&dev->lock);
1123 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1124 r = LIBUSB_ERROR_NOT_FOUND;
1128 r = usbi_backend->release_interface(dev, interface_number);
1130 dev->claimed_interfaces &= ~(1 << interface_number);
1133 pthread_mutex_unlock(&dev->lock);
1138 * Activate an alternate setting for an interface. The interface must have
1139 * been previously claimed with libusb_claim_interface().
1141 * You should always use this function rather than formulating your own
1142 * SET_INTERFACE control request. This is because the underlying operating
1143 * system needs to know when such changes happen.
1145 * This is a blocking function.
1147 * \param dev a device handle
1148 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1149 * previously-claimed interface
1150 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1151 * setting to activate
1152 * \returns 0 on success
1153 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1154 * requested alternate setting does not exist
1155 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1156 * \returns another LIBUSB_ERROR code on other failure
1158 API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev,
1159 int interface_number, int alternate_setting)
1161 usbi_dbg("interface %d altsetting %d",
1162 interface_number, alternate_setting);
1163 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1164 return LIBUSB_ERROR_INVALID_PARAM;
1166 pthread_mutex_lock(&dev->lock);
1167 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1168 pthread_mutex_unlock(&dev->lock);
1169 return LIBUSB_ERROR_NOT_FOUND;
1171 pthread_mutex_unlock(&dev->lock);
1173 return usbi_backend->set_interface_altsetting(dev, interface_number,
1178 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1179 * are unable to receive or transmit data until the halt condition is stalled.
1181 * You should cancel all pending transfers before attempting to clear the halt
1184 * This is a blocking function.
1186 * \param dev a device handle
1187 * \param endpoint the endpoint to clear halt status
1188 * \returns 0 on success
1189 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1190 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1191 * \returns another LIBUSB_ERROR code on other failure
1193 API_EXPORTED int libusb_clear_halt(libusb_device_handle *dev,
1194 unsigned char endpoint)
1196 usbi_dbg("endpoint %x", endpoint);
1197 return usbi_backend->clear_halt(dev, endpoint);
1201 * Perform a USB port reset to reinitialize a device. The system will attempt
1202 * to restore the previous configuration and alternate settings after the
1203 * reset has completed.
1205 * If the reset fails, the descriptors change, or the previous state cannot be
1206 * restored, the device will appear to be disconnected and reconnected. This
1207 * means that the device handle is no longer valid (you should close it) and
1208 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1209 * when this is the case.
1211 * This is a blocking function which usually incurs a noticeable delay.
1213 * \param dev a handle of the device to reset
1214 * \returns 0 on success
1215 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1216 * device has been disconnected
1217 * \returns another LIBUSB_ERROR code on other failure
1219 API_EXPORTED int libusb_reset_device(libusb_device_handle *dev)
1222 return usbi_backend->reset_device(dev);
1226 * Determine if a kernel driver is active on an interface. If a kernel driver
1227 * is active, you cannot claim the interface, and libusb will be unable to
1230 * \param dev a device handle
1231 * \param interface the interface to check
1232 * \returns 0 if no kernel driver is active
1233 * \returns 1 if a kernel driver is active
1234 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1235 * \returns another LIBUSB_ERROR code on other failure
1236 * \see libusb_detach_kernel_driver()
1238 API_EXPORTED int libusb_kernel_driver_active(libusb_device_handle *dev,
1241 usbi_dbg("interface %d", interface);
1242 if (usbi_backend->kernel_driver_active)
1243 return usbi_backend->kernel_driver_active(dev, interface);
1245 return LIBUSB_ERROR_NOT_SUPPORTED;
1249 * Detach a kernel driver from an interface. If successful, you will then be
1250 * able to claim the interface and perform I/O.
1252 * \param dev a device handle
1253 * \param interface the interface to detach the driver from
1254 * \returns 0 on success
1255 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1256 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1257 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1258 * \returns another LIBUSB_ERROR code on other failure
1259 * \see libusb_kernel_driver_active()
1261 API_EXPORTED int libusb_detach_kernel_driver(libusb_device_handle *dev,
1264 usbi_dbg("interface %d", interface);
1265 if (usbi_backend->detach_kernel_driver)
1266 return usbi_backend->detach_kernel_driver(dev, interface);
1268 return LIBUSB_ERROR_NOT_SUPPORTED;
1272 * Re-attach an interface's kernel driver, which was previously detached
1273 * using libusb_detach_kernel_driver().
1275 * \param dev a device handle
1276 * \param interface the interface to attach the driver from
1277 * \returns 0 on success
1278 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1279 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1280 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1281 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1282 * interface is claimed by a program or driver
1283 * \returns another LIBUSB_ERROR code on other failure
1284 * \see libusb_kernel_driver_active()
1286 API_EXPORTED int libusb_attach_kernel_driver(libusb_device_handle *dev,
1289 usbi_dbg("interface %d", interface);
1290 if (usbi_backend->attach_kernel_driver)
1291 return usbi_backend->attach_kernel_driver(dev, interface);
1293 return LIBUSB_ERROR_NOT_SUPPORTED;
1297 * Set message verbosity.
1298 * - Level 0: no messages ever printed by the library (default)
1299 * - Level 1: error messages are printed to stderr
1300 * - Level 2: warning and error messages are printed to stderr
1301 * - Level 3: informational messages are printed to stdout, warning and error
1302 * messages are printed to stderr
1304 * The default level is 0, which means no messages are ever printed. If you
1305 * choose to increase the message verbosity level, ensure that your
1306 * application does not close the stdout/stderr file descriptors.
1308 * You are advised to set level 3. libusb is conservative with its message
1309 * logging and most of the time, will only log messages that explain error
1310 * conditions and other oddities. This will help you debug your software.
1312 * If the LIBUSB_DEBUG environment variable was set when libusb was
1313 * initialized, this function does nothing: the message verbosity is fixed
1314 * to the value in the environment variable.
1316 * If libusb was compiled without any message logging, this function does
1317 * nothing: you'll never get any messages.
1319 * If libusb was compiled with verbose debug message logging, this function
1320 * does nothing: you'll always get messages from all levels.
1322 * \param ctx the context to operate on, or NULL for the default context
1323 * \param level debug level to set
1325 API_EXPORTED void libusb_set_debug(libusb_context *ctx, int level)
1327 USBI_GET_CONTEXT(ctx);
1328 if (!ctx->debug_fixed)
1333 * Initialize libusb. This function must be called before calling any other
1335 * \param context Optional output location for context pointer.
1336 * Only valid on return code 0.
1337 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1339 API_EXPORTED int libusb_init(libusb_context **context)
1341 char *dbg = getenv("LIBUSB_DEBUG");
1342 struct libusb_context *ctx = malloc(sizeof(*ctx));
1346 return LIBUSB_ERROR_NO_MEM;
1347 memset(ctx, 0, sizeof(*ctx));
1350 ctx->debug = atoi(dbg);
1352 ctx->debug_fixed = 1;
1357 if (usbi_backend->init) {
1358 r = usbi_backend->init(ctx);
1363 pthread_mutex_init(&ctx->usb_devs_lock, NULL);
1364 pthread_mutex_init(&ctx->open_devs_lock, NULL);
1365 list_init(&ctx->usb_devs);
1366 list_init(&ctx->open_devs);
1368 r = usbi_io_init(ctx);
1370 if (usbi_backend->exit)
1371 usbi_backend->exit();
1375 pthread_mutex_lock(&default_context_lock);
1376 if (!usbi_default_context) {
1377 usbi_dbg("created default context");
1378 usbi_default_context = ctx;
1380 pthread_mutex_unlock(&default_context_lock);
1392 * Deinitialize libusb. Should be called after closing all open devices and
1393 * before your application terminates.
1394 * \param ctx the context to deinitialize, or NULL for the default context
1396 API_EXPORTED void libusb_exit(struct libusb_context *ctx)
1398 USBI_GET_CONTEXT(ctx);
1401 /* a little sanity check. doesn't bother with open_devs locking because
1402 * unless there is an application bug, nobody will be accessing this. */
1403 if (!list_empty(&ctx->open_devs))
1404 usbi_warn(ctx, "application left some devices open");
1407 if (usbi_backend->exit)
1408 usbi_backend->exit();
1410 pthread_mutex_lock(&default_context_lock);
1411 if (ctx == usbi_default_context) {
1412 usbi_dbg("freeing default context");
1413 usbi_default_context = NULL;
1415 pthread_mutex_unlock(&default_context_lock);
1420 void usbi_log(struct libusb_context *ctx, enum usbi_log_level level,
1421 const char *function, const char *format, ...)
1424 FILE *stream = stdout;
1427 #ifndef ENABLE_DEBUG_LOGGING
1428 USBI_GET_CONTEXT(ctx);
1431 if (level == LOG_LEVEL_WARNING && ctx->debug < 2)
1433 if (level == LOG_LEVEL_INFO && ctx->debug < 3)
1438 case LOG_LEVEL_INFO:
1441 case LOG_LEVEL_WARNING:
1445 case LOG_LEVEL_ERROR:
1449 case LOG_LEVEL_DEBUG:
1459 fprintf(stream, "libusb:%s [%s] ", prefix, function);
1461 va_start (args, format);
1462 vfprintf(stream, format, args);
1465 fprintf(stream, "\n");