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
34 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
36 #error "Unsupported OS"
39 static struct list_head usb_devs;
40 static pthread_mutex_t usb_devs_lock = PTHREAD_MUTEX_INITIALIZER;
42 struct list_head usbi_open_devs;
43 pthread_mutex_t usbi_open_devs_lock = PTHREAD_MUTEX_INITIALIZER;
46 * \mainpage libusb-1.0 API Reference
47 * libusb is an open source library that allows you to communicate with USB
48 * devices from userspace. For more info, see the
49 * <a href="http://libusb.sourceforge.net">libusb homepage</a>.
51 * This documentation is aimed at application developers wishing to
52 * communicate with USB peripherals from their own software. After reviewing
53 * this documentation, feedback and questions can be sent to the
54 * <a href="http://sourceforge.net/mail/?group_id=1674">libusb-devel mailing
59 * @defgroup lib Library initialization/deinitialization
60 * This page details how to initialize and deinitialize libusb. Initialization
61 * must be performed before using any libusb functionality, and similarly you
62 * must not call any libusb functions after deinitialization.
66 * @defgroup dev Device handling and enumeration
67 * The functionality documented below is designed to help with the following
69 * - Enumerating the USB devices currently attached to the system
70 * - Choosing a device to operate from your software
71 * - Opening and closing the chosen device
73 * \section nutshell In a nutshell...
75 * The description below really makes things sound more complicated than they
76 * actually are. The following sequence of function calls will be suitable
77 * for almost all scenarios and does not require you to have such a deep
78 * understanding of the resource management issues:
82 libusb_device *found = NULL;
83 size_t cnt = libusb_get_device_list(&list);
88 for (i = 0; i < cnt; i++) {
89 libusb_device *device = list[i];
90 if (is_interesting(device)) {
97 libusb_device_handle *handle = libusb_open(found);
101 libusb_free_device_list(list, 1);
104 * The two important points:
105 * - You asked libusb_free_device_list() to unreference the devices (2nd
107 * - You opened the device before freeing the list and unreferencing the
110 * If you ended up with a handle, you can now proceed to perform I/O on the
113 * \section devshandles Devices and device handles
114 * libusb has a concept of a USB device, represented by the
115 * \ref libusb_device opaque type. A device represents a USB device that
116 * is currently or was previously connected to the system. Using a reference
117 * to a device, you can determine certain information about the device (e.g.
118 * you can read the descriptor data).
120 * The libusb_get_device_list() function can be used to obtain a list of
121 * devices currently connected to the system. This is known as device
124 * Just because you have a reference to a device does not mean it is
125 * necessarily usable. The device may have been unplugged, you may not have
126 * permission to operate such device, or another program or driver may be
129 * When you've found a device that you'd like to operate, you must ask
130 * libusb to open the device using the libusb_open() function. Assuming
131 * success, libusb then returns you a <em>device handle</em>
132 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
133 * operate on the handle rather than the original device pointer.
135 * \section devref Device discovery and reference counting
137 * Device discovery (i.e. calling libusb_get_device_list()) returns a
138 * freshly-allocated list of devices. The list itself must be freed when
139 * you are done with it. libusb also needs to know when it is OK to free
140 * the contents of the list - the devices themselves.
142 * To handle these issues, libusb provides you with two separate items:
143 * - A function to free the list itself
144 * - A reference counting system for the devices inside
146 * New devices presented by the libusb_get_device_list() function all have a
147 * reference count of 1. You can increase and decrease reference count using
148 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
149 * it's reference count reaches 0.
151 * With the above information in mind, the process of opening a device can
152 * be viewed as follows:
153 * -# Discover devices using libusb_get_device_list().
154 * -# Choose the device that you want to operate, and call libusb_open().
155 * -# Unref all devices in the discovered device list.
156 * -# Free the discovered device list.
158 * The order is important - you must not unreference the device before
159 * attempting to open it, because unreferencing it may destroy the device.
161 * For convenience, the libusb_free_device_list() function includes a
162 * parameter to optionally unreference all the devices in the list before
163 * freeing the list itself. This combines steps 3 and 4 above.
165 * As an implementation detail, libusb_open() actually adds a reference to
166 * the device in question. This is because the device remains available
167 * through the handle via libusb_get_device(). The reference is deleted during
172 * @defgroup misc Miscellaneous structures and constants
173 * This page documents structures and constants that don't belong anywhere
177 /* we traverse usbfs without knowing how many devices we are going to find.
178 * so we create this discovered_devs model which is similar to a linked-list
179 * which grows when required. it can be freed once discovery has completed,
180 * eliminating the need for a list node in the libusb_device structure
182 #define DISCOVERED_DEVICES_SIZE_STEP 8
184 static struct discovered_devs *discovered_devs_alloc(void)
186 struct discovered_devs *ret =
187 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
191 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
196 /* append a device to the discovered devices collection. may realloc itself,
197 * returning new discdevs. returns NULL on realloc failure. */
198 struct discovered_devs *discovered_devs_append(
199 struct discovered_devs *discdevs, struct libusb_device *dev)
201 size_t len = discdevs->len;
204 /* if there is space, just append the device */
205 if (len < discdevs->capacity) {
206 discdevs->devices[len] = libusb_ref_device(dev);
211 /* exceeded capacity, need to grow */
212 usbi_dbg("need to increase capacity");
213 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
214 discdevs = realloc(discdevs,
215 sizeof(*discdevs) + (sizeof(void *) * capacity));
217 discdevs->capacity = capacity;
218 discdevs->devices[len] = libusb_ref_device(dev);
225 static void discovered_devs_free(struct discovered_devs *discdevs)
229 for (i = 0; i < discdevs->len; i++)
230 libusb_unref_device(discdevs->devices[i]);
235 struct libusb_device *usbi_alloc_device(unsigned long session_id)
237 size_t priv_size = usbi_backend->device_priv_size;
238 struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
244 r = pthread_mutex_init(&dev->lock, NULL);
249 dev->session_data = session_id;
250 memset(&dev->os_priv, 0, priv_size);
252 pthread_mutex_lock(&usb_devs_lock);
253 list_add(&dev->list, &usb_devs);
254 pthread_mutex_unlock(&usb_devs_lock);
258 struct libusb_device *usbi_get_device_by_session_id(unsigned long session_id)
260 struct libusb_device *dev;
261 struct libusb_device *ret = NULL;
263 pthread_mutex_lock(&usb_devs_lock);
264 list_for_each_entry(dev, &usb_devs, list)
265 if (dev->session_data == session_id) {
269 pthread_mutex_unlock(&usb_devs_lock);
275 * Returns a list of USB devices currently attached to the system. This is
276 * your entry point into finding a USB device to operate.
278 * You are expected to unreference all the devices when you are done with
279 * them, and then free the list with libusb_free_device_list(). Note that
280 * libusb_free_device_list() can unref all the devices for you. Be careful
281 * not to unreference a device you are about to open until after you have
284 * This return value of this function indicates the number of devices in
285 * the resultant list. The list is actually one element larger, as it is
288 * \param list output location for a list of devices. Must be later freed with
289 * libusb_free_device_list().
290 * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
291 * on memory allocation failure.
293 API_EXPORTED size_t libusb_get_device_list(libusb_device ***list)
295 struct discovered_devs *discdevs = discovered_devs_alloc();
296 struct libusb_device **ret;
303 return LIBUSB_ERROR_NO_MEM;
305 r = usbi_backend->get_device_list(&discdevs);
311 /* convert discovered_devs into a list */
313 ret = malloc(sizeof(void *) * (len + 1));
315 len = LIBUSB_ERROR_NO_MEM;
320 for (i = 0; i < len; i++) {
321 struct libusb_device *dev = discdevs->devices[i];
322 ret[i] = libusb_ref_device(dev);
327 discovered_devs_free(discdevs);
332 * Frees a list of devices previously discovered using
333 * libusb_get_device_list(). If the unref_devices parameter is set, the
334 * reference count of each device in the list is decremented by 1.
335 * \param list the list to free
336 * \param unref_devices whether to unref the devices in the list
338 API_EXPORTED void libusb_free_device_list(libusb_device **list,
346 struct libusb_device *dev;
348 while ((dev = list[i++]) != NULL)
349 libusb_unref_device(dev);
355 * Get the number of the bus that a device is connected to.
356 * \param dev a device
357 * \returns the bus number
359 API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev)
361 return dev->bus_number;
365 * Get the address of the device on the bus it is connected to.
366 * \param dev a device
367 * \returns the device address
369 API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev)
371 return dev->device_address;
375 * Increment the reference count of a device.
376 * \param dev the device to reference
377 * \returns the same device
379 API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev)
381 pthread_mutex_lock(&dev->lock);
383 pthread_mutex_unlock(&dev->lock);
388 * Decrement the reference count of a device. If the decrement operation
389 * causes the reference count to reach zero, the device shall be destroyed.
390 * \param dev the device to unreference
392 API_EXPORTED void libusb_unref_device(libusb_device *dev)
399 pthread_mutex_lock(&dev->lock);
400 refcnt = --dev->refcnt;
401 pthread_mutex_unlock(&dev->lock);
404 usbi_dbg("destroy device %04x:%04x", dev->desc.idVendor,
405 dev->desc.idProduct);
407 if (usbi_backend->destroy_device)
408 usbi_backend->destroy_device(dev);
410 pthread_mutex_lock(&usb_devs_lock);
411 list_del(&dev->list);
412 pthread_mutex_unlock(&usb_devs_lock);
415 usbi_clear_configurations(dev);
423 * Open a device and obtain a device handle. A handle allows you to perform
424 * I/O on the device in question.
426 * Internally, this function adds a reference to the device and makes it
427 * available to you through libusb_get_device(). This reference is removed
428 * during libusb_close().
430 * \param dev the device to open
431 * \returns a handle for the device, or NULL on error
433 API_EXPORTED libusb_device_handle *libusb_open(libusb_device *dev)
435 struct libusb_device_handle *handle;
436 size_t priv_size = usbi_backend->device_handle_priv_size;
438 usbi_dbg("open %04x:%04x", dev->desc.idVendor, dev->desc.idProduct);
440 handle = malloc(sizeof(*handle) + priv_size);
444 r = pthread_mutex_init(&handle->lock, NULL);
448 handle->dev = libusb_ref_device(dev);
449 handle->claimed_interfaces = 0;
450 memset(&handle->os_priv, 0, priv_size);
452 r = usbi_backend->open(handle);
454 libusb_unref_device(dev);
459 pthread_mutex_lock(&usbi_open_devs_lock);
460 list_add(&handle->list, &usbi_open_devs);
461 pthread_mutex_unlock(&usbi_open_devs_lock);
466 * Convenience function for finding a device with a particular
467 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
468 * for those scenarios where you are using libusb to knock up a quick test
469 * application - it allows you to avoid calling libusb_get_device_list() and
470 * worrying about traversing/freeing the list.
472 * This function has limitations and is hence not intended for use in real
473 * applications: if multiple devices have the same IDs it will only
474 * give you the first one, etc.
476 * \param vendor_id the idVendor value to search for
477 * \param product_id the idProduct value to search for
478 * \returns a handle for the first found device, or NULL on error or if the
479 * device could not be found. */
480 API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid(
481 uint16_t vendor_id, uint16_t product_id)
483 struct libusb_device **devs;
484 struct libusb_device *found = NULL;
485 struct libusb_device *dev;
486 struct libusb_device_handle *handle = NULL;
489 if (libusb_get_device_list(&devs) < 0)
492 while ((dev = devs[i++]) != NULL) {
493 const struct libusb_device_descriptor *desc =
494 libusb_get_device_descriptor(dev);
495 if (desc->idVendor == vendor_id && desc->idProduct == product_id) {
502 handle = libusb_open(found);
504 libusb_free_device_list(devs, 1);
508 static void do_close(struct libusb_device_handle *dev_handle)
510 usbi_backend->close(dev_handle);
511 libusb_unref_device(dev_handle->dev);
515 * Close a device handle. Should be called on all open handles before your
518 * Internally, this function destroys the reference that was added by
519 * libusb_open() on the given device.
521 * \param dev_handle the handle to close
523 API_EXPORTED void libusb_close(libusb_device_handle *dev_handle)
529 pthread_mutex_lock(&usbi_open_devs_lock);
530 list_del(&dev_handle->list);
531 pthread_mutex_unlock(&usbi_open_devs_lock);
533 do_close(dev_handle);
538 * Get the underlying device for a handle. This function does not modify
539 * the reference count of the returned device, so do not feel compelled to
540 * unreference it when you are done.
541 * \param dev_handle a device handle
542 * \returns the underlying device
544 API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle)
546 return dev_handle->dev;
550 * Set the active configuration for a device. The operating system may have
551 * already set an active configuration on the device, but for portability
552 * reasons you should use this function to select the configuration you want
553 * before claiming any interfaces.
555 * If you wish to change to another configuration at some later time, you
556 * must release all claimed interfaces using libusb_release_interface() before
557 * setting a new active configuration.
559 * \param dev a device handle
560 * \param configuration the bConfigurationValue of the configuration you
562 * \returns 0 on success
563 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
564 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
565 * \returns another LIBUSB_ERROR code on other failure
567 API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev,
570 usbi_dbg("configuration %d", configuration);
571 return usbi_backend->set_configuration(dev, configuration);
575 * Claim an interface on a given device handle. You must claim the interface
576 * you wish to use before you can perform I/O on any of its endpoints.
578 * It is legal to attempt to claim an already-claimed interface, in which
579 * case libusb just returns 0 without doing anything.
581 * \param dev a device handle
582 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
584 * \returns 0 on success
585 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
586 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
588 * \returns a LIBUSB_ERROR code on other failure
590 API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev,
591 int interface_number)
595 usbi_dbg("interface %d", interface_number);
596 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
597 return LIBUSB_ERROR_INVALID_PARAM;
599 pthread_mutex_lock(&dev->lock);
600 if (dev->claimed_interfaces & (1 << interface_number))
603 r = usbi_backend->claim_interface(dev, interface_number);
605 dev->claimed_interfaces |= 1 << interface_number;
608 pthread_mutex_unlock(&dev->lock);
613 * Release an interface previously claimed with libusb_claim_interface(). You
614 * should release all claimed interfaces before closing a device handle.
615 * \param dev a device handle
616 * \param interface_number the <tt>bInterfaceNumber</tt> of the
617 * previously-claimed interface
618 * \returns 0 on success, or a LIBUSB_ERROR code on failure.
619 * LIBUSB_ERROR_NOT_FOUND indicates that the interface was not claimed.
621 API_EXPORTED int libusb_release_interface(libusb_device_handle *dev,
622 int interface_number)
626 usbi_dbg("interface %d", interface_number);
627 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
628 return LIBUSB_ERROR_INVALID_PARAM;
630 pthread_mutex_lock(&dev->lock);
631 if (!(dev->claimed_interfaces & (1 << interface_number))) {
632 r = LIBUSB_ERROR_NOT_FOUND;
636 r = usbi_backend->release_interface(dev, interface_number);
638 dev->claimed_interfaces &= ~(1 << interface_number);
641 pthread_mutex_unlock(&dev->lock);
646 * Activate an alternate setting for an interface. The interface must have
647 * been previously claimed with libusb_claim_interface().
649 * \param dev a device handle
650 * \param interface_number the <tt>bInterfaceNumber</tt> of the
651 * previously-claimed interface
652 * \param altsetting the <tt>bAlternateSetting</tt> of the alternate setting
654 * \returns 0 on success
655 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
656 * requested alternate setting does not exist
657 * \returns another LIBUSB_ERROR code on other failure
659 API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev,
660 int interface_number, int alternate_setting)
662 usbi_dbg("interface %d altsetting %d", interface_number, alternate_setting);
663 if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
664 return LIBUSB_ERROR_INVALID_PARAM;
666 pthread_mutex_lock(&dev->lock);
667 if (!(dev->claimed_interfaces & (1 << interface_number))) {
668 pthread_mutex_unlock(&dev->lock);
669 return LIBUSB_ERROR_NOT_FOUND;
671 pthread_mutex_unlock(&dev->lock);
673 return usbi_backend->set_interface_altsetting(dev, interface_number,
678 * Initialize libusb. This function must be called before calling any other
680 * \returns 0 on success, or a LIBUSB_ERROR code on failure
682 API_EXPORTED int libusb_init(void)
686 if (usbi_backend->init) {
687 int r = usbi_backend->init();
692 list_init(&usb_devs);
693 list_init(&usbi_open_devs);
699 * Deinitialize libusb. Should be called after closing all open devices and
700 * before your application terminates.
702 API_EXPORTED void libusb_exit(void)
704 struct libusb_device_handle *devh;
707 pthread_mutex_lock(&usbi_open_devs_lock);
708 if (!list_empty(&usbi_open_devs)) {
709 usbi_dbg("naughty app left some devices open!\n");
710 list_for_each_entry(devh, &usbi_open_devs, list)
712 /* FIXME where do the open handles get freed? */
714 pthread_mutex_unlock(&usbi_open_devs_lock);
716 if (usbi_backend->exit)
717 usbi_backend->exit();
720 void usbi_log(enum usbi_log_level level, const char *function,
721 const char *format, ...)
724 FILE *stream = stdout;
731 case LOG_LEVEL_WARNING:
735 case LOG_LEVEL_ERROR:
739 case LOG_LEVEL_DEBUG:
749 fprintf(stream, "libusb:%s [%s] ", prefix, function);
751 va_start (args, format);
752 vfprintf(stream, format, args);
755 fprintf(stream, "\n");