Tests: Add libusbx stress test
[libusbx.git] / libusb / core.c
blob07b0b04e0a4c190812fdf1f294827b440e4f7e82
1 /*
2 * Core functions for libusbx
3 * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
4 * Copyright © 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
21 #include <config.h>
23 #include <errno.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/types.h>
30 #ifdef HAVE_SYS_TIME_H
31 #include <sys/time.h>
32 #endif
34 #include "libusbi.h"
36 #if defined(OS_LINUX)
37 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
38 #elif defined(OS_DARWIN)
39 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
40 #elif defined(OS_OPENBSD)
41 const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
42 #elif defined(OS_WINDOWS)
43 const struct usbi_os_backend * const usbi_backend = &windows_backend;
44 #else
45 #error "Unsupported OS"
46 #endif
48 struct libusb_context *usbi_default_context = NULL;
49 const struct libusb_version libusb_version_internal =
50 { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
51 LIBUSB_RC, "http://libusbx.org" };
52 static int default_context_refcnt = 0;
53 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
54 static struct timeval timestamp_origin = { 0, 0 };
56 /**
57 * \mainpage libusbx-1.0 API Reference
59 * \section intro Introduction
61 * libusbx is an open source library that allows you to communicate with USB
62 * devices from userspace. For more info, see the
63 * <a href="http://libusbx.org">libusbx homepage</a>.
65 * This documentation is aimed at application developers wishing to
66 * communicate with USB peripherals from their own software. After reviewing
67 * this documentation, feedback and questions can be sent to the
68 * <a href="http://mailing-list.libusbx.org">libusbx-devel mailing list</a>.
70 * This documentation assumes knowledge of how to operate USB devices from
71 * a software standpoint (descriptors, configurations, interfaces, endpoints,
72 * control/bulk/interrupt/isochronous transfers, etc). Full information
73 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
74 * Specification</a> which is available for free download. You can probably
75 * find less verbose introductions by searching the web.
77 * \section features Library features
79 * - All transfer types supported (control/bulk/interrupt/isochronous)
80 * - 2 transfer interfaces:
81 * -# Synchronous (simple)
82 * -# Asynchronous (more complicated, but more powerful)
83 * - Thread safe (although the asynchronous interface means that you
84 * usually won't need to thread)
85 * - Lightweight with lean API
86 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
88 * \section gettingstarted Getting Started
90 * To begin reading the API documentation, start with the Modules page which
91 * links to the different categories of libusbx's functionality.
93 * One decision you will have to make is whether to use the synchronous
94 * or the asynchronous data transfer interface. The \ref io documentation
95 * provides some insight into this topic.
97 * Some example programs can be found in the libusbx source distribution under
98 * the "examples" subdirectory. The libusbx homepage includes a list of
99 * real-life project examples which use libusbx.
101 * \section errorhandling Error handling
103 * libusbx functions typically return 0 on success or a negative error code
104 * on failure. These negative error codes relate to LIBUSB_ERROR constants
105 * which are listed on the \ref misc "miscellaneous" documentation page.
107 * \section msglog Debug message logging
109 * libusbx uses stderr for all logging. By default, logging is set to NONE,
110 * which means that no output will be produced. However, unless the library
111 * has been compiled with logging disabled, then any application calls to
112 * libusb_set_debug(), or the setting of the environmental variable
113 * LIBUSB_DEBUG outside of the application, can result in logging being
114 * produced. Your application should therefore not close stderr, but instead
115 * direct it to the null device if its output is undesireable.
117 * The libusb_set_debug() function can be used to enable logging of certain
118 * messages. Under standard configuration, libusbx doesn't really log much
119 * so you are advised to use this function to enable all error/warning/
120 * informational messages. It will help debug problems with your software.
122 * The logged messages are unstructured. There is no one-to-one correspondence
123 * between messages being logged and success or failure return codes from
124 * libusbx functions. There is no format to the messages, so you should not
125 * try to capture or parse them. They are not and will not be localized.
126 * These messages are not intended to being passed to your application user;
127 * instead, you should interpret the error codes returned from libusbx functions
128 * and provide appropriate notification to the user. The messages are simply
129 * there to aid you as a programmer, and if you're confused because you're
130 * getting a strange error code from a libusbx function, enabling message
131 * logging may give you a suitable explanation.
133 * The LIBUSB_DEBUG environment variable can be used to enable message logging
134 * at run-time. This environment variable should be set to a log level number,
135 * which is interpreted the same as the libusb_set_debug() parameter. When this
136 * environment variable is set, the message logging verbosity level is fixed
137 * and libusb_set_debug() effectively does nothing.
139 * libusbx can be compiled without any logging functions, useful for embedded
140 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
141 * variable have no effects.
143 * libusbx can also be compiled with verbose debugging messages always. When
144 * the library is compiled in this way, all messages of all verbosities are
145 * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
146 * have no effects.
148 * \section remarks Other remarks
150 * libusbx does have imperfections. The \ref caveats "caveats" page attempts
151 * to document these.
155 * \page caveats Caveats
157 * \section devresets Device resets
159 * The libusb_reset_device() function allows you to reset a device. If your
160 * program has to call such a function, it should obviously be aware that
161 * the reset will cause device state to change (e.g. register values may be
162 * reset).
164 * The problem is that any other program could reset the device your program
165 * is working with, at any time. libusbx does not offer a mechanism to inform
166 * you when this has happened, so if someone else resets your device it will
167 * not be clear to your own program why the device state has changed.
169 * Ultimately, this is a limitation of writing drivers in userspace.
170 * Separation from the USB stack in the underlying kernel makes it difficult
171 * for the operating system to deliver such notifications to your program.
172 * The Linux kernel USB stack allows such reset notifications to be delivered
173 * to in-kernel USB drivers, but it is not clear how such notifications could
174 * be delivered to second-class drivers that live in userspace.
176 * \section blockonly Blocking-only functionality
178 * The functionality listed below is only available through synchronous,
179 * blocking functions. There are no asynchronous/non-blocking alternatives,
180 * and no clear ways of implementing these.
182 * - Configuration activation (libusb_set_configuration())
183 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
184 * - Releasing of interfaces (libusb_release_interface())
185 * - Clearing of halt/stall condition (libusb_clear_halt())
186 * - Device resets (libusb_reset_device())
188 * \section nohotplug No hotplugging
190 * libusbx-1.0 lacks functionality for providing notifications of when devices
191 * are added or removed. This functionality is planned to be implemented
192 * in a later version of libusbx.
194 * That said, there is basic disconnection handling for open device handles:
195 * - If there are ongoing transfers, libusbx's handle_events loop will detect
196 * disconnections and complete ongoing transfers with the
197 * LIBUSB_TRANSFER_NO_DEVICE status code.
198 * - Many functions such as libusb_set_configuration() return the special
199 * LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected.
201 * \section configsel Configuration selection and handling
203 * When libusbx presents a device handle to an application, there is a chance
204 * that the corresponding device may be in unconfigured state. For devices
205 * with multiple configurations, there is also a chance that the configuration
206 * currently selected is not the one that the application wants to use.
208 * The obvious solution is to add a call to libusb_set_configuration() early
209 * on during your device initialization routines, but there are caveats to
210 * be aware of:
211 * -# If the device is already in the desired configuration, calling
212 * libusb_set_configuration() using the same configuration value will cause
213 * a lightweight device reset. This may not be desirable behaviour.
214 * -# libusbx will be unable to change configuration if the device is in
215 * another configuration and other programs or drivers have claimed
216 * interfaces under that configuration.
217 * -# In the case where the desired configuration is already active, libusbx
218 * may not even be able to perform a lightweight device reset. For example,
219 * take my USB keyboard with fingerprint reader: I'm interested in driving
220 * the fingerprint reader interface through libusbx, but the kernel's
221 * USB-HID driver will almost always have claimed the keyboard interface.
222 * Because the kernel has claimed an interface, it is not even possible to
223 * perform the lightweight device reset, so libusb_set_configuration() will
224 * fail. (Luckily the device in question only has a single configuration.)
226 * One solution to some of the above problems is to consider the currently
227 * active configuration. If the configuration we want is already active, then
228 * we don't have to select any configuration:
229 \code
230 cfg = libusb_get_configuration(dev);
231 if (cfg != desired)
232 libusb_set_configuration(dev, desired);
233 \endcode
235 * This is probably suitable for most scenarios, but is inherently racy:
236 * another application or driver may change the selected configuration
237 * <em>after</em> the libusb_get_configuration() call.
239 * Even in cases where libusb_set_configuration() succeeds, consider that other
240 * applications or drivers may change configuration after your application
241 * calls libusb_set_configuration().
243 * One possible way to lock your device into a specific configuration is as
244 * follows:
245 * -# Set the desired configuration (or use the logic above to realise that
246 * it is already in the desired configuration)
247 * -# Claim the interface that you wish to use
248 * -# Check that the currently active configuration is the one that you want
249 * to use.
251 * The above method works because once an interface is claimed, no application
252 * or driver is able to select another configuration.
254 * \section earlycomp Early transfer completion
256 * NOTE: This section is currently Linux-centric. I am not sure if any of these
257 * considerations apply to Darwin or other platforms.
259 * When a transfer completes early (i.e. when less data is received/sent in
260 * any one packet than the transfer buffer allows for) then libusbx is designed
261 * to terminate the transfer immediately, not transferring or receiving any
262 * more data unless other transfers have been queued by the user.
264 * On legacy platforms, libusbx is unable to do this in all situations. After
265 * the incomplete packet occurs, "surplus" data may be transferred. For recent
266 * versions of libusbx, this information is kept (the data length of the
267 * transfer is updated) and, for device-to-host transfers, any surplus data was
268 * added to the buffer. Still, this is not a nice solution because it loses the
269 * information about the end of the short packet, and the user probably wanted
270 * that surplus data to arrive in the next logical transfer.
273 * \section zlp Zero length packets
275 * - libusbx is able to send a packet of zero length to an endpoint simply by
276 * submitting a transfer of zero length.
277 * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
278 * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
282 * \page contexts Contexts
284 * It is possible that libusbx may be used simultaneously from two independent
285 * libraries linked into the same executable. For example, if your application
286 * has a plugin-like system which allows the user to dynamically load a range
287 * of modules into your program, it is feasible that two independently
288 * developed modules may both use libusbx.
290 * libusbx is written to allow for these multiple user scenarios. The two
291 * "instances" of libusbx will not interfere: libusb_set_debug() calls
292 * from one user will not affect the same settings for other users, other
293 * users can continue using libusbx after one of them calls libusb_exit(), etc.
295 * This is made possible through libusbx's <em>context</em> concept. When you
296 * call libusb_init(), you are (optionally) given a context. You can then pass
297 * this context pointer back into future libusbx functions.
299 * In order to keep things simple for more simplistic applications, it is
300 * legal to pass NULL to all functions requiring a context pointer (as long as
301 * you're sure no other code will attempt to use libusbx from the same process).
302 * When you pass NULL, the default context will be used. The default context
303 * is created the first time a process calls libusb_init() when no other
304 * context is alive. Contexts are destroyed during libusb_exit().
306 * The default context is reference-counted and can be shared. That means that
307 * if libusb_init(NULL) is called twice within the same process, the two
308 * users end up sharing the same context. The deinitialization and freeing of
309 * the default context will only happen when the last user calls libusb_exit().
310 * In other words, the default context is created and initialized when its
311 * reference count goes from 0 to 1, and is deinitialized and destroyed when
312 * its reference count goes from 1 to 0.
314 * You may be wondering why only a subset of libusbx functions require a
315 * context pointer in their function definition. Internally, libusbx stores
316 * context pointers in other objects (e.g. libusb_device instances) and hence
317 * can infer the context from those objects.
321 * @defgroup lib Library initialization/deinitialization
322 * This page details how to initialize and deinitialize libusbx. Initialization
323 * must be performed before using any libusbx functionality, and similarly you
324 * must not call any libusbx functions after deinitialization.
328 * @defgroup dev Device handling and enumeration
329 * The functionality documented below is designed to help with the following
330 * operations:
331 * - Enumerating the USB devices currently attached to the system
332 * - Choosing a device to operate from your software
333 * - Opening and closing the chosen device
335 * \section nutshell In a nutshell...
337 * The description below really makes things sound more complicated than they
338 * actually are. The following sequence of function calls will be suitable
339 * for almost all scenarios and does not require you to have such a deep
340 * understanding of the resource management issues:
341 * \code
342 // discover devices
343 libusb_device **list;
344 libusb_device *found = NULL;
345 ssize_t cnt = libusb_get_device_list(NULL, &list);
346 ssize_t i = 0;
347 int err = 0;
348 if (cnt < 0)
349 error();
351 for (i = 0; i < cnt; i++) {
352 libusb_device *device = list[i];
353 if (is_interesting(device)) {
354 found = device;
355 break;
359 if (found) {
360 libusb_device_handle *handle;
362 err = libusb_open(found, &handle);
363 if (err)
364 error();
365 // etc
368 libusb_free_device_list(list, 1);
369 \endcode
371 * The two important points:
372 * - You asked libusb_free_device_list() to unreference the devices (2nd
373 * parameter)
374 * - You opened the device before freeing the list and unreferencing the
375 * devices
377 * If you ended up with a handle, you can now proceed to perform I/O on the
378 * device.
380 * \section devshandles Devices and device handles
381 * libusbx has a concept of a USB device, represented by the
382 * \ref libusb_device opaque type. A device represents a USB device that
383 * is currently or was previously connected to the system. Using a reference
384 * to a device, you can determine certain information about the device (e.g.
385 * you can read the descriptor data).
387 * The libusb_get_device_list() function can be used to obtain a list of
388 * devices currently connected to the system. This is known as device
389 * discovery.
391 * Just because you have a reference to a device does not mean it is
392 * necessarily usable. The device may have been unplugged, you may not have
393 * permission to operate such device, or another program or driver may be
394 * using the device.
396 * When you've found a device that you'd like to operate, you must ask
397 * libusbx to open the device using the libusb_open() function. Assuming
398 * success, libusbx then returns you a <em>device handle</em>
399 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
400 * operate on the handle rather than the original device pointer.
402 * \section devref Device discovery and reference counting
404 * Device discovery (i.e. calling libusb_get_device_list()) returns a
405 * freshly-allocated list of devices. The list itself must be freed when
406 * you are done with it. libusbx also needs to know when it is OK to free
407 * the contents of the list - the devices themselves.
409 * To handle these issues, libusbx provides you with two separate items:
410 * - A function to free the list itself
411 * - A reference counting system for the devices inside
413 * New devices presented by the libusb_get_device_list() function all have a
414 * reference count of 1. You can increase and decrease reference count using
415 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
416 * its reference count reaches 0.
418 * With the above information in mind, the process of opening a device can
419 * be viewed as follows:
420 * -# Discover devices using libusb_get_device_list().
421 * -# Choose the device that you want to operate, and call libusb_open().
422 * -# Unref all devices in the discovered device list.
423 * -# Free the discovered device list.
425 * The order is important - you must not unreference the device before
426 * attempting to open it, because unreferencing it may destroy the device.
428 * For convenience, the libusb_free_device_list() function includes a
429 * parameter to optionally unreference all the devices in the list before
430 * freeing the list itself. This combines steps 3 and 4 above.
432 * As an implementation detail, libusb_open() actually adds a reference to
433 * the device in question. This is because the device remains available
434 * through the handle via libusb_get_device(). The reference is deleted during
435 * libusb_close().
438 /** @defgroup misc Miscellaneous */
440 /* we traverse usbfs without knowing how many devices we are going to find.
441 * so we create this discovered_devs model which is similar to a linked-list
442 * which grows when required. it can be freed once discovery has completed,
443 * eliminating the need for a list node in the libusb_device structure
444 * itself. */
445 #define DISCOVERED_DEVICES_SIZE_STEP 8
447 static struct discovered_devs *discovered_devs_alloc(void)
449 struct discovered_devs *ret =
450 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
452 if (ret) {
453 ret->len = 0;
454 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
456 return ret;
459 /* append a device to the discovered devices collection. may realloc itself,
460 * returning new discdevs. returns NULL on realloc failure. */
461 struct discovered_devs *discovered_devs_append(
462 struct discovered_devs *discdevs, struct libusb_device *dev)
464 size_t len = discdevs->len;
465 size_t capacity;
467 /* if there is space, just append the device */
468 if (len < discdevs->capacity) {
469 discdevs->devices[len] = libusb_ref_device(dev);
470 discdevs->len++;
471 return discdevs;
474 /* exceeded capacity, need to grow */
475 usbi_dbg("need to increase capacity");
476 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
477 discdevs = usbi_reallocf(discdevs,
478 sizeof(*discdevs) + (sizeof(void *) * capacity));
479 if (discdevs) {
480 discdevs->capacity = capacity;
481 discdevs->devices[len] = libusb_ref_device(dev);
482 discdevs->len++;
485 return discdevs;
488 static void discovered_devs_free(struct discovered_devs *discdevs)
490 size_t i;
492 for (i = 0; i < discdevs->len; i++)
493 libusb_unref_device(discdevs->devices[i]);
495 free(discdevs);
498 /* Allocate a new device with a specific session ID. The returned device has
499 * a reference count of 1. */
500 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
501 unsigned long session_id)
503 size_t priv_size = usbi_backend->device_priv_size;
504 struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
505 int r;
507 if (!dev)
508 return NULL;
510 r = usbi_mutex_init(&dev->lock, NULL);
511 if (r) {
512 free(dev);
513 return NULL;
516 dev->ctx = ctx;
517 dev->refcnt = 1;
518 dev->session_data = session_id;
519 dev->speed = LIBUSB_SPEED_UNKNOWN;
520 memset(&dev->os_priv, 0, priv_size);
522 usbi_mutex_lock(&ctx->usb_devs_lock);
523 list_add(&dev->list, &ctx->usb_devs);
524 usbi_mutex_unlock(&ctx->usb_devs_lock);
525 return dev;
528 /* Perform some final sanity checks on a newly discovered device. If this
529 * function fails (negative return code), the device should not be added
530 * to the discovered device list. */
531 int usbi_sanitize_device(struct libusb_device *dev)
533 int r;
534 unsigned char raw_desc[DEVICE_DESC_LENGTH];
535 uint8_t num_configurations;
536 int host_endian;
538 r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
539 if (r < 0)
540 return r;
542 num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
543 if (num_configurations > USB_MAXCONFIG) {
544 usbi_err(DEVICE_CTX(dev), "too many configurations");
545 return LIBUSB_ERROR_IO;
546 } else if (0 == num_configurations)
547 usbi_dbg("zero configurations, maybe an unauthorized device");
549 dev->num_configurations = num_configurations;
550 return 0;
553 /* Examine libusbx's internal list of known devices, looking for one with
554 * a specific session ID. Returns the matching device if it was found, and
555 * NULL otherwise. */
556 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
557 unsigned long session_id)
559 struct libusb_device *dev;
560 struct libusb_device *ret = NULL;
562 usbi_mutex_lock(&ctx->usb_devs_lock);
563 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
564 if (dev->session_data == session_id) {
565 ret = dev;
566 break;
568 usbi_mutex_unlock(&ctx->usb_devs_lock);
570 return ret;
573 /** @ingroup dev
574 * Returns a list of USB devices currently attached to the system. This is
575 * your entry point into finding a USB device to operate.
577 * You are expected to unreference all the devices when you are done with
578 * them, and then free the list with libusb_free_device_list(). Note that
579 * libusb_free_device_list() can unref all the devices for you. Be careful
580 * not to unreference a device you are about to open until after you have
581 * opened it.
583 * This return value of this function indicates the number of devices in
584 * the resultant list. The list is actually one element larger, as it is
585 * NULL-terminated.
587 * \param ctx the context to operate on, or NULL for the default context
588 * \param list output location for a list of devices. Must be later freed with
589 * libusb_free_device_list().
590 * \returns the number of devices in the outputted list, or any
591 * \ref libusb_error according to errors encountered by the backend.
593 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
594 libusb_device ***list)
596 struct discovered_devs *discdevs = discovered_devs_alloc();
597 struct libusb_device **ret;
598 int r = 0;
599 ssize_t i, len;
600 USBI_GET_CONTEXT(ctx);
601 usbi_dbg("");
603 if (!discdevs)
604 return LIBUSB_ERROR_NO_MEM;
606 r = usbi_backend->get_device_list(ctx, &discdevs);
607 if (r < 0) {
608 len = r;
609 goto out;
612 /* convert discovered_devs into a list */
613 len = discdevs->len;
614 ret = calloc(len + 1, sizeof(struct libusb_device *));
615 if (!ret) {
616 len = LIBUSB_ERROR_NO_MEM;
617 goto out;
620 ret[len] = NULL;
621 for (i = 0; i < len; i++) {
622 struct libusb_device *dev = discdevs->devices[i];
623 ret[i] = libusb_ref_device(dev);
625 *list = ret;
627 out:
628 discovered_devs_free(discdevs);
629 return len;
632 /** \ingroup dev
633 * Frees a list of devices previously discovered using
634 * libusb_get_device_list(). If the unref_devices parameter is set, the
635 * reference count of each device in the list is decremented by 1.
636 * \param list the list to free
637 * \param unref_devices whether to unref the devices in the list
639 void API_EXPORTED libusb_free_device_list(libusb_device **list,
640 int unref_devices)
642 if (!list)
643 return;
645 if (unref_devices) {
646 int i = 0;
647 struct libusb_device *dev;
649 while ((dev = list[i++]) != NULL)
650 libusb_unref_device(dev);
652 free(list);
655 /** \ingroup dev
656 * Get the number of the bus that a device is connected to.
657 * \param dev a device
658 * \returns the bus number
660 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
662 return dev->bus_number;
665 /** \ingroup dev
666 * Get the number of the port that a device is connected to
667 * \param dev a device
668 * \returns the port number (0 if not available)
670 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
672 return dev->port_number;
675 /** \ingroup dev
676 * Get the list of all port numbers from root for the specified device
677 * \param ctx the context to operate on, or NULL for the default context
678 * \param dev a device
679 * \param path the array that should contain the port numbers
680 * \param path_len the maximum length of the array. As per the USB 3.0
681 * specs, the current maximum limit for the depth is 7.
682 * \returns the number of elements filled
683 * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
685 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t* path, uint8_t path_len)
687 int i = path_len;
688 ssize_t r;
689 struct libusb_device **devs = NULL;
691 /* The device needs to be open, else the parents may have been destroyed */
692 r = libusb_get_device_list(ctx, &devs);
693 if (r < 0)
694 return (int)r;
696 while(dev) {
697 // HCDs can be listed as devices and would have port #0
698 // TODO: see how the other backends want to implement HCDs as parents
699 if (dev->port_number == 0)
700 break;
701 i--;
702 if (i < 0) {
703 libusb_free_device_list(devs, 1);
704 return LIBUSB_ERROR_OVERFLOW;
706 path[i] = dev->port_number;
707 dev = dev->parent_dev;
709 libusb_free_device_list(devs, 1);
710 memmove(path, &path[i], path_len-i);
711 return path_len-i;
714 /** \ingroup dev
715 * Get the the parent from the specified device [EXPERIMENTAL]
716 * \param dev a device
717 * \returns the device parent or NULL if not available
718 * You should issue a libusb_get_device_list() before calling this
719 * function and make sure that you only access the parent before issuing
720 * libusb_free_device_list(). The reason is that libusbx currently does
721 * not maintain a permanent list of device instances, and therefore can
722 * only guarantee that parents are fully instantiated within a
723 * libusb_get_device_list() - libusb_free_device_list() block.
725 DEFAULT_VISIBILITY
726 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
728 return dev->parent_dev;
731 /** \ingroup dev
732 * Get the address of the device on the bus it is connected to.
733 * \param dev a device
734 * \returns the device address
736 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
738 return dev->device_address;
741 /** \ingroup dev
742 * Get the negotiated connection speed for a device.
743 * \param dev a device
744 * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
745 * the OS doesn't know or doesn't support returning the negotiated speed.
747 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
749 return dev->speed;
752 static const struct libusb_endpoint_descriptor *find_endpoint(
753 struct libusb_config_descriptor *config, unsigned char endpoint)
755 int iface_idx;
756 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
757 const struct libusb_interface *iface = &config->interface[iface_idx];
758 int altsetting_idx;
760 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
761 altsetting_idx++) {
762 const struct libusb_interface_descriptor *altsetting
763 = &iface->altsetting[altsetting_idx];
764 int ep_idx;
766 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
767 const struct libusb_endpoint_descriptor *ep =
768 &altsetting->endpoint[ep_idx];
769 if (ep->bEndpointAddress == endpoint)
770 return ep;
774 return NULL;
777 /** \ingroup dev
778 * Convenience function to retrieve the wMaxPacketSize value for a particular
779 * endpoint in the active device configuration.
781 * This function was originally intended to be of assistance when setting up
782 * isochronous transfers, but a design mistake resulted in this function
783 * instead. It simply returns the wMaxPacketSize value without considering
784 * its contents. If you're dealing with isochronous transfers, you probably
785 * want libusb_get_max_iso_packet_size() instead.
787 * \param dev a device
788 * \param endpoint address of the endpoint in question
789 * \returns the wMaxPacketSize value
790 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
791 * \returns LIBUSB_ERROR_OTHER on other failure
793 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
794 unsigned char endpoint)
796 struct libusb_config_descriptor *config;
797 const struct libusb_endpoint_descriptor *ep;
798 int r;
800 r = libusb_get_active_config_descriptor(dev, &config);
801 if (r < 0) {
802 usbi_err(DEVICE_CTX(dev),
803 "could not retrieve active config descriptor");
804 return LIBUSB_ERROR_OTHER;
807 ep = find_endpoint(config, endpoint);
808 if (!ep)
809 return LIBUSB_ERROR_NOT_FOUND;
811 r = ep->wMaxPacketSize;
812 libusb_free_config_descriptor(config);
813 return r;
816 /** \ingroup dev
817 * Calculate the maximum packet size which a specific endpoint is capable is
818 * sending or receiving in the duration of 1 microframe
820 * Only the active configution is examined. The calculation is based on the
821 * wMaxPacketSize field in the endpoint descriptor as described in section
822 * 9.6.6 in the USB 2.0 specifications.
824 * If acting on an isochronous or interrupt endpoint, this function will
825 * multiply the value found in bits 0:10 by the number of transactions per
826 * microframe (determined by bits 11:12). Otherwise, this function just
827 * returns the numeric value found in bits 0:10.
829 * This function is useful for setting up isochronous transfers, for example
830 * you might pass the return value from this function to
831 * libusb_set_iso_packet_lengths() in order to set the length field of every
832 * isochronous packet in a transfer.
834 * Since v1.0.3.
836 * \param dev a device
837 * \param endpoint address of the endpoint in question
838 * \returns the maximum packet size which can be sent/received on this endpoint
839 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
840 * \returns LIBUSB_ERROR_OTHER on other failure
842 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
843 unsigned char endpoint)
845 struct libusb_config_descriptor *config;
846 const struct libusb_endpoint_descriptor *ep;
847 enum libusb_transfer_type ep_type;
848 uint16_t val;
849 int r;
851 r = libusb_get_active_config_descriptor(dev, &config);
852 if (r < 0) {
853 usbi_err(DEVICE_CTX(dev),
854 "could not retrieve active config descriptor");
855 return LIBUSB_ERROR_OTHER;
858 ep = find_endpoint(config, endpoint);
859 if (!ep)
860 return LIBUSB_ERROR_NOT_FOUND;
862 val = ep->wMaxPacketSize;
863 ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
864 libusb_free_config_descriptor(config);
866 r = val & 0x07ff;
867 if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
868 || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
869 r *= (1 + ((val >> 11) & 3));
870 return r;
873 /** \ingroup dev
874 * Increment the reference count of a device.
875 * \param dev the device to reference
876 * \returns the same device
878 DEFAULT_VISIBILITY
879 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
881 usbi_mutex_lock(&dev->lock);
882 dev->refcnt++;
883 usbi_mutex_unlock(&dev->lock);
884 return dev;
887 /** \ingroup dev
888 * Decrement the reference count of a device. If the decrement operation
889 * causes the reference count to reach zero, the device shall be destroyed.
890 * \param dev the device to unreference
892 void API_EXPORTED libusb_unref_device(libusb_device *dev)
894 int refcnt;
896 if (!dev)
897 return;
899 usbi_mutex_lock(&dev->lock);
900 refcnt = --dev->refcnt;
901 usbi_mutex_unlock(&dev->lock);
903 if (refcnt == 0) {
904 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
906 if (usbi_backend->destroy_device)
907 usbi_backend->destroy_device(dev);
909 usbi_mutex_lock(&dev->ctx->usb_devs_lock);
910 list_del(&dev->list);
911 usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
913 usbi_mutex_destroy(&dev->lock);
914 free(dev);
919 * Interrupt the iteration of the event handling thread, so that it picks
920 * up the new fd.
922 void usbi_fd_notification(struct libusb_context *ctx)
924 unsigned char dummy = 1;
925 ssize_t r;
927 if (ctx == NULL)
928 return;
930 /* record that we are messing with poll fds */
931 usbi_mutex_lock(&ctx->pollfd_modify_lock);
932 ctx->pollfd_modify++;
933 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
935 /* write some data on control pipe to interrupt event handlers */
936 r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
937 if (r <= 0) {
938 usbi_warn(ctx, "internal signalling write failed");
939 usbi_mutex_lock(&ctx->pollfd_modify_lock);
940 ctx->pollfd_modify--;
941 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
942 return;
945 /* take event handling lock */
946 libusb_lock_events(ctx);
948 /* read the dummy data */
949 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
950 if (r <= 0)
951 usbi_warn(ctx, "internal signalling read failed");
953 /* we're done with modifying poll fds */
954 usbi_mutex_lock(&ctx->pollfd_modify_lock);
955 ctx->pollfd_modify--;
956 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
958 /* Release event handling lock and wake up event waiters */
959 libusb_unlock_events(ctx);
962 /** \ingroup dev
963 * Open a device and obtain a device handle. A handle allows you to perform
964 * I/O on the device in question.
966 * Internally, this function adds a reference to the device and makes it
967 * available to you through libusb_get_device(). This reference is removed
968 * during libusb_close().
970 * This is a non-blocking function; no requests are sent over the bus.
972 * \param dev the device to open
973 * \param handle output location for the returned device handle pointer. Only
974 * populated when the return code is 0.
975 * \returns 0 on success
976 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
977 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
978 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
979 * \returns another LIBUSB_ERROR code on other failure
981 int API_EXPORTED libusb_open(libusb_device *dev,
982 libusb_device_handle **handle)
984 struct libusb_context *ctx = DEVICE_CTX(dev);
985 struct libusb_device_handle *_handle;
986 size_t priv_size = usbi_backend->device_handle_priv_size;
987 int r;
988 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
990 _handle = malloc(sizeof(*_handle) + priv_size);
991 if (!_handle)
992 return LIBUSB_ERROR_NO_MEM;
994 r = usbi_mutex_init(&_handle->lock, NULL);
995 if (r) {
996 free(_handle);
997 return LIBUSB_ERROR_OTHER;
1000 _handle->dev = libusb_ref_device(dev);
1001 _handle->claimed_interfaces = 0;
1002 memset(&_handle->os_priv, 0, priv_size);
1004 r = usbi_backend->open(_handle);
1005 if (r < 0) {
1006 usbi_dbg("could not open device: %s", libusb_error_name(r));
1007 libusb_unref_device(dev);
1008 usbi_mutex_destroy(&_handle->lock);
1009 free(_handle);
1010 return r;
1013 usbi_mutex_lock(&ctx->open_devs_lock);
1014 list_add(&_handle->list, &ctx->open_devs);
1015 usbi_mutex_unlock(&ctx->open_devs_lock);
1016 *handle = _handle;
1018 /* At this point, we want to interrupt any existing event handlers so
1019 * that they realise the addition of the new device's poll fd. One
1020 * example when this is desirable is if the user is running a separate
1021 * dedicated libusbx events handling thread, which is running with a long
1022 * or infinite timeout. We want to interrupt that iteration of the loop,
1023 * so that it picks up the new fd, and then continues. */
1024 usbi_fd_notification(ctx);
1026 return 0;
1029 /** \ingroup dev
1030 * Convenience function for finding a device with a particular
1031 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1032 * for those scenarios where you are using libusbx to knock up a quick test
1033 * application - it allows you to avoid calling libusb_get_device_list() and
1034 * worrying about traversing/freeing the list.
1036 * This function has limitations and is hence not intended for use in real
1037 * applications: if multiple devices have the same IDs it will only
1038 * give you the first one, etc.
1040 * \param ctx the context to operate on, or NULL for the default context
1041 * \param vendor_id the idVendor value to search for
1042 * \param product_id the idProduct value to search for
1043 * \returns a handle for the first found device, or NULL on error or if the
1044 * device could not be found. */
1045 DEFAULT_VISIBILITY
1046 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1047 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1049 struct libusb_device **devs;
1050 struct libusb_device *found = NULL;
1051 struct libusb_device *dev;
1052 struct libusb_device_handle *handle = NULL;
1053 size_t i = 0;
1054 int r;
1056 if (libusb_get_device_list(ctx, &devs) < 0)
1057 return NULL;
1059 while ((dev = devs[i++]) != NULL) {
1060 struct libusb_device_descriptor desc;
1061 r = libusb_get_device_descriptor(dev, &desc);
1062 if (r < 0)
1063 goto out;
1064 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1065 found = dev;
1066 break;
1070 if (found) {
1071 r = libusb_open(found, &handle);
1072 if (r < 0)
1073 handle = NULL;
1076 out:
1077 libusb_free_device_list(devs, 1);
1078 return handle;
1081 static void do_close(struct libusb_context *ctx,
1082 struct libusb_device_handle *dev_handle)
1084 struct usbi_transfer *itransfer;
1085 struct usbi_transfer *tmp;
1087 libusb_lock_events(ctx);
1089 /* remove any transfers in flight that are for this device */
1090 usbi_mutex_lock(&ctx->flying_transfers_lock);
1092 /* safe iteration because transfers may be being deleted */
1093 list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
1094 struct libusb_transfer *transfer =
1095 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1097 if (transfer->dev_handle != dev_handle)
1098 continue;
1100 if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1101 usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1103 if (itransfer->flags & USBI_TRANSFER_CANCELLING)
1104 usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1105 else
1106 usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1109 /* remove from the list of in-flight transfers and make sure
1110 * we don't accidentally use the device handle in the future
1111 * (or that such accesses will be easily caught and identified as a crash)
1113 usbi_mutex_lock(&itransfer->lock);
1114 list_del(&itransfer->list);
1115 transfer->dev_handle = NULL;
1116 usbi_mutex_unlock(&itransfer->lock);
1118 /* it is up to the user to free up the actual transfer struct. this is
1119 * just making sure that we don't attempt to process the transfer after
1120 * the device handle is invalid
1122 usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
1123 transfer, dev_handle);
1125 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1127 libusb_unlock_events(ctx);
1129 usbi_mutex_lock(&ctx->open_devs_lock);
1130 list_del(&dev_handle->list);
1131 usbi_mutex_unlock(&ctx->open_devs_lock);
1133 usbi_backend->close(dev_handle);
1134 libusb_unref_device(dev_handle->dev);
1135 usbi_mutex_destroy(&dev_handle->lock);
1136 free(dev_handle);
1139 /** \ingroup dev
1140 * Close a device handle. Should be called on all open handles before your
1141 * application exits.
1143 * Internally, this function destroys the reference that was added by
1144 * libusb_open() on the given device.
1146 * This is a non-blocking function; no requests are sent over the bus.
1148 * \param dev_handle the handle to close
1150 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1152 struct libusb_context *ctx;
1153 unsigned char dummy = 1;
1154 ssize_t r;
1156 if (!dev_handle)
1157 return;
1158 usbi_dbg("");
1160 ctx = HANDLE_CTX(dev_handle);
1162 /* Similarly to libusb_open(), we want to interrupt all event handlers
1163 * at this point. More importantly, we want to perform the actual close of
1164 * the device while holding the event handling lock (preventing any other
1165 * thread from doing event handling) because we will be removing a file
1166 * descriptor from the polling loop. */
1168 /* record that we are messing with poll fds */
1169 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1170 ctx->pollfd_modify++;
1171 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1173 /* write some data on control pipe to interrupt event handlers */
1174 r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1175 if (r <= 0) {
1176 usbi_warn(ctx, "internal signalling write failed, closing anyway");
1177 do_close(ctx, dev_handle);
1178 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1179 ctx->pollfd_modify--;
1180 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1181 return;
1184 /* take event handling lock */
1185 libusb_lock_events(ctx);
1187 /* read the dummy data */
1188 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1189 if (r <= 0)
1190 usbi_warn(ctx, "internal signalling read failed, closing anyway");
1192 /* Close the device */
1193 do_close(ctx, dev_handle);
1195 /* we're done with modifying poll fds */
1196 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1197 ctx->pollfd_modify--;
1198 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1200 /* Release event handling lock and wake up event waiters */
1201 libusb_unlock_events(ctx);
1204 /** \ingroup dev
1205 * Get the underlying device for a handle. This function does not modify
1206 * the reference count of the returned device, so do not feel compelled to
1207 * unreference it when you are done.
1208 * \param dev_handle a device handle
1209 * \returns the underlying device
1211 DEFAULT_VISIBILITY
1212 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1214 return dev_handle->dev;
1217 /** \ingroup dev
1218 * Determine the bConfigurationValue of the currently active configuration.
1220 * You could formulate your own control request to obtain this information,
1221 * but this function has the advantage that it may be able to retrieve the
1222 * information from operating system caches (no I/O involved).
1224 * If the OS does not cache this information, then this function will block
1225 * while a control transfer is submitted to retrieve the information.
1227 * This function will return a value of 0 in the <tt>config</tt> output
1228 * parameter if the device is in unconfigured state.
1230 * \param dev a device handle
1231 * \param config output location for the bConfigurationValue of the active
1232 * configuration (only valid for return code 0)
1233 * \returns 0 on success
1234 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1235 * \returns another LIBUSB_ERROR code on other failure
1237 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
1238 int *config)
1240 int r = LIBUSB_ERROR_NOT_SUPPORTED;
1242 usbi_dbg("");
1243 if (usbi_backend->get_configuration)
1244 r = usbi_backend->get_configuration(dev, config);
1246 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1247 uint8_t tmp = 0;
1248 usbi_dbg("falling back to control message");
1249 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1250 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1251 if (r == 0) {
1252 usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
1253 r = LIBUSB_ERROR_IO;
1254 } else if (r == 1) {
1255 r = 0;
1256 *config = tmp;
1257 } else {
1258 usbi_dbg("control failed, error %d", r);
1262 if (r == 0)
1263 usbi_dbg("active config %d", *config);
1265 return r;
1268 /** \ingroup dev
1269 * Set the active configuration for a device.
1271 * The operating system may or may not have already set an active
1272 * configuration on the device. It is up to your application to ensure the
1273 * correct configuration is selected before you attempt to claim interfaces
1274 * and perform other operations.
1276 * If you call this function on a device already configured with the selected
1277 * configuration, then this function will act as a lightweight device reset:
1278 * it will issue a SET_CONFIGURATION request using the current configuration,
1279 * causing most USB-related device state to be reset (altsetting reset to zero,
1280 * endpoint halts cleared, toggles reset).
1282 * You cannot change/reset configuration if your application has claimed
1283 * interfaces - you should free them with libusb_release_interface() first.
1284 * You cannot change/reset configuration if other applications or drivers have
1285 * claimed interfaces.
1287 * A configuration value of -1 will put the device in unconfigured state.
1288 * The USB specifications state that a configuration value of 0 does this,
1289 * however buggy devices exist which actually have a configuration 0.
1291 * You should always use this function rather than formulating your own
1292 * SET_CONFIGURATION control request. This is because the underlying operating
1293 * system needs to know when such changes happen.
1295 * This is a blocking function.
1297 * \param dev a device handle
1298 * \param configuration the bConfigurationValue of the configuration you
1299 * wish to activate, or -1 if you wish to put the device in unconfigured state
1300 * \returns 0 on success
1301 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1302 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1303 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1304 * \returns another LIBUSB_ERROR code on other failure
1306 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
1307 int configuration)
1309 usbi_dbg("configuration %d", configuration);
1310 return usbi_backend->set_configuration(dev, configuration);
1313 /** \ingroup dev
1314 * Claim an interface on a given device handle. You must claim the interface
1315 * you wish to use before you can perform I/O on any of its endpoints.
1317 * It is legal to attempt to claim an already-claimed interface, in which
1318 * case libusbx just returns 0 without doing anything.
1320 * Claiming of interfaces is a purely logical operation; it does not cause
1321 * any requests to be sent over the bus. Interface claiming is used to
1322 * instruct the underlying operating system that your application wishes
1323 * to take ownership of the interface.
1325 * This is a non-blocking function.
1327 * \param dev a device handle
1328 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1329 * wish to claim
1330 * \returns 0 on success
1331 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1332 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1333 * interface
1334 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1335 * \returns a LIBUSB_ERROR code on other failure
1337 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
1338 int interface_number)
1340 int r = 0;
1342 usbi_dbg("interface %d", interface_number);
1343 if (interface_number >= USB_MAXINTERFACES)
1344 return LIBUSB_ERROR_INVALID_PARAM;
1346 usbi_mutex_lock(&dev->lock);
1347 if (dev->claimed_interfaces & (1 << interface_number))
1348 goto out;
1350 r = usbi_backend->claim_interface(dev, interface_number);
1351 if (r == 0)
1352 dev->claimed_interfaces |= 1 << interface_number;
1354 out:
1355 usbi_mutex_unlock(&dev->lock);
1356 return r;
1359 /** \ingroup dev
1360 * Release an interface previously claimed with libusb_claim_interface(). You
1361 * should release all claimed interfaces before closing a device handle.
1363 * This is a blocking function. A SET_INTERFACE control request will be sent
1364 * to the device, resetting interface state to the first alternate setting.
1366 * \param dev a device handle
1367 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1368 * previously-claimed interface
1369 * \returns 0 on success
1370 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1371 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1372 * \returns another LIBUSB_ERROR code on other failure
1374 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
1375 int interface_number)
1377 int r;
1379 usbi_dbg("interface %d", interface_number);
1380 if (interface_number >= USB_MAXINTERFACES)
1381 return LIBUSB_ERROR_INVALID_PARAM;
1383 usbi_mutex_lock(&dev->lock);
1384 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1385 r = LIBUSB_ERROR_NOT_FOUND;
1386 goto out;
1389 r = usbi_backend->release_interface(dev, interface_number);
1390 if (r == 0)
1391 dev->claimed_interfaces &= ~(1 << interface_number);
1393 out:
1394 usbi_mutex_unlock(&dev->lock);
1395 return r;
1398 /** \ingroup dev
1399 * Activate an alternate setting for an interface. The interface must have
1400 * been previously claimed with libusb_claim_interface().
1402 * You should always use this function rather than formulating your own
1403 * SET_INTERFACE control request. This is because the underlying operating
1404 * system needs to know when such changes happen.
1406 * This is a blocking function.
1408 * \param dev a device handle
1409 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1410 * previously-claimed interface
1411 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1412 * setting to activate
1413 * \returns 0 on success
1414 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1415 * requested alternate setting does not exist
1416 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1417 * \returns another LIBUSB_ERROR code on other failure
1419 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
1420 int interface_number, int alternate_setting)
1422 usbi_dbg("interface %d altsetting %d",
1423 interface_number, alternate_setting);
1424 if (interface_number >= USB_MAXINTERFACES)
1425 return LIBUSB_ERROR_INVALID_PARAM;
1427 usbi_mutex_lock(&dev->lock);
1428 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1429 usbi_mutex_unlock(&dev->lock);
1430 return LIBUSB_ERROR_NOT_FOUND;
1432 usbi_mutex_unlock(&dev->lock);
1434 return usbi_backend->set_interface_altsetting(dev, interface_number,
1435 alternate_setting);
1438 /** \ingroup dev
1439 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1440 * are unable to receive or transmit data until the halt condition is stalled.
1442 * You should cancel all pending transfers before attempting to clear the halt
1443 * condition.
1445 * This is a blocking function.
1447 * \param dev a device handle
1448 * \param endpoint the endpoint to clear halt status
1449 * \returns 0 on success
1450 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1451 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1452 * \returns another LIBUSB_ERROR code on other failure
1454 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
1455 unsigned char endpoint)
1457 usbi_dbg("endpoint %x", endpoint);
1458 return usbi_backend->clear_halt(dev, endpoint);
1461 /** \ingroup dev
1462 * Perform a USB port reset to reinitialize a device. The system will attempt
1463 * to restore the previous configuration and alternate settings after the
1464 * reset has completed.
1466 * If the reset fails, the descriptors change, or the previous state cannot be
1467 * restored, the device will appear to be disconnected and reconnected. This
1468 * means that the device handle is no longer valid (you should close it) and
1469 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1470 * when this is the case.
1472 * This is a blocking function which usually incurs a noticeable delay.
1474 * \param dev a handle of the device to reset
1475 * \returns 0 on success
1476 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1477 * device has been disconnected
1478 * \returns another LIBUSB_ERROR code on other failure
1480 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
1482 usbi_dbg("");
1483 return usbi_backend->reset_device(dev);
1486 /** \ingroup dev
1487 * Determine if a kernel driver is active on an interface. If a kernel driver
1488 * is active, you cannot claim the interface, and libusbx will be unable to
1489 * perform I/O.
1491 * This functionality is not available on Windows.
1493 * \param dev a device handle
1494 * \param interface_number the interface to check
1495 * \returns 0 if no kernel driver is active
1496 * \returns 1 if a kernel driver is active
1497 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1498 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1499 * is not available
1500 * \returns another LIBUSB_ERROR code on other failure
1501 * \see libusb_detach_kernel_driver()
1503 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
1504 int interface_number)
1506 usbi_dbg("interface %d", interface_number);
1507 if (usbi_backend->kernel_driver_active)
1508 return usbi_backend->kernel_driver_active(dev, interface_number);
1509 else
1510 return LIBUSB_ERROR_NOT_SUPPORTED;
1513 /** \ingroup dev
1514 * Detach a kernel driver from an interface. If successful, you will then be
1515 * able to claim the interface and perform I/O.
1517 * This functionality is not available on Darwin or Windows.
1519 * Note that libusbx itself also talks to the device through a special kernel
1520 * driver, if this driver is already attached to the device, this call will
1521 * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1523 * \param dev a device handle
1524 * \param interface_number the interface to detach the driver from
1525 * \returns 0 on success
1526 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1527 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1528 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1529 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1530 * is not available
1531 * \returns another LIBUSB_ERROR code on other failure
1532 * \see libusb_kernel_driver_active()
1534 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
1535 int interface_number)
1537 usbi_dbg("interface %d", interface_number);
1538 if (usbi_backend->detach_kernel_driver)
1539 return usbi_backend->detach_kernel_driver(dev, interface_number);
1540 else
1541 return LIBUSB_ERROR_NOT_SUPPORTED;
1544 /** \ingroup dev
1545 * Re-attach an interface's kernel driver, which was previously detached
1546 * using libusb_detach_kernel_driver(). This call is only effective on
1547 * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1549 * This functionality is not available on Darwin or Windows.
1551 * \param dev a device handle
1552 * \param interface_number the interface to attach the driver from
1553 * \returns 0 on success
1554 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1555 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1556 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1557 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1558 * is not available
1559 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1560 * interface is claimed by a program or driver
1561 * \returns another LIBUSB_ERROR code on other failure
1562 * \see libusb_kernel_driver_active()
1564 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
1565 int interface_number)
1567 usbi_dbg("interface %d", interface_number);
1568 if (usbi_backend->attach_kernel_driver)
1569 return usbi_backend->attach_kernel_driver(dev, interface_number);
1570 else
1571 return LIBUSB_ERROR_NOT_SUPPORTED;
1574 /** \ingroup lib
1575 * Set log message verbosity.
1577 * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
1578 * printed. If you choose to increase the message verbosity level, ensure
1579 * that your application does not close the stdout/stderr file descriptors.
1581 * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusbx is conservative
1582 * with its message logging and most of the time, will only log messages that
1583 * explain error conditions and other oddities. This will help you debug
1584 * your software.
1586 * If the LIBUSB_DEBUG environment variable was set when libusbx was
1587 * initialized, this function does nothing: the message verbosity is fixed
1588 * to the value in the environment variable.
1590 * If libusbx was compiled without any message logging, this function does
1591 * nothing: you'll never get any messages.
1593 * If libusbx was compiled with verbose debug message logging, this function
1594 * does nothing: you'll always get messages from all levels.
1596 * \param ctx the context to operate on, or NULL for the default context
1597 * \param level debug level to set
1599 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
1601 USBI_GET_CONTEXT(ctx);
1602 if (!ctx->debug_fixed)
1603 ctx->debug = level;
1606 /** \ingroup lib
1607 * Initialize libusb. This function must be called before calling any other
1608 * libusbx function.
1610 * If you do not provide an output location for a context pointer, a default
1611 * context will be created. If there was already a default context, it will
1612 * be reused (and nothing will be initialized/reinitialized).
1614 * \param context Optional output location for context pointer.
1615 * Only valid on return code 0.
1616 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1617 * \see contexts
1619 int API_EXPORTED libusb_init(libusb_context **context)
1621 char *dbg;
1622 struct libusb_context *ctx;
1623 int r = 0;
1625 usbi_mutex_static_lock(&default_context_lock);
1627 if (!timestamp_origin.tv_sec) {
1628 usbi_gettimeofday(&timestamp_origin, NULL);
1631 if (!context && usbi_default_context) {
1632 usbi_dbg("reusing default context");
1633 default_context_refcnt++;
1634 usbi_mutex_static_unlock(&default_context_lock);
1635 return 0;
1638 ctx = calloc(1, sizeof(*ctx));
1639 if (!ctx) {
1640 r = LIBUSB_ERROR_NO_MEM;
1641 goto err_unlock;
1644 #ifdef ENABLE_DEBUG_LOGGING
1645 ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
1646 #endif
1648 dbg = getenv("LIBUSB_DEBUG");
1649 if (dbg) {
1650 ctx->debug = atoi(dbg);
1651 if (ctx->debug)
1652 ctx->debug_fixed = 1;
1655 /* default context should be initialized before calling usbi_dbg */
1656 if (!usbi_default_context) {
1657 usbi_default_context = ctx;
1658 usbi_dbg("created default context");
1661 usbi_dbg("libusbx v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
1662 libusb_version_internal.micro, libusb_version_internal.nano);
1664 if (usbi_backend->init) {
1665 r = usbi_backend->init(ctx);
1666 if (r)
1667 goto err_free_ctx;
1670 usbi_mutex_init(&ctx->usb_devs_lock, NULL);
1671 usbi_mutex_init(&ctx->open_devs_lock, NULL);
1672 list_init(&ctx->usb_devs);
1673 list_init(&ctx->open_devs);
1675 r = usbi_io_init(ctx);
1676 if (r < 0) {
1677 if (usbi_backend->exit)
1678 usbi_backend->exit();
1679 goto err_destroy_mutex;
1682 if (context) {
1683 *context = ctx;
1684 } else if (!usbi_default_context) {
1685 usbi_dbg("created default context");
1686 usbi_default_context = ctx;
1687 default_context_refcnt++;
1689 usbi_mutex_static_unlock(&default_context_lock);
1691 return 0;
1693 err_destroy_mutex:
1694 usbi_mutex_destroy(&ctx->open_devs_lock);
1695 usbi_mutex_destroy(&ctx->usb_devs_lock);
1696 err_free_ctx:
1697 free(ctx);
1698 err_unlock:
1699 usbi_mutex_static_unlock(&default_context_lock);
1700 return r;
1703 /** \ingroup lib
1704 * Deinitialize libusb. Should be called after closing all open devices and
1705 * before your application terminates.
1706 * \param ctx the context to deinitialize, or NULL for the default context
1708 void API_EXPORTED libusb_exit(struct libusb_context *ctx)
1710 usbi_dbg("");
1711 USBI_GET_CONTEXT(ctx);
1713 /* if working with default context, only actually do the deinitialization
1714 * if we're the last user */
1715 if (ctx == usbi_default_context) {
1716 usbi_mutex_static_lock(&default_context_lock);
1717 if (--default_context_refcnt > 0) {
1718 usbi_dbg("not destroying default context");
1719 usbi_mutex_static_unlock(&default_context_lock);
1720 return;
1722 usbi_dbg("destroying default context");
1723 usbi_default_context = NULL;
1724 usbi_mutex_static_unlock(&default_context_lock);
1727 /* a little sanity check. doesn't bother with open_devs locking because
1728 * unless there is an application bug, nobody will be accessing this. */
1729 if (!list_empty(&ctx->open_devs))
1730 usbi_warn(ctx, "application left some devices open");
1732 usbi_io_exit(ctx);
1733 if (usbi_backend->exit)
1734 usbi_backend->exit();
1736 usbi_mutex_destroy(&ctx->open_devs_lock);
1737 usbi_mutex_destroy(&ctx->usb_devs_lock);
1738 free(ctx);
1741 /** \ingroup misc
1742 * Check at runtime if the loaded library has a given capability.
1744 * \param capability the \ref libusb_capability to check for
1745 * \returns 1 if the running library has the capability, 0 otherwise
1747 int API_EXPORTED libusb_has_capability(uint32_t capability)
1749 switch (capability) {
1750 case LIBUSB_CAP_HAS_CAPABILITY:
1751 return 1;
1753 return 0;
1756 /* this is defined in libusbi.h if needed */
1757 #ifdef LIBUSB_GETTIMEOFDAY_WIN32
1759 * gettimeofday
1760 * Implementation according to:
1761 * The Open Group Base Specifications Issue 6
1762 * IEEE Std 1003.1, 2004 Edition
1766 * THIS SOFTWARE IS NOT COPYRIGHTED
1768 * This source code is offered for use in the public domain. You may
1769 * use, modify or distribute it freely.
1771 * This code is distributed in the hope that it will be useful but
1772 * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
1773 * DISCLAIMED. This includes but is not limited to warranties of
1774 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1776 * Contributed by:
1777 * Danny Smith <dannysmith@users.sourceforge.net>
1780 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
1781 #define _W32_FT_OFFSET (116444736000000000)
1783 int usbi_gettimeofday(struct timeval *tp, void *tzp)
1785 union {
1786 unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
1787 FILETIME ft;
1788 } _now;
1789 UNUSED(tzp);
1791 if(tp) {
1792 GetSystemTimeAsFileTime (&_now.ft);
1793 tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
1794 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
1796 /* Always return 0 as per Open Group Base Specifications Issue 6.
1797 Do not set errno on error. */
1798 return 0;
1800 #endif
1802 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
1803 const char *function, const char *format, va_list args)
1805 const char *prefix = "";
1806 struct timeval now;
1807 int global_debug;
1808 static int has_debug_header_been_displayed = 0;
1810 #ifdef ENABLE_DEBUG_LOGGING
1811 global_debug = 1;
1812 UNUSED(ctx);
1813 #else
1814 USBI_GET_CONTEXT(ctx);
1815 if (ctx == NULL)
1816 return;
1817 global_debug = (ctx->debug == LIBUSB_LOG_LEVEL_DEBUG);
1818 if (!ctx->debug)
1819 return;
1820 if (level == LIBUSB_LOG_LEVEL_WARNING && ctx->debug < LIBUSB_LOG_LEVEL_WARNING)
1821 return;
1822 if (level == LIBUSB_LOG_LEVEL_INFO && ctx->debug < LIBUSB_LOG_LEVEL_INFO)
1823 return;
1824 if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx->debug < LIBUSB_LOG_LEVEL_DEBUG)
1825 return;
1826 #endif
1828 usbi_gettimeofday(&now, NULL);
1829 if ((global_debug) && (!has_debug_header_been_displayed)) {
1830 has_debug_header_been_displayed = 1;
1831 fprintf(stderr, "[timestamp] [threadID] facility level [function call] <message>\n");
1832 fprintf(stderr, "--------------------------------------------------------------------------------\n");
1834 if (now.tv_usec < timestamp_origin.tv_usec) {
1835 now.tv_sec--;
1836 now.tv_usec += 1000000;
1838 now.tv_sec -= timestamp_origin.tv_sec;
1839 now.tv_usec -= timestamp_origin.tv_usec;
1841 switch (level) {
1842 case LIBUSB_LOG_LEVEL_INFO:
1843 prefix = "info";
1844 break;
1845 case LIBUSB_LOG_LEVEL_WARNING:
1846 prefix = "warning";
1847 break;
1848 case LIBUSB_LOG_LEVEL_ERROR:
1849 prefix = "error";
1850 break;
1851 case LIBUSB_LOG_LEVEL_DEBUG:
1852 prefix = "debug";
1853 break;
1854 case LIBUSB_LOG_LEVEL_NONE:
1855 break;
1856 default:
1857 prefix = "unknown";
1858 break;
1861 if (global_debug) {
1862 fprintf(stderr, "[%2d.%06d] [%08x] libusbx: %s [%s] ",
1863 (int)now.tv_sec, (int)now.tv_usec, usbi_get_tid(), prefix, function);
1864 } else {
1865 fprintf(stderr, "libusbx: %s [%s] ", prefix, function);
1868 vfprintf(stderr, format, args);
1870 fprintf(stderr, "\n");
1873 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
1874 const char *function, const char *format, ...)
1876 va_list args;
1878 va_start (args, format);
1879 usbi_log_v(ctx, level, function, format, args);
1880 va_end (args);
1883 /** \ingroup misc
1884 * Returns a constant NULL-terminated string with the ASCII name of a libusb
1885 * error or transfer status code. The caller must not free() the returned
1886 * string.
1888 * \param error_code The \ref libusb_error or libusb_transfer_status code to
1889 * return the name of.
1890 * \returns The error name, or the string **UNKNOWN** if the value of
1891 * error_code is not a known error / status code.
1893 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
1895 switch (error_code) {
1896 case LIBUSB_ERROR_IO:
1897 return "LIBUSB_ERROR_IO";
1898 case LIBUSB_ERROR_INVALID_PARAM:
1899 return "LIBUSB_ERROR_INVALID_PARAM";
1900 case LIBUSB_ERROR_ACCESS:
1901 return "LIBUSB_ERROR_ACCESS";
1902 case LIBUSB_ERROR_NO_DEVICE:
1903 return "LIBUSB_ERROR_NO_DEVICE";
1904 case LIBUSB_ERROR_NOT_FOUND:
1905 return "LIBUSB_ERROR_NOT_FOUND";
1906 case LIBUSB_ERROR_BUSY:
1907 return "LIBUSB_ERROR_BUSY";
1908 case LIBUSB_ERROR_TIMEOUT:
1909 return "LIBUSB_ERROR_TIMEOUT";
1910 case LIBUSB_ERROR_OVERFLOW:
1911 return "LIBUSB_ERROR_OVERFLOW";
1912 case LIBUSB_ERROR_PIPE:
1913 return "LIBUSB_ERROR_PIPE";
1914 case LIBUSB_ERROR_INTERRUPTED:
1915 return "LIBUSB_ERROR_INTERRUPTED";
1916 case LIBUSB_ERROR_NO_MEM:
1917 return "LIBUSB_ERROR_NO_MEM";
1918 case LIBUSB_ERROR_NOT_SUPPORTED:
1919 return "LIBUSB_ERROR_NOT_SUPPORTED";
1920 case LIBUSB_ERROR_OTHER:
1921 return "LIBUSB_ERROR_OTHER";
1923 case LIBUSB_TRANSFER_ERROR:
1924 return "LIBUSB_TRANSFER_ERROR";
1925 case LIBUSB_TRANSFER_TIMED_OUT:
1926 return "LIBUSB_TRANSFER_TIMED_OUT";
1927 case LIBUSB_TRANSFER_CANCELLED:
1928 return "LIBUSB_TRANSFER_CANCELLED";
1929 case LIBUSB_TRANSFER_STALL:
1930 return "LIBUSB_TRANSFER_STALL";
1931 case LIBUSB_TRANSFER_NO_DEVICE:
1932 return "LIBUSB_TRANSFER_NO_DEVICE";
1933 case LIBUSB_TRANSFER_OVERFLOW:
1934 return "LIBUSB_TRANSFER_OVERFLOW";
1936 case 0:
1937 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
1938 default:
1939 return "**UNKNOWN**";
1943 /** \ingroup misc
1944 * Returns a pointer to const struct libusb_version with the version
1945 * (major, minor, micro, nano and rc) of the running library.
1947 DEFAULT_VISIBILITY
1948 const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
1950 return &libusb_version_internal;