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 struct list_head usbi_open_devs;
43 * \mainpage libusb-1.0 API Reference
44 * libusb is an open source library that allows you to communicate with USB
45 * devices from userspace. For more info, see the
46 * <a href="http://libusb.sourceforge.net">libusb homepage</a>.
48 * This documentation is aimed at application developers wishing to
49 * communicate with USB peripherals from their own software. After reviewing
50 * this documentation, feedback and questions can be sent to the
51 * <a href="http://sourceforge.net/mail/?group_id=1674">libusb-devel mailing
56 * @defgroup lib Library initialization/deinitialization
57 * This page details how to initialize and deinitialize libusb. Initialization
58 * must be performed before using any libusb functionality, and similarly you
59 * must not call any libusb functions after deinitialization.
63 * @defgroup dev Device handling and enumeration
64 * The functionality documented below is designed to help with the following
66 * - Enumerating the USB devices currently attached to the system
67 * - Choosing a device to operate from your software
68 * - Opening and closing the chosen device
70 * \section nutshell In a nutshell...
72 * The description below really makes things sound more complicated than they
73 * actually are. The following sequence of function calls will be suitable
74 * for almost all scenarios and does not require you to have such a deep
75 * understanding of the resource management issues:
80 int cnt = libusb_get_device_list(&list);
85 for (i = 0; i < cnt; i++) {
86 libusb_device *device = list[i];
87 if (is_interesting(device)) {
94 libusb_device_handle *handle = libusb_open(found);
98 libusb_free_device_list(list, 1);
101 * The two important points:
102 * - You asked libusb_free_device_list() to unreference the devices (2nd
104 * - You opened the device before freeing the list and unreferencing the
107 * If you ended up with a handle, you can now proceed to perform I/O on the
110 * \section devshandles Devices and device handles
111 * libusb has a concept of a USB device, represented by the
112 * <tt>libusb_device</tt> opaque type. A device represents a USB device that
113 * is currently or was previously connected to the system. Using a reference
114 * to a device, you can determine certain information about the device (e.g.
115 * you can read the descriptor data).
117 * The libusb_get_device_list() function can be used to obtain a list of
118 * devices currently connected to the system. This is known as device
121 * Just because you have a reference to a device does not mean it is
122 * necessarily usable. The device may have been unplugged, you may not have
123 * permission to operate such device, or another program or driver may be
126 * When you've found a device that you'd like to operate, you must ask
127 * libusb to open the device using the libusb_open() function. Assuming
128 * success, libusb then returns you a <em>device handle</em>
129 * (a <tt>libusb_device_handle</tt> pointer). All "real" I/O operations then
130 * operate on the handle rather than the original device pointer.
132 * \section devref Device discovery and reference counting
134 * Device discovery (i.e. calling libusb_get_device_list()) returns a
135 * freshly-allocated list of devices. The list itself must be freed when
136 * you are done with it. libusb also needs to know when it is OK to free
137 * the contents of the list - the devices themselves.
139 * To handle these issues, libusb provides you with two separate items:
140 * - A function to free the list itself
141 * - A reference counting system for the devices inside
143 * New devices presented by the libusb_get_device_list() function all have a
144 * reference count of 1. You can increase and decrease reference count using
145 * libusb_device_ref() and libusb_device_unref(). A device is destroyed when
146 * it's reference count reaches 0.
148 * With the above information in mind, the process of opening a device can
149 * be viewed as follows:
150 * -# Discover devices using libusb_get_device_list().
151 * -# Choose the device that you want to operate, and call libusb_open().
152 * -# Unref all devices in the discovered device list.
153 * -# Free the discovered device list.
155 * The order is important - you must not unreference the device before
156 * attempting to open it, because unreferencing it may destroy the device.
158 * For convenience, the libusb_free_device_list() function includes a
159 * parameter to optionally unreference all the devices in the list before
160 * freeing the list itself. This combines steps 3 and 4 above.
162 * As an implementation detail, libusb_open() actually adds a reference to
163 * the device in question. This is because the device is available later
164 * through libusb_get_device(). The reference is deleted during libusb_close().
168 * @defgroup misc Miscellaneous structures and constants
169 * This page documents structures and constants that don't belong anywhere
173 /* we traverse usbfs without knowing how many devices we are going to find.
174 * so we create this discovered_devs model which is similar to a linked-list
175 * which grows when required. it can be freed once discovery has completed,
176 * eliminating the need for a list node in the libusb_device structure
178 #define DISCOVERED_DEVICES_SIZE_STEP 8
180 static struct discovered_devs *discovered_devs_alloc(void)
182 struct discovered_devs *ret =
183 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
187 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
192 /* append a device to the discovered devices collection. may realloc itself,
193 * returning new discdevs. returns NULL on realloc failure. */
194 struct discovered_devs *discovered_devs_append(
195 struct discovered_devs *discdevs, struct libusb_device *dev)
197 size_t len = discdevs->len;
200 /* if there is space, just append the device */
201 if (len < discdevs->capacity) {
202 discdevs->devices[len] = libusb_device_ref(dev);
207 /* exceeded capacity, need to grow */
208 usbi_dbg("need to increase capacity");
209 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
210 discdevs = realloc(discdevs,
211 sizeof(*discdevs) + (sizeof(void *) * capacity));
213 discdevs->capacity = capacity;
214 discdevs->devices[len] = libusb_device_ref(dev);
221 static void discovered_devs_free(struct discovered_devs *discdevs)
225 for (i = 0; i < discdevs->len; i++)
226 libusb_device_unref(discdevs->devices[i]);
231 struct libusb_device *usbi_alloc_device(unsigned long session_id)
233 size_t priv_size = usbi_backend->device_priv_size;
234 struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
239 dev->session_data = session_id;
240 list_add(&dev->list, &usb_devs);
241 memset(&dev->os_priv, 0, priv_size);
245 struct libusb_device *usbi_get_device_by_session_id(unsigned long session_id)
247 struct libusb_device *dev;
249 list_for_each_entry(dev, &usb_devs, list)
250 if (dev->session_data == session_id)
257 * Returns a list of USB devices currently attached to the system. This is
258 * your entry point into finding a USB device to operate.
260 * You are expected to unreference all the devices when you are done with
261 * them, and then free the list with libusb_free_device_list(). Note that
262 * libusb_free_device_list() can unref all the devices for you. Be careful
263 * not to unreference a device you are about to open until after you have
266 * \param list output location for a list of devices. Must be later freed with
267 * libusb_free_device_list().
268 * \returns the number of devices in the outputted list, or negative on error
270 API_EXPORTED int libusb_get_device_list(struct libusb_device ***list)
272 struct discovered_devs *discdevs = discovered_devs_alloc();
273 struct libusb_device **ret;
282 r = usbi_backend->get_device_list(&discdevs);
286 /* convert discovered_devs into a list */
288 ret = malloc(sizeof(void *) * (len + 1));
295 for (i = 0; i < len; i++) {
296 struct libusb_device *dev = discdevs->devices[i];
297 ret[i] = libusb_device_ref(dev);
302 discovered_devs_free(discdevs);
307 * Frees a list of devices previously discovered using
308 * libusb_get_device_list(). If the unref_devices parameter is set, the
309 * reference count of each device in the list is decremented by 1.
310 * \param list the list to free
311 * \param unref_devices whether to unref the devices in the list
313 API_EXPORTED void libusb_free_device_list(struct libusb_device **list,
321 struct libusb_device *dev;
323 while ((dev = list[i++]) != NULL)
324 libusb_device_unref(dev);
330 * Increment the reference count of a device.
331 * \param dev the device to reference
332 * \returns the same device
334 API_EXPORTED struct libusb_device *libusb_device_ref(struct libusb_device *dev)
341 * Decrement the reference count of a device. If the decrement operation
342 * causes the reference count to reach zero, the device shall be destroyed.
343 * \param dev the device to unreference
345 API_EXPORTED void libusb_device_unref(struct libusb_device *dev)
350 if (--dev->refcnt == 0) {
351 usbi_dbg("destroy device %04x:%04x", dev->desc.idVendor,
352 dev->desc.idProduct);
354 if (usbi_backend->destroy_device)
355 usbi_backend->destroy_device(dev);
357 list_del(&dev->list);
365 * Open a device and obtain a device handle. A handle allows you to perform
366 * I/O on the device in question.
368 * Internally, this function adds a reference to the device and makes it
369 * available to you through libusb_get_device(). This reference is removed
370 * during libusb_close().
372 * \param dev the device to open
373 * \returns a handle for the device, or NULL on error
375 API_EXPORTED struct libusb_device_handle *libusb_open(struct libusb_device *dev)
377 struct libusb_device_handle *handle;
378 size_t priv_size = usbi_backend->device_handle_priv_size;
380 usbi_dbg("open %04x:%04x", dev->desc.idVendor, dev->desc.idProduct);
382 handle = malloc(sizeof(*handle) + priv_size);
386 handle->dev = libusb_device_ref(dev);
387 memset(&handle->os_priv, 0, priv_size);
388 r = usbi_backend->open(handle);
390 libusb_device_unref(dev);
395 list_add(&handle->list, &usbi_open_devs);
400 * Convenience function for finding a device with a particular
401 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
402 * for those scenarios where you are using libusb to knock up a quick test
403 * application - it allows you to avoid calling libusb_get_device_list() and
404 * worrying about traversing/freeing the list.
406 * This function has limitations and is hence not intended for use in real
407 * applications: if multiple devices have the same IDs it will only
408 * give you the first one, etc.
410 * \param vendor_id the idVendor value to search for
411 * \param product_id the idProduct value to search for
412 * \returns a handle for the first found device, or NULL on error or if the
413 * device could not be found. */
414 API_EXPORTED struct libusb_device_handle *libusb_open_device_with_vid_pid(
415 uint16_t vendor_id, uint16_t product_id)
417 struct libusb_device **devs;
418 struct libusb_device *found = NULL;
419 struct libusb_device *dev;
420 struct libusb_device_handle *handle = NULL;
423 if (libusb_get_device_list(&devs) < 0)
426 while ((dev = devs[i++]) != NULL) {
427 const struct libusb_device_descriptor *desc =
428 libusb_get_device_descriptor(dev);
429 if (desc->idVendor == vendor_id && desc->idProduct == product_id) {
436 handle = libusb_open(found);
438 libusb_free_device_list(devs, 1);
442 static void do_close(struct libusb_device_handle *dev_handle)
444 usbi_backend->close(dev_handle);
445 libusb_device_unref(dev_handle->dev);
449 * Close a device handle. Should be called on all open handles before your
452 * Internally, this function destroys the reference that was added by
453 * libusb_open() on the given device.
455 * \param dev_handle the handle to close
457 API_EXPORTED void libusb_close(struct libusb_device_handle *dev_handle)
463 list_del(&dev_handle->list);
464 do_close(dev_handle);
469 * Get the underlying device for a handle. This function does not modify
470 * the reference count of the returned device, so do not feel compelled to
471 * unreference it when you are done.
472 * \param dev_handle a device handle
473 * \returns the underlying device
475 API_EXPORTED struct libusb_device *libusb_get_device(
476 struct libusb_device_handle *dev_handle)
478 return dev_handle->dev;
481 /* FIXME: what about claiming multiple interfaces? */
483 * Claim an interface on a given device handle. You must claim the interface
484 * you wish to use before you can perform I/O on any of the endpoints.
485 * \param iface the <tt>bInterfaceNumber</tt> of the interface you wish to claim
486 * \param dev a device handle
487 * \returns 0 on success, non-zero on error
489 API_EXPORTED int libusb_claim_interface(struct libusb_device_handle *dev,
492 usbi_dbg("interface %d", iface);
493 return usbi_backend->claim_interface(dev, iface);
497 * Release an interface previously claimed with libusb_claim_interface(). You
498 * should release all claimed interfaces before closing a device handle.
499 * \param dev a device handle
500 * \param iface the <tt>bInterfaceNumber</tt> of the previously-claimed
502 * \returns 0 on success, non-zero on error
504 API_EXPORTED int libusb_release_interface(struct libusb_device_handle *dev,
507 usbi_dbg("interface %d", iface);
508 return usbi_backend->release_interface(dev, iface);
512 API_EXPORTED int libusb_set_interface_altsetting(
513 struct libusb_device_handle *dev, int iface, int altsetting)
515 usbi_dbg("interface %d altsetting %d", iface, altsetting);
516 return usbi_backend->set_interface_altsetting(dev, iface, altsetting);
520 * Initialize libusb. This function must be called before calling any other
522 * \returns 0 on success, non-zero on error
524 API_EXPORTED int libusb_init(void)
528 if (usbi_backend->init) {
529 int r = usbi_backend->init();
534 list_init(&usb_devs);
535 list_init(&usbi_open_devs);
541 * Deinitialize libusb. Should be called after closing all open devices and
542 * before your application terminates.
544 API_EXPORTED void libusb_exit(void)
546 struct libusb_device_handle *devh;
548 if (!list_empty(&usbi_open_devs)) {
549 usbi_dbg("naughty app left some devices open!\n");
550 list_for_each_entry(devh, &usbi_open_devs, list)
552 /* FIXME where do the open handles get freed? */
554 if (usbi_backend->exit)
555 usbi_backend->exit();
558 void usbi_log(enum usbi_log_level level, const char *function,
559 const char *format, ...)
562 FILE *stream = stdout;
569 case LOG_LEVEL_WARNING:
573 case LOG_LEVEL_ERROR:
577 case LOG_LEVEL_DEBUG:
587 fprintf(stream, "libusb:%s [%s] ", prefix, function);
589 va_start (args, format);
590 vfprintf(stream, format, args);
593 fprintf(stream, "\n");