2 * Core functions for libusb
3 * Copyright (C) 2007-2008 Daniel Drake <dsd@gentoo.org>
4 * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include <sys/types.h>
35 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
37 #error "Unsupported OS"
40 struct libusb_context *usbi_default_context = NULL;
41 static pthread_mutex_t default_context_lock = PTHREAD_MUTEX_INITIALIZER;
44 * \mainpage libusb-1.0 API Reference
46 * \section intro Introduction
48 * libusb is an open source library that allows you to communicate with USB
49 * devices from userspace. For more info, see the
50 * <a href="http://libusb.sourceforge.net">libusb homepage</a>.
52 * This documentation is aimed at application developers wishing to
53 * communicate with USB peripherals from their own software. After reviewing
54 * this documentation, feedback and questions can be sent to the
55 * <a href="http://sourceforge.net/mail/?group_id=1674">libusb-devel mailing
58 * This documentation assumes knowledge of how to operate USB devices from
59 * a software standpoint (descriptors, configurations, interfaces, endpoints,
60 * control/bulk/interrupt/isochronous transfers, etc). Full information
61 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 2.0
62 * Specification</a> which is available for free download. You can probably
63 * find less verbose introductions by searching the web.
65 * \section features Library features
67 * - All transfer types supported (control/bulk/interrupt/isochronous)
68 * - 2 transfer interfaces:
69 * -# Synchronous (simple)
70 * -# Asynchronous (more complicated, but more powerful)
71 * - Thread safe (although the asynchronous interface means that you
72 * usually won't need to thread)
73 * - Lightweight with lean API
74 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
76 * \section gettingstarted Getting Started
78 * To begin reading the API documentation, start with the Modules page which
79 * links to the different categories of libusb's functionality.
81 * One decision you will have to make is whether to use the synchronous
82 * or the asynchronous data transfer interface. The \ref io documentation
83 * provides some insight into this topic.
85 * Some example programs can be found in the libusb source distribution under
86 * the "examples" subdirectory. The libusb homepage includes a list of
87 * real-life project examples which use libusb.
89 * \section errorhandling Error handling
91 * libusb functions typically return 0 on success or a negative error code
92 * on failure. These negative error codes relate to LIBUSB_ERROR constants
93 * which are listed on the \ref misc "miscellaneous" documentation page.
95 * \section msglog Debug message logging
97 * libusb does not log any messages by default. Your application is therefore
98 * free to close stdout/stderr and those descriptors may be reused without
101 * The libusb_set_debug() function can be used to enable stdout/stderr logging
102 * of certain messages. Under standard configuration, libusb doesn't really
103 * log much at all, so you are advised to use this function to enable all
104 * error/warning/informational messages. It will help you debug problems with
107 * The LIBUSB_DEBUG environment variable can be used to enable message logging
108 * at run-time. This environment variable should be set to a number, which is
109 * interpreted the same as the libusb_set_debug() parameter. When this
110 * environment variable is set, the message logging verbosity level is fixed
111 * and libusb_set_debug() effectively does nothing.
113 * libusb can be compiled without any logging functions, useful for embedded
114 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
115 * variable have no effects.
117 * libusb can also be compiled with verbose debugging messages. When the
118 * library is compiled in this way, all messages of all verbosities are always
119 * logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable have
122 * \section remarks Other remarks
124 * libusb does have imperfections. The \ref caveats "caveats" page attempts
129 * \page caveats Caveats
131 * \section devresets Device resets
133 * The libusb_reset_device() function allows you to reset a device. If your
134 * program has to call such a function, it should obviously be aware that
135 * the reset will cause device state to change (e.g. register values may be
138 * The problem is that any other program could reset the device your program
139 * is working with, at any time. libusb does not offer a mechanism to inform
140 * you when this has happened, so if someone else resets your device it will
141 * not be clear to your own program why the device state has changed.
143 * Ultimately, this is a limitation of writing drivers in userspace.
144 * Separation from the USB stack in the underlying kernel makes it difficult
145 * for the operating system to deliver such notifications to your program.
146 * The Linux kernel USB stack allows such reset notifications to be delivered
147 * to in-kernel USB drivers, but it is not clear how such notifications could
148 * be delivered to second-class drivers that live in userspace.
150 * \section blockonly Blocking-only functionality
152 * The functionality listed below is only available through synchronous,
153 * blocking functions. There are no asynchronous/non-blocking alternatives,
154 * and no clear ways of implementing these.
156 * - Configuration activation (libusb_set_configuration())
157 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
158 * - Releasing of interfaces (libusb_release_interface())
159 * - Clearing of halt/stall condition (libusb_clear_halt())
160 * - Device resets (libusb_reset_device())
162 * \section nohotplug No hotplugging
164 * libusb-1.0 lacks functionality for providing notifications of when devices
165 * are added or removed. This functionality is planned to be implemented
168 * That said, there is basic disconnection handling for open device handles:
169 * - If there are ongoing transfers, libusb's handle_events loop will detect
170 * disconnections and complete ongoing transfers with the
171 * LIBUSB_TRANSFER_NO_DEVICE status code.
172 * - Many functions such as libusb_set_configuration() return the special
173 * LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected.
175 * \section configsel Configuration selection and handling
177 * When libusb presents a device handle to an application, there is a chance
178 * that the corresponding device may be in unconfigured state. For devices
179 * with multiple configurations, there is also a chance that the configuration
180 * currently selected is not the one that the application wants to use.
182 * The obvious solution is to add a call to libusb_set_configuration() early
183 * on during your device initialization routines, but there are caveats to
185 * -# If the device is already in the desired configuration, calling
186 * libusb_set_configuration() using the same configuration value will cause
187 * a lightweight device reset. This may not be desirable behaviour.
188 * -# libusb will be unable to change configuration if the device is in
189 * another configuration and other programs or drivers have claimed
190 * interfaces under that configuration.
191 * -# In the case where the desired configuration is already active, libusb
192 * may not even be able to perform a lightweight device reset. For example,
193 * take my USB keyboard with fingerprint reader: I'm interested in driving
194 * the fingerprint reader interface through libusb, but the kernel's
195 * USB-HID driver will almost always have claimed the keyboard interface.
196 * Because the kernel has claimed an interface, it is not even possible to
197 * perform the lightweight device reset, so libusb_set_configuration() will
198 * fail. (Luckily the device in question only has a single configuration.)
200 * One solution to some of the above problems is to consider the currently
201 * active configuration. If the configuration we want is already active, then
202 * we don't have to select any configuration:
204 cfg = libusb_get_configuration(dev);
206 libusb_set_configuration(dev, desired);
209 * This is probably suitable for most scenarios, but is inherently racy:
210 * another application or driver may change the selected configuration
211 * <em>after</em> the libusb_get_configuration() call.
213 * Even in cases where libusb_set_configuration() succeeds, consider that other
214 * applications or drivers may change configuration after your application
215 * calls libusb_set_configuration().
217 * One possible way to lock your device into a specific configuration is as
219 * -# Set the desired configuration (or use the logic above to realise that
220 * it is already in the desired configuration)
221 * -# Claim the interface that you wish to use
222 * -# Check that the currently active configuration is the one that you want
225 * The above method works because once an interface is claimed, no application
226 * or driver is able to select another configuration.
230 * \page contexts Contexts
232 * It is possible that libusb may be used simultaneously from two independent
233 * libraries linked into the same executable. For example, if your application
234 * has a plugin-like system which allows the user to dynamically load a range
235 * of modules into your program, it is feasible that two independently
236 * developed modules may both use libusb.
238 * libusb is written to allow for these multiple user scenarios. The two
239 * "instances" of libusb will not interfere: libusb_set_debug() calls
240 * from one user will not affect the same settings for other users, other
241 * users can continue using libusb after one of them calls libusb_exit(), etc.
243 * This is made possible through libusb's <em>context</em> concept. When you
244 * call libusb_init(), you are (optionally) given a context. You can then pass
245 * this context pointer back into future libusb functions.
247 * In order to keep things simple for more simplistic applications, it is
248 * legal to pass NULL to all functions requiring a context pointer (as long as
249 * you're sure no other code will attempt to use libusb from the same process).
250 * When you pass NULL, the default context will be used. The default context
251 * is created the first time a process calls libusb_init() when no other
252 * context is alive. Contexts are destroyed during libusb_exit().
254 * You may be wondering why only a subset of libusb functions require a
255 * context pointer in their function definition. Internally, libusb stores
256 * context pointers in other objects (e.g. libusb_device instances) and hence
257 * can infer the context from those objects.
261 * @defgroup lib Library initialization/deinitialization
262 * This page details how to initialize and deinitialize libusb. Initialization
263 * must be performed before using any libusb functionality, and similarly you
264 * must not call any libusb functions after deinitialization.
268 * @defgroup dev Device handling and enumeration
269 * The functionality documented below is designed to help with the following
271 * - Enumerating the USB devices currently attached to the system
272 * - Choosing a device to operate from your software
273 * - Opening and closing the chosen device
275 * \section nutshell In a nutshell...
277 * The description below really makes things sound more complicated than they
278 * actually are. The following sequence of function calls will be suitable
279 * for almost all scenarios and does not require you to have such a deep
280 * understanding of the resource management issues:
283 libusb_device **list;
284 libusb_device *found = NULL;
285 size_t cnt = libusb_get_device_list(NULL, &list);
291 for (i = 0; i < cnt; i++) {
292 libusb_device *device = list[i];
293 if (is_interesting(device)) {
300 libusb_device_handle *handle;
302 err = libusb_open(found, &handle);
308 libusb_free_device_list(list, 1);
311 * The two important points:
312 * - You asked libusb_free_device_list() to unreference the devices (2nd
314 * - You opened the device before freeing the list and unreferencing the
317 * If you ended up with a handle, you can now proceed to perform I/O on the
320 * \section devshandles Devices and device handles
321 * libusb has a concept of a USB device, represented by the
322 * \ref libusb_device opaque type. A device represents a USB device that
323 * is currently or was previously connected to the system. Using a reference
324 * to a device, you can determine certain information about the device (e.g.
325 * you can read the descriptor data).
327 * The libusb_get_device_list() function can be used to obtain a list of
328 * devices currently connected to the system. This is known as device
331 * Just because you have a reference to a device does not mean it is
332 * necessarily usable. The device may have been unplugged, you may not have
333 * permission to operate such device, or another program or driver may be
336 * When you've found a device that you'd like to operate, you must ask
337 * libusb to open the device using the libusb_open() function. Assuming
338 * success, libusb then returns you a <em>device handle</em>
339 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
340 * operate on the handle rather than the original device pointer.
342 * \section devref Device discovery and reference counting
344 * Device discovery (i.e. calling libusb_get_device_list()) returns a
345 * freshly-allocated list of devices. The list itself must be freed when
346 * you are done with it. libusb also needs to know when it is OK to free
347 * the contents of the list - the devices themselves.
349 * To handle these issues, libusb provides you with two separate items:
350 * - A function to free the list itself
351 * - A reference counting system for the devices inside
353 * New devices presented by the libusb_get_device_list() function all have a
354 * reference count of 1. You can increase and decrease reference count using
355 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
356 * it's reference count reaches 0.
358 * With the above information in mind, the process of opening a device can
359 * be viewed as follows:
360 * -# Discover devices using libusb_get_device_list().
361 * -# Choose the device that you want to operate, and call libusb_open().
362 * -# Unref all devices in the discovered device list.
363 * -# Free the discovered device list.
365 * The order is important - you must not unreference the device before
366 * attempting to open it, because unreferencing it may destroy the device.
368 * For convenience, the libusb_free_device_list() function includes a
369 * parameter to optionally unreference all the devices in the list before
370 * freeing the list itself. This combines steps 3 and 4 above.
372 * As an implementation detail, libusb_open() actually adds a reference to
373 * the device in question. This is because the device remains available
374 * through the handle via libusb_get_device(). The reference is deleted during
378 /** @defgroup misc Miscellaneous */
380 /* we traverse usbfs without knowing how many devices we are going to find.
381 * so we create this discovered_devs model which is similar to a linked-list
382 * which grows when required. it can be freed once discovery has completed,
383 * eliminating the need for a list node in the libusb_device structure
385 #define DISCOVERED_DEVICES_SIZE_STEP 8
387 static struct discovered_devs *discovered_devs_alloc(void)
389 struct discovered_devs *ret =
390 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
394 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
399 /* append a device to the discovered devices collection. may realloc itself,
400 * returning new discdevs. returns NULL on realloc failure. */
401 struct discovered_devs *discovered_devs_append(
402 struct discovered_devs *discdevs, struct libusb_device *dev)
404 size_t len = discdevs->len;
407 /* if there is space, just append the device */
408 if (len < discdevs->capacity) {
409 discdevs->devices[len] = libusb_ref_device(dev);
414 /* exceeded capacity, need to grow */
415 usbi_dbg("need to increase capacity");
416 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
417 discdevs = realloc(discdevs,
418 sizeof(*discdevs) + (sizeof(void *) * capacity));
420 discdevs->capacity = capacity;
421 discdevs->devices[len] = libusb_ref_device(dev);
428 static void discovered_devs_free(struct discovered_devs *discdevs)
432 for (i = 0; i < discdevs->len; i++)
433 libusb_unref_device(discdevs->devices[i]);
438 /* Allocate a new device with a specific session ID. The returned device has
439 * a reference count of 1. */
440 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
441 unsigned long session_id)
443 size_t priv_size = usbi_backend->device_priv_size;
444 struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
450 r = pthread_mutex_init(&dev->lock, NULL);
456 dev->session_data = session_id;
457 memset(&dev->os_priv, 0, priv_size);
459 pthread_mutex_lock(&ctx->usb_devs_lock);
460 list_add(&dev->list, &ctx->usb_devs);
461 pthread_mutex_unlock(&ctx->usb_devs_lock);
465 /* Perform some final sanity checks on a newly discovered device. If this
466 * function fails (negative return code), the device should not be added
467 * to the discovered device list. */
468 int usbi_sanitize_device(struct libusb_device *dev)
471 unsigned char raw_desc[DEVICE_DESC_LENGTH];
472 uint8_t num_configurations;
475 r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
479 num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
480 if (num_configurations > USB_MAXCONFIG) {
481 usbi_err(DEVICE_CTX(dev), "too many configurations");
482 return LIBUSB_ERROR_IO;
483 } else if (num_configurations < 1) {
484 usbi_dbg("no configurations?");
485 return LIBUSB_ERROR_IO;
488 dev->num_configurations = num_configurations;
492 /* Examine libusb's internal list of known devices, looking for one with
493 * a specific session ID. Returns the matching device if it was found, and
495 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
496 unsigned long session_id)
498 struct libusb_device *dev;
499 struct libusb_device *ret = NULL;
501 pthread_mutex_lock(&ctx->usb_devs_lock);
502 list_for_each_entry(dev, &ctx->usb_devs, list)
503 if (dev->session_data == session_id) {
507 pthread_mutex_unlock(&ctx->usb_devs_lock);
513 * Returns a list of USB devices currently attached to the system. This is
514 * your entry point into finding a USB device to operate.
516 * You are expected to unreference all the devices when you are done with
517 * them, and then free the list with libusb_free_device_list(). Note that
518 * libusb_free_device_list() can unref all the devices for you. Be careful
519 * not to unreference a device you are about to open until after you have
522 * This return value of this function indicates the number of devices in
523 * the resultant list. The list is actually one element larger, as it is
526 * \param ctx the context to operate on, or NULL for the default context
527 * \param list output location for a list of devices. Must be later freed with
528 * libusb_free_device_list().
529 * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
530 * on memory allocation failure.
532 API_EXPORTED ssize_t libusb_get_device_list(libusb_context *ctx,
533 libusb_device ***list)
535 struct discovered_devs *discdevs = discovered_devs_alloc();
536 struct libusb_device **ret;
540 USBI_GET_CONTEXT(ctx);
544 return LIBUSB_ERROR_NO_MEM;
546 r = usbi_backend->get_device_list(ctx, &discdevs);
552 /* convert discovered_devs into a list */
554 ret = malloc(sizeof(void *) * (len + 1));
556 len = LIBUSB_ERROR_NO_MEM;
561 for (i = 0; i < len; i++) {
562 struct libusb_device *dev = discdevs->devices[i];
563 ret[i] = libusb_ref_device(dev);
568 discovered_devs_free(discdevs);
573 * Frees a list of devices previously discovered using
574 * libusb_get_device_list(). If the unref_devices parameter is set, the
575 * reference count of each device in the list is decremented by 1.
576 * \param list the list to free
577 * \param unref_devices whether to unref the devices in the list
579 API_EXPORTED void libusb_free_device_list(libusb_device **list,
587 struct libusb_device *dev;
589 while ((dev = list[i++]) != NULL)
590 libusb_unref_device(dev);
596 * Get the number of the bus that a device is connected to.
597 * \param dev a device
598 * \returns the bus number
600 API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev)
602 return dev->bus_number;
606 * Get the address of the device on the bus it is connected to.
607 * \param dev a device
608 * \returns the device address
610 API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev)
612 return dev->device_address;
616 * Convenience function to retrieve the wMaxPacketSize value for a particular
617 * endpoint in the active device configuration. This is useful for setting up
618 * isochronous transfers.
620 * \param dev a device
621 * \param endpoint address of the endpoint in question
622 * \returns the wMaxPacketSize value
623 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
624 * \returns LIBUSB_ERROR_OTHER on other failure
626 API_EXPORTED int libusb_get_max_packet_size(libusb_device *dev,
627 unsigned char endpoint)
630 struct libusb_config_descriptor *config;
633 r = libusb_get_active_config_descriptor(dev, &config);
635 usbi_err(DEVICE_CTX(dev),
636 "could not retrieve active config descriptor");
637 return LIBUSB_ERROR_OTHER;
640 r = LIBUSB_ERROR_NOT_FOUND;
641 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
642 const struct libusb_interface *iface = &config->interface[iface_idx];
645 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
647 const struct libusb_interface_descriptor *altsetting
648 = &iface->altsetting[altsetting_idx];
651 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
652 const struct libusb_endpoint_descriptor *ep =
653 &altsetting->endpoint[ep_idx];
654 if (ep->bEndpointAddress == endpoint) {
655 r = ep->wMaxPacketSize;
663 libusb_free_config_descriptor(config);
668 * Increment the reference count of a device.
669 * \param dev the device to reference
670 * \returns the same device
672 API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev)
674 pthread_mutex_lock(&dev->lock);
676 pthread_mutex_unlock(&dev->lock);
681 * Decrement the reference count of a device. If the decrement operation
682 * causes the reference count to reach zero, the device shall be destroyed.
683 * \param dev the device to unreference
685 API_EXPORTED void libusb_unref_device(libusb_device *dev)
692 pthread_mutex_lock(&dev->lock);
693 refcnt = --dev->refcnt;
694 pthread_mutex_unlock(&dev->lock);
697 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
699 if (usbi_backend->destroy_device)
700 usbi_backend->destroy_device(dev);
702 pthread_mutex_lock(&dev->ctx->usb_devs_lock);
703 list_del(&dev->list);
704 pthread_mutex_unlock(&dev->ctx->usb_devs_lock);
711 * Open a device and obtain a device handle. A handle allows you to perform
712 * I/O on the device in question.
714 * Internally, this function adds a reference to the device and makes it
715 * available to you through libusb_get_device(). This reference is removed
716 * during libusb_close().
718 * This is a non-blocking function; no requests are sent over the bus.
720 * \param dev the device to open
721 * \param handle output location for the returned device handle pointer. Only
722 * populated when the return code is 0.
723 * \returns 0 on success
724 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
725 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
726 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
727 * \returns another LIBUSB_ERROR code on other failure
729 API_EXPORTED int libusb_open(libusb_device *dev, libusb_device_handle **handle)
731 struct libusb_device_handle *_handle;
732 size_t priv_size = usbi_backend->device_handle_priv_size;
734 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
736 _handle = malloc(sizeof(*_handle) + priv_size);
738 return LIBUSB_ERROR_NO_MEM;
740 r = pthread_mutex_init(&_handle->lock, NULL);
742 return LIBUSB_ERROR_OTHER;
744 _handle->dev = libusb_ref_device(dev);
745 _handle->claimed_interfaces = 0;
746 memset(&_handle->os_priv, 0, priv_size);
748 r = usbi_backend->open(_handle);
750 libusb_unref_device(dev);
755 pthread_mutex_lock(&dev->ctx->open_devs_lock);
756 list_add(&_handle->list, &dev->ctx->open_devs);
757 pthread_mutex_unlock(&dev->ctx->open_devs_lock);
763 * Convenience function for finding a device with a particular
764 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
765 * for those scenarios where you are using libusb to knock up a quick test
766 * application - it allows you to avoid calling libusb_get_device_list() and
767 * worrying about traversing/freeing the list.
769 * This function has limitations and is hence not intended for use in real
770 * applications: if multiple devices have the same IDs it will only
771 * give you the first one, etc.
773 * \param ctx the context to operate on, or NULL for the default context
774 * \param vendor_id the idVendor value to search for
775 * \param product_id the idProduct value to search for
776 * \returns a handle for the first found device, or NULL on error or if the
777 * device could not be found. */
778 API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid(
779 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
781 struct libusb_device **devs;
782 struct libusb_device *found = NULL;
783 struct libusb_device *dev;
784 struct libusb_device_handle *handle = NULL;
788 if (libusb_get_device_list(ctx, &devs) < 0)
791 while ((dev = devs[i++]) != NULL) {
792 struct libusb_device_descriptor desc;
793 r = libusb_get_device_descriptor(dev, &desc);
796 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
803 r = libusb_open(found, &handle);
809 libusb_free_device_list(devs, 1);
813 static void do_close(struct libusb_device_handle *dev_handle)
815 usbi_backend->close(dev_handle);
816 libusb_unref_device(dev_handle->dev);
820 * Close a device handle. Should be called on all open handles before your
823 * Internally, this function destroys the reference that was added by
824 * libusb_open() on the given device.
826 * This is a non-blocking function; no requests are sent over the bus.
828 * \param dev_handle the handle to close
830 API_EXPORTED void libusb_close(libusb_device_handle *dev_handle)
836 pthread_mutex_lock(&HANDLE_CTX(dev_handle)->open_devs_lock);
837 list_del(&dev_handle->list);
838 pthread_mutex_unlock(&HANDLE_CTX(dev_handle)->open_devs_lock);
840 do_close(dev_handle);
845 * Get the underlying device for a handle. This function does not modify
846 * the reference count of the returned device, so do not feel compelled to
847 * unreference it when you are done.
848 * \param dev_handle a device handle
849 * \returns the underlying device
851 API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle)
853 return dev_handle->dev;
857 * Determine the bConfigurationValue of the currently active configuration.
859 * You could formulate your own control request to obtain this information,
860 * but this function has the advantage that it may be able to retrieve the
861 * information from operating system caches (no I/O involved).
863 * If the OS does not cache this information, then this function will block
864 * while a control transfer is submitted to retrieve the information.
866 * This function will return a value of 0 in the <tt>config</tt> output
867 * parameter if the device is in unconfigured state.
869 * \param dev a device handle
870 * \param config output location for the bConfigurationValue of the active
871 * configuration (only valid for return code 0)
872 * \returns 0 on success
873 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
874 * \returns another LIBUSB_ERROR code on other failure
876 API_EXPORTED int libusb_get_configuration(libusb_device_handle *dev,
879 int r = LIBUSB_ERROR_NOT_SUPPORTED;
882 if (usbi_backend->get_configuration)
883 r = usbi_backend->get_configuration(dev, config);
885 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
887 usbi_dbg("falling back to control message");
888 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
889 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
891 usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
897 usbi_dbg("control failed, error %d", r);
902 usbi_dbg("active config %d", *config);
908 * Set the active configuration for a device.
910 * The operating system may or may not have already set an active
911 * configuration on the device. It is up to your application to ensure the
912 * correct configuration is selected before you attempt to claim interfaces
913 * and perform other operations.
915 * If you call this function on a device already configured with the selected
916 * configuration, then this function will act as a lightweight device reset:
917 * it will issue a SET_CONFIGURATION request using the current configuration,
918 * causing most USB-related device state to be reset (altsetting reset to zero,
919 * endpoint halts cleared, toggles reset).
921 * You cannot change/reset configuration if your application has claimed
922 * interfaces - you should free them with libusb_release_interface() first.
923 * You cannot change/reset configuration if other applications or drivers have
924 * claimed interfaces.
926 * A configuration value of -1 will put the device in unconfigured state.
927 * The USB specifications state that a configuration value of 0 does this,
928 * however buggy devices exist which actually have a configuration 0.
930 * You should always use this function rather than formulating your own
931 * SET_CONFIGURATION control request. This is because the underlying operating
932 * system needs to know when such changes happen.
934 * This is a blocking function.
936 * \param dev a device handle
937 * \param configuration the bConfigurationValue of the configuration you
938 * wish to activate, or -1 if you wish to put the device in unconfigured state
939 * \returns 0 on success
940 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
941 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
942 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
943 * \returns another LIBUSB_ERROR code on other failure
945 API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev,
948 usbi_dbg("configuration %d", configuration);
949 return usbi_backend->set_configuration(dev, configuration);
953 * Claim an interface on a given device handle. You must claim the interface
954 * you wish to use before you can perform I/O on any of its endpoints.
956 * It is legal to attempt to claim an already-claimed interface, in which
957 * case libusb just returns 0 without doing anything.
959 * Claiming of interfaces is a purely logical operation; it does not cause
960 * any requests to be sent over the bus. Interface claiming is used to
961 * instruct the underlying operating system that your application wishes
962 * to take ownership of the interface.
964 * This is a non-blocking function.
966 * \param dev a device handle
967 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
969 * \returns 0 on success
970 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
971 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
973 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
974 * \returns a LIBUSB_ERROR code on other failure
976 API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev,
977 int interface_number)
981 usbi_dbg("interface %d", interface_number);
982 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
983 return LIBUSB_ERROR_INVALID_PARAM;
985 pthread_mutex_lock(&dev->lock);
986 if (dev->claimed_interfaces & (1 << interface_number))
989 r = usbi_backend->claim_interface(dev, interface_number);
991 dev->claimed_interfaces |= 1 << interface_number;
994 pthread_mutex_unlock(&dev->lock);
999 * Release an interface previously claimed with libusb_claim_interface(). You
1000 * should release all claimed interfaces before closing a device handle.
1002 * This is a blocking function. A SET_INTERFACE control request will be sent
1003 * to the device, resetting interface state to the first alternate setting.
1005 * \param dev a device handle
1006 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1007 * previously-claimed interface
1008 * \returns 0 on success
1009 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1010 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1011 * \returns another LIBUSB_ERROR code on other failure
1013 API_EXPORTED int libusb_release_interface(libusb_device_handle *dev,
1014 int interface_number)
1018 usbi_dbg("interface %d", interface_number);
1019 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1020 return LIBUSB_ERROR_INVALID_PARAM;
1022 pthread_mutex_lock(&dev->lock);
1023 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1024 r = LIBUSB_ERROR_NOT_FOUND;
1028 r = usbi_backend->release_interface(dev, interface_number);
1030 dev->claimed_interfaces &= ~(1 << interface_number);
1033 pthread_mutex_unlock(&dev->lock);
1038 * Activate an alternate setting for an interface. The interface must have
1039 * been previously claimed with libusb_claim_interface().
1041 * You should always use this function rather than formulating your own
1042 * SET_INTERFACE control request. This is because the underlying operating
1043 * system needs to know when such changes happen.
1045 * This is a blocking function.
1047 * \param dev a device handle
1048 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1049 * previously-claimed interface
1050 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1051 * setting to activate
1052 * \returns 0 on success
1053 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1054 * requested alternate setting does not exist
1055 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1056 * \returns another LIBUSB_ERROR code on other failure
1058 API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev,
1059 int interface_number, int alternate_setting)
1061 usbi_dbg("interface %d altsetting %d",
1062 interface_number, alternate_setting);
1063 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1064 return LIBUSB_ERROR_INVALID_PARAM;
1066 pthread_mutex_lock(&dev->lock);
1067 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1068 pthread_mutex_unlock(&dev->lock);
1069 return LIBUSB_ERROR_NOT_FOUND;
1071 pthread_mutex_unlock(&dev->lock);
1073 return usbi_backend->set_interface_altsetting(dev, interface_number,
1078 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1079 * are unable to receive or transmit data until the halt condition is stalled.
1081 * You should cancel all pending transfers before attempting to clear the halt
1084 * This is a blocking function.
1086 * \param dev a device handle
1087 * \param endpoint the endpoint to clear halt status
1088 * \returns 0 on success
1089 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1090 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1091 * \returns another LIBUSB_ERROR code on other failure
1093 API_EXPORTED int libusb_clear_halt(libusb_device_handle *dev,
1094 unsigned char endpoint)
1096 usbi_dbg("endpoint %x", endpoint);
1097 return usbi_backend->clear_halt(dev, endpoint);
1101 * Perform a USB port reset to reinitialize a device. The system will attempt
1102 * to restore the previous configuration and alternate settings after the
1103 * reset has completed.
1105 * If the reset fails, the descriptors change, or the previous state cannot be
1106 * restored, the device will appear to be disconnected and reconnected. This
1107 * means that the device handle is no longer valid (you should close it) and
1108 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1109 * when this is the case.
1111 * This is a blocking function which usually incurs a noticeable delay.
1113 * \param dev a handle of the device to reset
1114 * \returns 0 on success
1115 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1116 * device has been disconnected
1117 * \returns another LIBUSB_ERROR code on other failure
1119 API_EXPORTED int libusb_reset_device(libusb_device_handle *dev)
1122 return usbi_backend->reset_device(dev);
1126 * Determine if a kernel driver is active on an interface. If a kernel driver
1127 * is active, you cannot claim the interface, and libusb will be unable to
1130 * \param dev a device handle
1131 * \param interface the interface to check
1132 * \returns 0 if no kernel driver is active
1133 * \returns 1 if a kernel driver is active
1134 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1135 * \returns another LIBUSB_ERROR code on other failure
1136 * \see libusb_detach_kernel_driver()
1138 API_EXPORTED int libusb_kernel_driver_active(libusb_device_handle *dev,
1141 usbi_dbg("interface %d", interface);
1142 if (usbi_backend->kernel_driver_active)
1143 return usbi_backend->kernel_driver_active(dev, interface);
1145 return LIBUSB_ERROR_NOT_SUPPORTED;
1149 * Detach a kernel driver from an interface. If successful, you will then be
1150 * able to claim the interface and perform I/O.
1152 * \param dev a device handle
1153 * \param interface the interface to detach the driver from
1154 * \returns 0 on success
1155 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1156 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1157 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1158 * \returns another LIBUSB_ERROR code on other failure
1159 * \see libusb_kernel_driver_active()
1161 API_EXPORTED int libusb_detach_kernel_driver(libusb_device_handle *dev,
1164 usbi_dbg("interface %d", interface);
1165 if (usbi_backend->detach_kernel_driver)
1166 return usbi_backend->detach_kernel_driver(dev, interface);
1168 return LIBUSB_ERROR_NOT_SUPPORTED;
1172 * Set message verbosity.
1173 * - Level 0: no messages ever printed by the library (default)
1174 * - Level 1: error messages are printed to stderr
1175 * - Level 2: warning and error messages are printed to stderr
1176 * - Level 3: informational messages are printed to stdout, warning and error
1177 * messages are printed to stderr
1179 * The default level is 0, which means no messages are ever printed. If you
1180 * choose to increase the message verbosity level, ensure that your
1181 * application does not close the stdout/stderr file descriptors.
1183 * You are advised to set level 3. libusb is conservative with it's message
1184 * logging and most of the time, will only log messages that explain error
1185 * conditions and other oddities. This will help you debug your software.
1187 * If the LIBUSB_DEBUG environment variable was set when libusb was
1188 * initialized, this function does nothing: the message verbosity is fixed
1189 * to the value in the environment variable.
1191 * If libusb was compiled without any message logging, this function does
1192 * nothing: you'll never get any messages.
1194 * If libusb was compiled with verbose debug message logging, this function
1195 * does nothing: you'll always get messages from all levels.
1197 * \param ctx the context to operate on, or NULL for the default context
1198 * \param level debug level to set
1200 API_EXPORTED void libusb_set_debug(libusb_context *ctx, int level)
1202 USBI_GET_CONTEXT(ctx);
1203 if (!ctx->debug_fixed)
1208 * Initialize libusb. This function must be called before calling any other
1210 * \param context Optional output location for context pointer.
1211 * Only valid on return code 0.
1212 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1214 API_EXPORTED int libusb_init(libusb_context **context)
1216 char *dbg = getenv("LIBUSB_DEBUG");
1217 struct libusb_context *ctx = malloc(sizeof(*ctx));
1220 return LIBUSB_ERROR_NO_MEM;
1221 memset(ctx, 0, sizeof(*ctx));
1224 ctx->debug = atoi(dbg);
1226 ctx->debug_fixed = 1;
1230 if (usbi_backend->init) {
1231 int r = usbi_backend->init(ctx);
1238 pthread_mutex_init(&ctx->usb_devs_lock, NULL);
1239 pthread_mutex_init(&ctx->open_devs_lock, NULL);
1240 list_init(&ctx->usb_devs);
1241 list_init(&ctx->open_devs);
1244 pthread_mutex_lock(&default_context_lock);
1245 if (!usbi_default_context) {
1246 usbi_dbg("created default context");
1247 usbi_default_context = ctx;
1249 pthread_mutex_unlock(&default_context_lock);
1257 * Deinitialize libusb. Should be called after closing all open devices and
1258 * before your application terminates.
1259 * \param ctx the context to deinitialize, or NULL for the default context
1261 API_EXPORTED void libusb_exit(struct libusb_context *ctx)
1263 USBI_GET_CONTEXT(ctx);
1266 pthread_mutex_lock(&ctx->open_devs_lock);
1267 if (!list_empty(&ctx->open_devs)) {
1268 struct libusb_device_handle *devh;
1269 struct libusb_device_handle *tmp;
1271 usbi_dbg("naughty app left some devices open!");
1272 list_for_each_entry_safe(devh, tmp, &ctx->open_devs, list) {
1273 list_del(&devh->list);
1278 pthread_mutex_unlock(&ctx->open_devs_lock);
1280 if (usbi_backend->exit)
1281 usbi_backend->exit();
1283 pthread_mutex_lock(&default_context_lock);
1284 if (ctx == usbi_default_context) {
1285 usbi_dbg("freeing default context");
1286 usbi_default_context = NULL;
1288 pthread_mutex_unlock(&default_context_lock);
1293 void usbi_log(struct libusb_context *ctx, enum usbi_log_level level,
1294 const char *function, const char *format, ...)
1297 FILE *stream = stdout;
1300 #ifndef ENABLE_DEBUG_LOGGING
1301 USBI_GET_CONTEXT(ctx);
1304 if (level == LOG_LEVEL_WARNING && ctx->debug < 2)
1306 if (level == LOG_LEVEL_INFO && ctx->debug < 3)
1311 case LOG_LEVEL_INFO:
1314 case LOG_LEVEL_WARNING:
1318 case LOG_LEVEL_ERROR:
1322 case LOG_LEVEL_DEBUG:
1332 fprintf(stream, "libusb:%s [%s] ", prefix, function);
1334 va_start (args, format);
1335 vfprintf(stream, format, args);
1338 fprintf(stream, "\n");