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:
83 int 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 * <tt>libusb_device</tt> 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 <tt>libusb_device_handle</tt> 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_device_ref() and libusb_device_unref(). 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 is available later
167 * through libusb_get_device(). The reference is deleted during libusb_close().
171 * @defgroup misc Miscellaneous structures and constants
172 * This page documents structures and constants that don't belong anywhere
176 /* we traverse usbfs without knowing how many devices we are going to find.
177 * so we create this discovered_devs model which is similar to a linked-list
178 * which grows when required. it can be freed once discovery has completed,
179 * eliminating the need for a list node in the libusb_device structure
181 #define DISCOVERED_DEVICES_SIZE_STEP 8
183 static struct discovered_devs *discovered_devs_alloc(void)
185 struct discovered_devs *ret =
186 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
190 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
195 /* append a device to the discovered devices collection. may realloc itself,
196 * returning new discdevs. returns NULL on realloc failure. */
197 struct discovered_devs *discovered_devs_append(
198 struct discovered_devs *discdevs, struct libusb_device *dev)
200 size_t len = discdevs->len;
203 /* if there is space, just append the device */
204 if (len < discdevs->capacity) {
205 discdevs->devices[len] = libusb_device_ref(dev);
210 /* exceeded capacity, need to grow */
211 usbi_dbg("need to increase capacity");
212 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
213 discdevs = realloc(discdevs,
214 sizeof(*discdevs) + (sizeof(void *) * capacity));
216 discdevs->capacity = capacity;
217 discdevs->devices[len] = libusb_device_ref(dev);
224 static void discovered_devs_free(struct discovered_devs *discdevs)
228 for (i = 0; i < discdevs->len; i++)
229 libusb_device_unref(discdevs->devices[i]);
234 struct libusb_device *usbi_alloc_device(unsigned long session_id)
236 size_t priv_size = usbi_backend->device_priv_size;
237 struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
243 r = pthread_mutex_init(&dev->lock, NULL);
248 dev->session_data = session_id;
249 memset(&dev->os_priv, 0, priv_size);
251 pthread_mutex_lock(&usb_devs_lock);
252 list_add(&dev->list, &usb_devs);
253 pthread_mutex_unlock(&usb_devs_lock);
257 struct libusb_device *usbi_get_device_by_session_id(unsigned long session_id)
259 struct libusb_device *dev;
260 struct libusb_device *ret = NULL;
262 pthread_mutex_lock(&usb_devs_lock);
263 list_for_each_entry(dev, &usb_devs, list)
264 if (dev->session_data == session_id) {
268 pthread_mutex_unlock(&usb_devs_lock);
274 * Returns a list of USB devices currently attached to the system. This is
275 * your entry point into finding a USB device to operate.
277 * You are expected to unreference all the devices when you are done with
278 * them, and then free the list with libusb_free_device_list(). Note that
279 * libusb_free_device_list() can unref all the devices for you. Be careful
280 * not to unreference a device you are about to open until after you have
283 * \param list output location for a list of devices. Must be later freed with
284 * libusb_free_device_list().
285 * \returns the number of devices in the outputted list, or negative on error
287 API_EXPORTED int libusb_get_device_list(struct libusb_device ***list)
289 struct discovered_devs *discdevs = discovered_devs_alloc();
290 struct libusb_device **ret;
299 r = usbi_backend->get_device_list(&discdevs);
303 /* convert discovered_devs into a list */
305 ret = malloc(sizeof(void *) * (len + 1));
312 for (i = 0; i < len; i++) {
313 struct libusb_device *dev = discdevs->devices[i];
314 ret[i] = libusb_device_ref(dev);
319 discovered_devs_free(discdevs);
324 * Frees a list of devices previously discovered using
325 * libusb_get_device_list(). If the unref_devices parameter is set, the
326 * reference count of each device in the list is decremented by 1.
327 * \param list the list to free
328 * \param unref_devices whether to unref the devices in the list
330 API_EXPORTED void libusb_free_device_list(struct libusb_device **list,
338 struct libusb_device *dev;
340 while ((dev = list[i++]) != NULL)
341 libusb_device_unref(dev);
347 * Increment the reference count of a device.
348 * \param dev the device to reference
349 * \returns the same device
351 API_EXPORTED struct libusb_device *libusb_device_ref(struct libusb_device *dev)
353 pthread_mutex_lock(&dev->lock);
355 pthread_mutex_unlock(&dev->lock);
360 * Decrement the reference count of a device. If the decrement operation
361 * causes the reference count to reach zero, the device shall be destroyed.
362 * \param dev the device to unreference
364 API_EXPORTED void libusb_device_unref(struct libusb_device *dev)
371 pthread_mutex_lock(&dev->lock);
372 refcnt = --dev->refcnt;
373 pthread_mutex_unlock(&dev->lock);
376 usbi_dbg("destroy device %04x:%04x", dev->desc.idVendor,
377 dev->desc.idProduct);
379 if (usbi_backend->destroy_device)
380 usbi_backend->destroy_device(dev);
382 pthread_mutex_lock(&usb_devs_lock);
383 list_del(&dev->list);
384 pthread_mutex_unlock(&usb_devs_lock);
393 * Open a device and obtain a device handle. A handle allows you to perform
394 * I/O on the device in question.
396 * Internally, this function adds a reference to the device and makes it
397 * available to you through libusb_get_device(). This reference is removed
398 * during libusb_close().
400 * \param dev the device to open
401 * \returns a handle for the device, or NULL on error
403 API_EXPORTED struct libusb_device_handle *libusb_open(struct libusb_device *dev)
405 struct libusb_device_handle *handle;
406 size_t priv_size = usbi_backend->device_handle_priv_size;
408 usbi_dbg("open %04x:%04x", dev->desc.idVendor, dev->desc.idProduct);
410 handle = malloc(sizeof(*handle) + priv_size);
414 handle->dev = libusb_device_ref(dev);
415 memset(&handle->os_priv, 0, priv_size);
416 r = usbi_backend->open(handle);
418 libusb_device_unref(dev);
423 pthread_mutex_lock(&usbi_open_devs_lock);
424 list_add(&handle->list, &usbi_open_devs);
425 pthread_mutex_unlock(&usbi_open_devs_lock);
430 * Convenience function for finding a device with a particular
431 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
432 * for those scenarios where you are using libusb to knock up a quick test
433 * application - it allows you to avoid calling libusb_get_device_list() and
434 * worrying about traversing/freeing the list.
436 * This function has limitations and is hence not intended for use in real
437 * applications: if multiple devices have the same IDs it will only
438 * give you the first one, etc.
440 * \param vendor_id the idVendor value to search for
441 * \param product_id the idProduct value to search for
442 * \returns a handle for the first found device, or NULL on error or if the
443 * device could not be found. */
444 API_EXPORTED struct libusb_device_handle *libusb_open_device_with_vid_pid(
445 uint16_t vendor_id, uint16_t product_id)
447 struct libusb_device **devs;
448 struct libusb_device *found = NULL;
449 struct libusb_device *dev;
450 struct libusb_device_handle *handle = NULL;
453 if (libusb_get_device_list(&devs) < 0)
456 while ((dev = devs[i++]) != NULL) {
457 const struct libusb_device_descriptor *desc =
458 libusb_get_device_descriptor(dev);
459 if (desc->idVendor == vendor_id && desc->idProduct == product_id) {
466 handle = libusb_open(found);
468 libusb_free_device_list(devs, 1);
472 static void do_close(struct libusb_device_handle *dev_handle)
474 usbi_backend->close(dev_handle);
475 libusb_device_unref(dev_handle->dev);
479 * Close a device handle. Should be called on all open handles before your
482 * Internally, this function destroys the reference that was added by
483 * libusb_open() on the given device.
485 * \param dev_handle the handle to close
487 API_EXPORTED void libusb_close(struct libusb_device_handle *dev_handle)
493 pthread_mutex_lock(&usbi_open_devs_lock);
494 list_del(&dev_handle->list);
495 pthread_mutex_unlock(&usbi_open_devs_lock);
497 do_close(dev_handle);
502 * Get the underlying device for a handle. This function does not modify
503 * the reference count of the returned device, so do not feel compelled to
504 * unreference it when you are done.
505 * \param dev_handle a device handle
506 * \returns the underlying device
508 API_EXPORTED struct libusb_device *libusb_get_device(
509 struct libusb_device_handle *dev_handle)
511 return dev_handle->dev;
514 /* FIXME: what about claiming multiple interfaces? */
516 * Claim an interface on a given device handle. You must claim the interface
517 * you wish to use before you can perform I/O on any of the endpoints.
518 * \param iface the <tt>bInterfaceNumber</tt> of the interface you wish to claim
519 * \param dev a device handle
520 * \returns 0 on success, non-zero on error
522 API_EXPORTED int libusb_claim_interface(struct libusb_device_handle *dev,
525 usbi_dbg("interface %d", iface);
526 return usbi_backend->claim_interface(dev, iface);
530 * Release an interface previously claimed with libusb_claim_interface(). You
531 * should release all claimed interfaces before closing a device handle.
532 * \param dev a device handle
533 * \param iface the <tt>bInterfaceNumber</tt> of the previously-claimed
535 * \returns 0 on success, non-zero on error
537 API_EXPORTED int libusb_release_interface(struct libusb_device_handle *dev,
540 usbi_dbg("interface %d", iface);
541 return usbi_backend->release_interface(dev, iface);
545 API_EXPORTED int libusb_set_interface_altsetting(
546 struct libusb_device_handle *dev, int iface, int altsetting)
548 usbi_dbg("interface %d altsetting %d", iface, altsetting);
549 return usbi_backend->set_interface_altsetting(dev, iface, altsetting);
553 * Initialize libusb. This function must be called before calling any other
555 * \returns 0 on success, non-zero on error
557 API_EXPORTED int libusb_init(void)
561 if (usbi_backend->init) {
562 int r = usbi_backend->init();
567 list_init(&usb_devs);
568 list_init(&usbi_open_devs);
574 * Deinitialize libusb. Should be called after closing all open devices and
575 * before your application terminates.
577 API_EXPORTED void libusb_exit(void)
579 struct libusb_device_handle *devh;
582 pthread_mutex_lock(&usbi_open_devs_lock);
583 if (!list_empty(&usbi_open_devs)) {
584 usbi_dbg("naughty app left some devices open!\n");
585 list_for_each_entry(devh, &usbi_open_devs, list)
587 /* FIXME where do the open handles get freed? */
589 pthread_mutex_unlock(&usbi_open_devs_lock);
591 if (usbi_backend->exit)
592 usbi_backend->exit();
595 void usbi_log(enum usbi_log_level level, const char *function,
596 const char *format, ...)
599 FILE *stream = stdout;
606 case LOG_LEVEL_WARNING:
610 case LOG_LEVEL_ERROR:
614 case LOG_LEVEL_DEBUG:
624 fprintf(stream, "libusb:%s [%s] ", prefix, function);
626 va_start (args, format);
627 vfprintf(stream, format, args);
630 fprintf(stream, "\n");