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);
242 dev->session_data = session_id;
243 memset(&dev->os_priv, 0, priv_size);
245 pthread_mutex_lock(&usb_devs_lock);
246 list_add(&dev->list, &usb_devs);
247 pthread_mutex_unlock(&usb_devs_lock);
251 struct libusb_device *usbi_get_device_by_session_id(unsigned long session_id)
253 struct libusb_device *dev;
254 struct libusb_device *ret = NULL;
256 pthread_mutex_lock(&usb_devs_lock);
257 list_for_each_entry(dev, &usb_devs, list)
258 if (dev->session_data == session_id) {
262 pthread_mutex_unlock(&usb_devs_lock);
268 * Returns a list of USB devices currently attached to the system. This is
269 * your entry point into finding a USB device to operate.
271 * You are expected to unreference all the devices when you are done with
272 * them, and then free the list with libusb_free_device_list(). Note that
273 * libusb_free_device_list() can unref all the devices for you. Be careful
274 * not to unreference a device you are about to open until after you have
277 * \param list output location for a list of devices. Must be later freed with
278 * libusb_free_device_list().
279 * \returns the number of devices in the outputted list, or negative on error
281 API_EXPORTED int libusb_get_device_list(struct libusb_device ***list)
283 struct discovered_devs *discdevs = discovered_devs_alloc();
284 struct libusb_device **ret;
293 r = usbi_backend->get_device_list(&discdevs);
297 /* convert discovered_devs into a list */
299 ret = malloc(sizeof(void *) * (len + 1));
306 for (i = 0; i < len; i++) {
307 struct libusb_device *dev = discdevs->devices[i];
308 ret[i] = libusb_device_ref(dev);
313 discovered_devs_free(discdevs);
318 * Frees a list of devices previously discovered using
319 * libusb_get_device_list(). If the unref_devices parameter is set, the
320 * reference count of each device in the list is decremented by 1.
321 * \param list the list to free
322 * \param unref_devices whether to unref the devices in the list
324 API_EXPORTED void libusb_free_device_list(struct libusb_device **list,
332 struct libusb_device *dev;
334 while ((dev = list[i++]) != NULL)
335 libusb_device_unref(dev);
341 * Increment the reference count of a device.
342 * \param dev the device to reference
343 * \returns the same device
345 API_EXPORTED struct libusb_device *libusb_device_ref(struct libusb_device *dev)
352 * Decrement the reference count of a device. If the decrement operation
353 * causes the reference count to reach zero, the device shall be destroyed.
354 * \param dev the device to unreference
356 API_EXPORTED void libusb_device_unref(struct libusb_device *dev)
361 if (--dev->refcnt == 0) {
362 usbi_dbg("destroy device %04x:%04x", dev->desc.idVendor,
363 dev->desc.idProduct);
365 if (usbi_backend->destroy_device)
366 usbi_backend->destroy_device(dev);
368 pthread_mutex_lock(&usb_devs_lock);
369 list_del(&dev->list);
370 pthread_mutex_unlock(&usb_devs_lock);
379 * Open a device and obtain a device handle. A handle allows you to perform
380 * I/O on the device in question.
382 * Internally, this function adds a reference to the device and makes it
383 * available to you through libusb_get_device(). This reference is removed
384 * during libusb_close().
386 * \param dev the device to open
387 * \returns a handle for the device, or NULL on error
389 API_EXPORTED struct libusb_device_handle *libusb_open(struct libusb_device *dev)
391 struct libusb_device_handle *handle;
392 size_t priv_size = usbi_backend->device_handle_priv_size;
394 usbi_dbg("open %04x:%04x", dev->desc.idVendor, dev->desc.idProduct);
396 handle = malloc(sizeof(*handle) + priv_size);
400 handle->dev = libusb_device_ref(dev);
401 memset(&handle->os_priv, 0, priv_size);
402 r = usbi_backend->open(handle);
404 libusb_device_unref(dev);
409 pthread_mutex_lock(&usbi_open_devs_lock);
410 list_add(&handle->list, &usbi_open_devs);
411 pthread_mutex_unlock(&usbi_open_devs_lock);
416 * Convenience function for finding a device with a particular
417 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
418 * for those scenarios where you are using libusb to knock up a quick test
419 * application - it allows you to avoid calling libusb_get_device_list() and
420 * worrying about traversing/freeing the list.
422 * This function has limitations and is hence not intended for use in real
423 * applications: if multiple devices have the same IDs it will only
424 * give you the first one, etc.
426 * \param vendor_id the idVendor value to search for
427 * \param product_id the idProduct value to search for
428 * \returns a handle for the first found device, or NULL on error or if the
429 * device could not be found. */
430 API_EXPORTED struct libusb_device_handle *libusb_open_device_with_vid_pid(
431 uint16_t vendor_id, uint16_t product_id)
433 struct libusb_device **devs;
434 struct libusb_device *found = NULL;
435 struct libusb_device *dev;
436 struct libusb_device_handle *handle = NULL;
439 if (libusb_get_device_list(&devs) < 0)
442 while ((dev = devs[i++]) != NULL) {
443 const struct libusb_device_descriptor *desc =
444 libusb_get_device_descriptor(dev);
445 if (desc->idVendor == vendor_id && desc->idProduct == product_id) {
452 handle = libusb_open(found);
454 libusb_free_device_list(devs, 1);
458 static void do_close(struct libusb_device_handle *dev_handle)
460 usbi_backend->close(dev_handle);
461 libusb_device_unref(dev_handle->dev);
465 * Close a device handle. Should be called on all open handles before your
468 * Internally, this function destroys the reference that was added by
469 * libusb_open() on the given device.
471 * \param dev_handle the handle to close
473 API_EXPORTED void libusb_close(struct libusb_device_handle *dev_handle)
479 pthread_mutex_lock(&usbi_open_devs_lock);
480 list_del(&dev_handle->list);
481 pthread_mutex_unlock(&usbi_open_devs_lock);
483 do_close(dev_handle);
488 * Get the underlying device for a handle. This function does not modify
489 * the reference count of the returned device, so do not feel compelled to
490 * unreference it when you are done.
491 * \param dev_handle a device handle
492 * \returns the underlying device
494 API_EXPORTED struct libusb_device *libusb_get_device(
495 struct libusb_device_handle *dev_handle)
497 return dev_handle->dev;
500 /* FIXME: what about claiming multiple interfaces? */
502 * Claim an interface on a given device handle. You must claim the interface
503 * you wish to use before you can perform I/O on any of the endpoints.
504 * \param iface the <tt>bInterfaceNumber</tt> of the interface you wish to claim
505 * \param dev a device handle
506 * \returns 0 on success, non-zero on error
508 API_EXPORTED int libusb_claim_interface(struct libusb_device_handle *dev,
511 usbi_dbg("interface %d", iface);
512 return usbi_backend->claim_interface(dev, iface);
516 * Release an interface previously claimed with libusb_claim_interface(). You
517 * should release all claimed interfaces before closing a device handle.
518 * \param dev a device handle
519 * \param iface the <tt>bInterfaceNumber</tt> of the previously-claimed
521 * \returns 0 on success, non-zero on error
523 API_EXPORTED int libusb_release_interface(struct libusb_device_handle *dev,
526 usbi_dbg("interface %d", iface);
527 return usbi_backend->release_interface(dev, iface);
531 API_EXPORTED int libusb_set_interface_altsetting(
532 struct libusb_device_handle *dev, int iface, int altsetting)
534 usbi_dbg("interface %d altsetting %d", iface, altsetting);
535 return usbi_backend->set_interface_altsetting(dev, iface, altsetting);
539 * Initialize libusb. This function must be called before calling any other
541 * \returns 0 on success, non-zero on error
543 API_EXPORTED int libusb_init(void)
547 if (usbi_backend->init) {
548 int r = usbi_backend->init();
553 list_init(&usb_devs);
554 list_init(&usbi_open_devs);
560 * Deinitialize libusb. Should be called after closing all open devices and
561 * before your application terminates.
563 API_EXPORTED void libusb_exit(void)
565 struct libusb_device_handle *devh;
568 pthread_mutex_lock(&usbi_open_devs_lock);
569 if (!list_empty(&usbi_open_devs)) {
570 usbi_dbg("naughty app left some devices open!\n");
571 list_for_each_entry(devh, &usbi_open_devs, list)
573 /* FIXME where do the open handles get freed? */
575 pthread_mutex_unlock(&usbi_open_devs_lock);
577 if (usbi_backend->exit)
578 usbi_backend->exit();
581 void usbi_log(enum usbi_log_level level, const char *function,
582 const char *format, ...)
585 FILE *stream = stdout;
592 case LOG_LEVEL_WARNING:
596 case LOG_LEVEL_ERROR:
600 case LOG_LEVEL_DEBUG:
610 fprintf(stream, "libusb:%s [%s] ", prefix, function);
612 va_start (args, format);
613 vfprintf(stream, format, args);
616 fprintf(stream, "\n");