Linux: Don't set the USBFS_URB_SHORT_NOT_OK flag on the last urb
[libusbx.git] / libusb / core.c
blob5bface25f0f89e0171fd74530f31cd6b06cfd884
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>
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
31 #endif
33 #ifdef HAVE_SYS_TIME_H
34 #include <sys/time.h>
35 #endif
37 #if defined(OS_WINCE)
38 #include "missing.h" // getenv()
39 #endif
41 #include "libusbi.h"
43 #if defined(OS_LINUX)
44 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
45 #elif defined(OS_DARWIN)
46 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
47 #elif defined(OS_OPENBSD)
48 const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
49 #elif defined(OS_WINDOWS)
50 const struct usbi_os_backend * const usbi_backend = &windows_backend;
51 #elif defined(OS_WINCE)
52 const struct usbi_os_backend * const usbi_backend = &wince_backend;
53 #else
54 #error "Unsupported OS"
55 #endif
57 struct libusb_context *usbi_default_context = NULL;
58 const struct libusb_version libusb_version_internal =
59 { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
60 LIBUSB_RC, "http://libusbx.org" };
61 static int default_context_refcnt = 0;
62 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
63 static struct timeval timestamp_origin = { 0, 0 };
65 /**
66 * \mainpage libusbx-1.0 API Reference
68 * \section intro Introduction
70 * libusbx is an open source library that allows you to communicate with USB
71 * devices from userspace. For more info, see the
72 * <a href="http://libusbx.org">libusbx homepage</a>.
74 * This documentation is aimed at application developers wishing to
75 * communicate with USB peripherals from their own software. After reviewing
76 * this documentation, feedback and questions can be sent to the
77 * <a href="http://mailing-list.libusbx.org">libusbx-devel mailing list</a>.
79 * This documentation assumes knowledge of how to operate USB devices from
80 * a software standpoint (descriptors, configurations, interfaces, endpoints,
81 * control/bulk/interrupt/isochronous transfers, etc). Full information
82 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
83 * Specification</a> which is available for free download. You can probably
84 * find less verbose introductions by searching the web.
86 * \section features Library features
88 * - All transfer types supported (control/bulk/interrupt/isochronous)
89 * - 2 transfer interfaces:
90 * -# Synchronous (simple)
91 * -# Asynchronous (more complicated, but more powerful)
92 * - Thread safe (although the asynchronous interface means that you
93 * usually won't need to thread)
94 * - Lightweight with lean API
95 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
97 * \section gettingstarted Getting Started
99 * To begin reading the API documentation, start with the Modules page which
100 * links to the different categories of libusbx's functionality.
102 * One decision you will have to make is whether to use the synchronous
103 * or the asynchronous data transfer interface. The \ref io documentation
104 * provides some insight into this topic.
106 * Some example programs can be found in the libusbx source distribution under
107 * the "examples" subdirectory. The libusbx homepage includes a list of
108 * real-life project examples which use libusbx.
110 * \section errorhandling Error handling
112 * libusbx functions typically return 0 on success or a negative error code
113 * on failure. These negative error codes relate to LIBUSB_ERROR constants
114 * which are listed on the \ref misc "miscellaneous" documentation page.
116 * \section msglog Debug message logging
118 * libusbx uses stderr for all logging. By default, logging is set to NONE,
119 * which means that no output will be produced. However, unless the library
120 * has been compiled with logging disabled, then any application calls to
121 * libusb_set_debug(), or the setting of the environmental variable
122 * LIBUSB_DEBUG outside of the application, can result in logging being
123 * produced. Your application should therefore not close stderr, but instead
124 * direct it to the null device if its output is undesireable.
126 * The libusb_set_debug() function can be used to enable logging of certain
127 * messages. Under standard configuration, libusbx doesn't really log much
128 * so you are advised to use this function to enable all error/warning/
129 * informational messages. It will help debug problems with your software.
131 * The logged messages are unstructured. There is no one-to-one correspondence
132 * between messages being logged and success or failure return codes from
133 * libusbx functions. There is no format to the messages, so you should not
134 * try to capture or parse them. They are not and will not be localized.
135 * These messages are not intended to being passed to your application user;
136 * instead, you should interpret the error codes returned from libusbx functions
137 * and provide appropriate notification to the user. The messages are simply
138 * there to aid you as a programmer, and if you're confused because you're
139 * getting a strange error code from a libusbx function, enabling message
140 * logging may give you a suitable explanation.
142 * The LIBUSB_DEBUG environment variable can be used to enable message logging
143 * at run-time. This environment variable should be set to a log level number,
144 * which is interpreted the same as the libusb_set_debug() parameter. When this
145 * environment variable is set, the message logging verbosity level is fixed
146 * and libusb_set_debug() effectively does nothing.
148 * libusbx can be compiled without any logging functions, useful for embedded
149 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
150 * variable have no effects.
152 * libusbx can also be compiled with verbose debugging messages always. When
153 * the library is compiled in this way, all messages of all verbosities are
154 * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
155 * have no effects.
157 * \section remarks Other remarks
159 * libusbx does have imperfections. The \ref caveats "caveats" page attempts
160 * to document these.
164 * \page caveats Caveats
166 * \section devresets Device resets
168 * The libusb_reset_device() function allows you to reset a device. If your
169 * program has to call such a function, it should obviously be aware that
170 * the reset will cause device state to change (e.g. register values may be
171 * reset).
173 * The problem is that any other program could reset the device your program
174 * is working with, at any time. libusbx does not offer a mechanism to inform
175 * you when this has happened, so if someone else resets your device it will
176 * not be clear to your own program why the device state has changed.
178 * Ultimately, this is a limitation of writing drivers in userspace.
179 * Separation from the USB stack in the underlying kernel makes it difficult
180 * for the operating system to deliver such notifications to your program.
181 * The Linux kernel USB stack allows such reset notifications to be delivered
182 * to in-kernel USB drivers, but it is not clear how such notifications could
183 * be delivered to second-class drivers that live in userspace.
185 * \section blockonly Blocking-only functionality
187 * The functionality listed below is only available through synchronous,
188 * blocking functions. There are no asynchronous/non-blocking alternatives,
189 * and no clear ways of implementing these.
191 * - Configuration activation (libusb_set_configuration())
192 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
193 * - Releasing of interfaces (libusb_release_interface())
194 * - Clearing of halt/stall condition (libusb_clear_halt())
195 * - Device resets (libusb_reset_device())
197 * \section nohotplug No hotplugging
199 * libusbx-1.0 lacks functionality for providing notifications of when devices
200 * are added or removed. This functionality is planned to be implemented
201 * in a later version of libusbx.
203 * That said, there is basic disconnection handling for open device handles:
204 * - If there are ongoing transfers, libusbx's handle_events loop will detect
205 * disconnections and complete ongoing transfers with the
206 * LIBUSB_TRANSFER_NO_DEVICE status code.
207 * - Many functions such as libusb_set_configuration() return the special
208 * LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected.
210 * \section configsel Configuration selection and handling
212 * When libusbx presents a device handle to an application, there is a chance
213 * that the corresponding device may be in unconfigured state. For devices
214 * with multiple configurations, there is also a chance that the configuration
215 * currently selected is not the one that the application wants to use.
217 * The obvious solution is to add a call to libusb_set_configuration() early
218 * on during your device initialization routines, but there are caveats to
219 * be aware of:
220 * -# If the device is already in the desired configuration, calling
221 * libusb_set_configuration() using the same configuration value will cause
222 * a lightweight device reset. This may not be desirable behaviour.
223 * -# libusbx will be unable to change configuration if the device is in
224 * another configuration and other programs or drivers have claimed
225 * interfaces under that configuration.
226 * -# In the case where the desired configuration is already active, libusbx
227 * may not even be able to perform a lightweight device reset. For example,
228 * take my USB keyboard with fingerprint reader: I'm interested in driving
229 * the fingerprint reader interface through libusbx, but the kernel's
230 * USB-HID driver will almost always have claimed the keyboard interface.
231 * Because the kernel has claimed an interface, it is not even possible to
232 * perform the lightweight device reset, so libusb_set_configuration() will
233 * fail. (Luckily the device in question only has a single configuration.)
235 * One solution to some of the above problems is to consider the currently
236 * active configuration. If the configuration we want is already active, then
237 * we don't have to select any configuration:
238 \code
239 cfg = libusb_get_configuration(dev);
240 if (cfg != desired)
241 libusb_set_configuration(dev, desired);
242 \endcode
244 * This is probably suitable for most scenarios, but is inherently racy:
245 * another application or driver may change the selected configuration
246 * <em>after</em> the libusb_get_configuration() call.
248 * Even in cases where libusb_set_configuration() succeeds, consider that other
249 * applications or drivers may change configuration after your application
250 * calls libusb_set_configuration().
252 * One possible way to lock your device into a specific configuration is as
253 * follows:
254 * -# Set the desired configuration (or use the logic above to realise that
255 * it is already in the desired configuration)
256 * -# Claim the interface that you wish to use
257 * -# Check that the currently active configuration is the one that you want
258 * to use.
260 * The above method works because once an interface is claimed, no application
261 * or driver is able to select another configuration.
263 * \section earlycomp Early transfer completion
265 * NOTE: This section is currently Linux-centric. I am not sure if any of these
266 * considerations apply to Darwin or other platforms.
268 * When a transfer completes early (i.e. when less data is received/sent in
269 * any one packet than the transfer buffer allows for) then libusbx is designed
270 * to terminate the transfer immediately, not transferring or receiving any
271 * more data unless other transfers have been queued by the user.
273 * On legacy platforms, libusbx is unable to do this in all situations. After
274 * the incomplete packet occurs, "surplus" data may be transferred. For recent
275 * versions of libusbx, this information is kept (the data length of the
276 * transfer is updated) and, for device-to-host transfers, any surplus data was
277 * added to the buffer. Still, this is not a nice solution because it loses the
278 * information about the end of the short packet, and the user probably wanted
279 * that surplus data to arrive in the next logical transfer.
282 * \section zlp Zero length packets
284 * - libusbx is able to send a packet of zero length to an endpoint simply by
285 * submitting a transfer of zero length.
286 * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
287 * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
291 * \page contexts Contexts
293 * It is possible that libusbx may be used simultaneously from two independent
294 * libraries linked into the same executable. For example, if your application
295 * has a plugin-like system which allows the user to dynamically load a range
296 * of modules into your program, it is feasible that two independently
297 * developed modules may both use libusbx.
299 * libusbx is written to allow for these multiple user scenarios. The two
300 * "instances" of libusbx will not interfere: libusb_set_debug() calls
301 * from one user will not affect the same settings for other users, other
302 * users can continue using libusbx after one of them calls libusb_exit(), etc.
304 * This is made possible through libusbx's <em>context</em> concept. When you
305 * call libusb_init(), you are (optionally) given a context. You can then pass
306 * this context pointer back into future libusbx functions.
308 * In order to keep things simple for more simplistic applications, it is
309 * legal to pass NULL to all functions requiring a context pointer (as long as
310 * you're sure no other code will attempt to use libusbx from the same process).
311 * When you pass NULL, the default context will be used. The default context
312 * is created the first time a process calls libusb_init() when no other
313 * context is alive. Contexts are destroyed during libusb_exit().
315 * The default context is reference-counted and can be shared. That means that
316 * if libusb_init(NULL) is called twice within the same process, the two
317 * users end up sharing the same context. The deinitialization and freeing of
318 * the default context will only happen when the last user calls libusb_exit().
319 * In other words, the default context is created and initialized when its
320 * reference count goes from 0 to 1, and is deinitialized and destroyed when
321 * its reference count goes from 1 to 0.
323 * You may be wondering why only a subset of libusbx functions require a
324 * context pointer in their function definition. Internally, libusbx stores
325 * context pointers in other objects (e.g. libusb_device instances) and hence
326 * can infer the context from those objects.
330 * @defgroup lib Library initialization/deinitialization
331 * This page details how to initialize and deinitialize libusbx. Initialization
332 * must be performed before using any libusbx functionality, and similarly you
333 * must not call any libusbx functions after deinitialization.
337 * @defgroup dev Device handling and enumeration
338 * The functionality documented below is designed to help with the following
339 * operations:
340 * - Enumerating the USB devices currently attached to the system
341 * - Choosing a device to operate from your software
342 * - Opening and closing the chosen device
344 * \section nutshell In a nutshell...
346 * The description below really makes things sound more complicated than they
347 * actually are. The following sequence of function calls will be suitable
348 * for almost all scenarios and does not require you to have such a deep
349 * understanding of the resource management issues:
350 * \code
351 // discover devices
352 libusb_device **list;
353 libusb_device *found = NULL;
354 ssize_t cnt = libusb_get_device_list(NULL, &list);
355 ssize_t i = 0;
356 int err = 0;
357 if (cnt < 0)
358 error();
360 for (i = 0; i < cnt; i++) {
361 libusb_device *device = list[i];
362 if (is_interesting(device)) {
363 found = device;
364 break;
368 if (found) {
369 libusb_device_handle *handle;
371 err = libusb_open(found, &handle);
372 if (err)
373 error();
374 // etc
377 libusb_free_device_list(list, 1);
378 \endcode
380 * The two important points:
381 * - You asked libusb_free_device_list() to unreference the devices (2nd
382 * parameter)
383 * - You opened the device before freeing the list and unreferencing the
384 * devices
386 * If you ended up with a handle, you can now proceed to perform I/O on the
387 * device.
389 * \section devshandles Devices and device handles
390 * libusbx has a concept of a USB device, represented by the
391 * \ref libusb_device opaque type. A device represents a USB device that
392 * is currently or was previously connected to the system. Using a reference
393 * to a device, you can determine certain information about the device (e.g.
394 * you can read the descriptor data).
396 * The libusb_get_device_list() function can be used to obtain a list of
397 * devices currently connected to the system. This is known as device
398 * discovery.
400 * Just because you have a reference to a device does not mean it is
401 * necessarily usable. The device may have been unplugged, you may not have
402 * permission to operate such device, or another program or driver may be
403 * using the device.
405 * When you've found a device that you'd like to operate, you must ask
406 * libusbx to open the device using the libusb_open() function. Assuming
407 * success, libusbx then returns you a <em>device handle</em>
408 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
409 * operate on the handle rather than the original device pointer.
411 * \section devref Device discovery and reference counting
413 * Device discovery (i.e. calling libusb_get_device_list()) returns a
414 * freshly-allocated list of devices. The list itself must be freed when
415 * you are done with it. libusbx also needs to know when it is OK to free
416 * the contents of the list - the devices themselves.
418 * To handle these issues, libusbx provides you with two separate items:
419 * - A function to free the list itself
420 * - A reference counting system for the devices inside
422 * New devices presented by the libusb_get_device_list() function all have a
423 * reference count of 1. You can increase and decrease reference count using
424 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
425 * its reference count reaches 0.
427 * With the above information in mind, the process of opening a device can
428 * be viewed as follows:
429 * -# Discover devices using libusb_get_device_list().
430 * -# Choose the device that you want to operate, and call libusb_open().
431 * -# Unref all devices in the discovered device list.
432 * -# Free the discovered device list.
434 * The order is important - you must not unreference the device before
435 * attempting to open it, because unreferencing it may destroy the device.
437 * For convenience, the libusb_free_device_list() function includes a
438 * parameter to optionally unreference all the devices in the list before
439 * freeing the list itself. This combines steps 3 and 4 above.
441 * As an implementation detail, libusb_open() actually adds a reference to
442 * the device in question. This is because the device remains available
443 * through the handle via libusb_get_device(). The reference is deleted during
444 * libusb_close().
447 /** @defgroup misc Miscellaneous */
449 /* we traverse usbfs without knowing how many devices we are going to find.
450 * so we create this discovered_devs model which is similar to a linked-list
451 * which grows when required. it can be freed once discovery has completed,
452 * eliminating the need for a list node in the libusb_device structure
453 * itself. */
454 #define DISCOVERED_DEVICES_SIZE_STEP 8
456 static struct discovered_devs *discovered_devs_alloc(void)
458 struct discovered_devs *ret =
459 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
461 if (ret) {
462 ret->len = 0;
463 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
465 return ret;
468 /* append a device to the discovered devices collection. may realloc itself,
469 * returning new discdevs. returns NULL on realloc failure. */
470 struct discovered_devs *discovered_devs_append(
471 struct discovered_devs *discdevs, struct libusb_device *dev)
473 size_t len = discdevs->len;
474 size_t capacity;
476 /* if there is space, just append the device */
477 if (len < discdevs->capacity) {
478 discdevs->devices[len] = libusb_ref_device(dev);
479 discdevs->len++;
480 return discdevs;
483 /* exceeded capacity, need to grow */
484 usbi_dbg("need to increase capacity");
485 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
486 discdevs = usbi_reallocf(discdevs,
487 sizeof(*discdevs) + (sizeof(void *) * capacity));
488 if (discdevs) {
489 discdevs->capacity = capacity;
490 discdevs->devices[len] = libusb_ref_device(dev);
491 discdevs->len++;
494 return discdevs;
497 static void discovered_devs_free(struct discovered_devs *discdevs)
499 size_t i;
501 for (i = 0; i < discdevs->len; i++)
502 libusb_unref_device(discdevs->devices[i]);
504 free(discdevs);
507 /* Allocate a new device with a specific session ID. The returned device has
508 * a reference count of 1. */
509 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
510 unsigned long session_id)
512 size_t priv_size = usbi_backend->device_priv_size;
513 struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
514 int r;
516 if (!dev)
517 return NULL;
519 r = usbi_mutex_init(&dev->lock, NULL);
520 if (r) {
521 free(dev);
522 return NULL;
525 dev->ctx = ctx;
526 dev->refcnt = 1;
527 dev->session_data = session_id;
528 dev->speed = LIBUSB_SPEED_UNKNOWN;
529 memset(&dev->os_priv, 0, priv_size);
531 usbi_mutex_lock(&ctx->usb_devs_lock);
532 list_add(&dev->list, &ctx->usb_devs);
533 usbi_mutex_unlock(&ctx->usb_devs_lock);
534 return dev;
537 /* Perform some final sanity checks on a newly discovered device. If this
538 * function fails (negative return code), the device should not be added
539 * to the discovered device list. */
540 int usbi_sanitize_device(struct libusb_device *dev)
542 int r;
543 unsigned char raw_desc[DEVICE_DESC_LENGTH];
544 uint8_t num_configurations;
545 int host_endian;
547 r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
548 if (r < 0)
549 return r;
551 num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
552 if (num_configurations > USB_MAXCONFIG) {
553 usbi_err(DEVICE_CTX(dev), "too many configurations");
554 return LIBUSB_ERROR_IO;
555 } else if (0 == num_configurations)
556 usbi_dbg("zero configurations, maybe an unauthorized device");
558 dev->num_configurations = num_configurations;
559 return 0;
562 /* Examine libusbx's internal list of known devices, looking for one with
563 * a specific session ID. Returns the matching device if it was found, and
564 * NULL otherwise. */
565 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
566 unsigned long session_id)
568 struct libusb_device *dev;
569 struct libusb_device *ret = NULL;
571 usbi_mutex_lock(&ctx->usb_devs_lock);
572 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
573 if (dev->session_data == session_id) {
574 ret = dev;
575 break;
577 usbi_mutex_unlock(&ctx->usb_devs_lock);
579 return ret;
582 /** @ingroup dev
583 * Returns a list of USB devices currently attached to the system. This is
584 * your entry point into finding a USB device to operate.
586 * You are expected to unreference all the devices when you are done with
587 * them, and then free the list with libusb_free_device_list(). Note that
588 * libusb_free_device_list() can unref all the devices for you. Be careful
589 * not to unreference a device you are about to open until after you have
590 * opened it.
592 * This return value of this function indicates the number of devices in
593 * the resultant list. The list is actually one element larger, as it is
594 * NULL-terminated.
596 * \param ctx the context to operate on, or NULL for the default context
597 * \param list output location for a list of devices. Must be later freed with
598 * libusb_free_device_list().
599 * \returns the number of devices in the outputted list, or any
600 * \ref libusb_error according to errors encountered by the backend.
602 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
603 libusb_device ***list)
605 struct discovered_devs *discdevs = discovered_devs_alloc();
606 struct libusb_device **ret;
607 int r = 0;
608 ssize_t i, len;
609 USBI_GET_CONTEXT(ctx);
610 usbi_dbg("");
612 if (!discdevs)
613 return LIBUSB_ERROR_NO_MEM;
615 r = usbi_backend->get_device_list(ctx, &discdevs);
616 if (r < 0) {
617 len = r;
618 goto out;
621 /* convert discovered_devs into a list */
622 len = discdevs->len;
623 ret = calloc(len + 1, sizeof(struct libusb_device *));
624 if (!ret) {
625 len = LIBUSB_ERROR_NO_MEM;
626 goto out;
629 ret[len] = NULL;
630 for (i = 0; i < len; i++) {
631 struct libusb_device *dev = discdevs->devices[i];
632 ret[i] = libusb_ref_device(dev);
634 *list = ret;
636 out:
637 discovered_devs_free(discdevs);
638 return len;
641 /** \ingroup dev
642 * Frees a list of devices previously discovered using
643 * libusb_get_device_list(). If the unref_devices parameter is set, the
644 * reference count of each device in the list is decremented by 1.
645 * \param list the list to free
646 * \param unref_devices whether to unref the devices in the list
648 void API_EXPORTED libusb_free_device_list(libusb_device **list,
649 int unref_devices)
651 if (!list)
652 return;
654 if (unref_devices) {
655 int i = 0;
656 struct libusb_device *dev;
658 while ((dev = list[i++]) != NULL)
659 libusb_unref_device(dev);
661 free(list);
664 /** \ingroup dev
665 * Get the number of the bus that a device is connected to.
666 * \param dev a device
667 * \returns the bus number
669 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
671 return dev->bus_number;
674 /** \ingroup dev
675 * Get the number of the port that a device is connected to
676 * \param dev a device
677 * \returns the port number (0 if not available)
679 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
681 return dev->port_number;
684 /** \ingroup dev
685 * Get the list of all port numbers from root for the specified device
686 * \param ctx the context to operate on, or NULL for the default context
687 * \param dev a device
688 * \param path the array that should contain the port numbers
689 * \param path_len the maximum length of the array. As per the USB 3.0
690 * specs, the current maximum limit for the depth is 7.
691 * \returns the number of elements filled
692 * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
694 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t* path, uint8_t path_len)
696 int i = path_len;
697 ssize_t r;
698 struct libusb_device **devs = NULL;
700 /* The device needs to be open, else the parents may have been destroyed */
701 r = libusb_get_device_list(ctx, &devs);
702 if (r < 0)
703 return (int)r;
705 while(dev) {
706 // HCDs can be listed as devices and would have port #0
707 // TODO: see how the other backends want to implement HCDs as parents
708 if (dev->port_number == 0)
709 break;
710 i--;
711 if (i < 0) {
712 libusb_free_device_list(devs, 1);
713 return LIBUSB_ERROR_OVERFLOW;
715 path[i] = dev->port_number;
716 dev = dev->parent_dev;
718 libusb_free_device_list(devs, 1);
719 memmove(path, &path[i], path_len-i);
720 return path_len-i;
723 /** \ingroup dev
724 * Get the the parent from the specified device [EXPERIMENTAL]
725 * \param dev a device
726 * \returns the device parent or NULL if not available
727 * You should issue a libusb_get_device_list() before calling this
728 * function and make sure that you only access the parent before issuing
729 * libusb_free_device_list(). The reason is that libusbx currently does
730 * not maintain a permanent list of device instances, and therefore can
731 * only guarantee that parents are fully instantiated within a
732 * libusb_get_device_list() - libusb_free_device_list() block.
734 DEFAULT_VISIBILITY
735 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
737 return dev->parent_dev;
740 /** \ingroup dev
741 * Get the address of the device on the bus it is connected to.
742 * \param dev a device
743 * \returns the device address
745 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
747 return dev->device_address;
750 /** \ingroup dev
751 * Get the negotiated connection speed for a device.
752 * \param dev a device
753 * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
754 * the OS doesn't know or doesn't support returning the negotiated speed.
756 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
758 return dev->speed;
761 static const struct libusb_endpoint_descriptor *find_endpoint(
762 struct libusb_config_descriptor *config, unsigned char endpoint)
764 int iface_idx;
765 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
766 const struct libusb_interface *iface = &config->interface[iface_idx];
767 int altsetting_idx;
769 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
770 altsetting_idx++) {
771 const struct libusb_interface_descriptor *altsetting
772 = &iface->altsetting[altsetting_idx];
773 int ep_idx;
775 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
776 const struct libusb_endpoint_descriptor *ep =
777 &altsetting->endpoint[ep_idx];
778 if (ep->bEndpointAddress == endpoint)
779 return ep;
783 return NULL;
786 /** \ingroup dev
787 * Convenience function to retrieve the wMaxPacketSize value for a particular
788 * endpoint in the active device configuration.
790 * This function was originally intended to be of assistance when setting up
791 * isochronous transfers, but a design mistake resulted in this function
792 * instead. It simply returns the wMaxPacketSize value without considering
793 * its contents. If you're dealing with isochronous transfers, you probably
794 * want libusb_get_max_iso_packet_size() instead.
796 * \param dev a device
797 * \param endpoint address of the endpoint in question
798 * \returns the wMaxPacketSize value
799 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
800 * \returns LIBUSB_ERROR_OTHER on other failure
802 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
803 unsigned char endpoint)
805 struct libusb_config_descriptor *config;
806 const struct libusb_endpoint_descriptor *ep;
807 int r;
809 r = libusb_get_active_config_descriptor(dev, &config);
810 if (r < 0) {
811 usbi_err(DEVICE_CTX(dev),
812 "could not retrieve active config descriptor");
813 return LIBUSB_ERROR_OTHER;
816 ep = find_endpoint(config, endpoint);
817 if (!ep)
818 return LIBUSB_ERROR_NOT_FOUND;
820 r = ep->wMaxPacketSize;
821 libusb_free_config_descriptor(config);
822 return r;
825 /** \ingroup dev
826 * Calculate the maximum packet size which a specific endpoint is capable is
827 * sending or receiving in the duration of 1 microframe
829 * Only the active configution is examined. The calculation is based on the
830 * wMaxPacketSize field in the endpoint descriptor as described in section
831 * 9.6.6 in the USB 2.0 specifications.
833 * If acting on an isochronous or interrupt endpoint, this function will
834 * multiply the value found in bits 0:10 by the number of transactions per
835 * microframe (determined by bits 11:12). Otherwise, this function just
836 * returns the numeric value found in bits 0:10.
838 * This function is useful for setting up isochronous transfers, for example
839 * you might pass the return value from this function to
840 * libusb_set_iso_packet_lengths() in order to set the length field of every
841 * isochronous packet in a transfer.
843 * Since v1.0.3.
845 * \param dev a device
846 * \param endpoint address of the endpoint in question
847 * \returns the maximum packet size which can be sent/received on this endpoint
848 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
849 * \returns LIBUSB_ERROR_OTHER on other failure
851 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
852 unsigned char endpoint)
854 struct libusb_config_descriptor *config;
855 const struct libusb_endpoint_descriptor *ep;
856 enum libusb_transfer_type ep_type;
857 uint16_t val;
858 int r;
860 r = libusb_get_active_config_descriptor(dev, &config);
861 if (r < 0) {
862 usbi_err(DEVICE_CTX(dev),
863 "could not retrieve active config descriptor");
864 return LIBUSB_ERROR_OTHER;
867 ep = find_endpoint(config, endpoint);
868 if (!ep)
869 return LIBUSB_ERROR_NOT_FOUND;
871 val = ep->wMaxPacketSize;
872 ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
873 libusb_free_config_descriptor(config);
875 r = val & 0x07ff;
876 if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
877 || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
878 r *= (1 + ((val >> 11) & 3));
879 return r;
882 /** \ingroup dev
883 * Increment the reference count of a device.
884 * \param dev the device to reference
885 * \returns the same device
887 DEFAULT_VISIBILITY
888 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
890 usbi_mutex_lock(&dev->lock);
891 dev->refcnt++;
892 usbi_mutex_unlock(&dev->lock);
893 return dev;
896 /** \ingroup dev
897 * Decrement the reference count of a device. If the decrement operation
898 * causes the reference count to reach zero, the device shall be destroyed.
899 * \param dev the device to unreference
901 void API_EXPORTED libusb_unref_device(libusb_device *dev)
903 int refcnt;
905 if (!dev)
906 return;
908 usbi_mutex_lock(&dev->lock);
909 refcnt = --dev->refcnt;
910 usbi_mutex_unlock(&dev->lock);
912 if (refcnt == 0) {
913 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
915 if (usbi_backend->destroy_device)
916 usbi_backend->destroy_device(dev);
918 usbi_mutex_lock(&dev->ctx->usb_devs_lock);
919 list_del(&dev->list);
920 usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
922 usbi_mutex_destroy(&dev->lock);
923 free(dev);
928 * Interrupt the iteration of the event handling thread, so that it picks
929 * up the new fd.
931 void usbi_fd_notification(struct libusb_context *ctx)
933 unsigned char dummy = 1;
934 ssize_t r;
936 if (ctx == NULL)
937 return;
939 /* record that we are messing with poll fds */
940 usbi_mutex_lock(&ctx->pollfd_modify_lock);
941 ctx->pollfd_modify++;
942 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
944 /* write some data on control pipe to interrupt event handlers */
945 r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
946 if (r <= 0) {
947 usbi_warn(ctx, "internal signalling write failed");
948 usbi_mutex_lock(&ctx->pollfd_modify_lock);
949 ctx->pollfd_modify--;
950 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
951 return;
954 /* take event handling lock */
955 libusb_lock_events(ctx);
957 /* read the dummy data */
958 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
959 if (r <= 0)
960 usbi_warn(ctx, "internal signalling read failed");
962 /* we're done with modifying poll fds */
963 usbi_mutex_lock(&ctx->pollfd_modify_lock);
964 ctx->pollfd_modify--;
965 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
967 /* Release event handling lock and wake up event waiters */
968 libusb_unlock_events(ctx);
971 /** \ingroup dev
972 * Open a device and obtain a device handle. A handle allows you to perform
973 * I/O on the device in question.
975 * Internally, this function adds a reference to the device and makes it
976 * available to you through libusb_get_device(). This reference is removed
977 * during libusb_close().
979 * This is a non-blocking function; no requests are sent over the bus.
981 * \param dev the device to open
982 * \param handle output location for the returned device handle pointer. Only
983 * populated when the return code is 0.
984 * \returns 0 on success
985 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
986 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
987 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
988 * \returns another LIBUSB_ERROR code on other failure
990 int API_EXPORTED libusb_open(libusb_device *dev,
991 libusb_device_handle **handle)
993 struct libusb_context *ctx = DEVICE_CTX(dev);
994 struct libusb_device_handle *_handle;
995 size_t priv_size = usbi_backend->device_handle_priv_size;
996 int r;
997 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
999 _handle = malloc(sizeof(*_handle) + priv_size);
1000 if (!_handle)
1001 return LIBUSB_ERROR_NO_MEM;
1003 r = usbi_mutex_init(&_handle->lock, NULL);
1004 if (r) {
1005 free(_handle);
1006 return LIBUSB_ERROR_OTHER;
1009 _handle->dev = libusb_ref_device(dev);
1010 _handle->claimed_interfaces = 0;
1011 memset(&_handle->os_priv, 0, priv_size);
1013 r = usbi_backend->open(_handle);
1014 if (r < 0) {
1015 usbi_dbg("could not open device: %s", libusb_error_name(r));
1016 libusb_unref_device(dev);
1017 usbi_mutex_destroy(&_handle->lock);
1018 free(_handle);
1019 return r;
1022 usbi_mutex_lock(&ctx->open_devs_lock);
1023 list_add(&_handle->list, &ctx->open_devs);
1024 usbi_mutex_unlock(&ctx->open_devs_lock);
1025 *handle = _handle;
1027 /* At this point, we want to interrupt any existing event handlers so
1028 * that they realise the addition of the new device's poll fd. One
1029 * example when this is desirable is if the user is running a separate
1030 * dedicated libusbx events handling thread, which is running with a long
1031 * or infinite timeout. We want to interrupt that iteration of the loop,
1032 * so that it picks up the new fd, and then continues. */
1033 usbi_fd_notification(ctx);
1035 return 0;
1038 /** \ingroup dev
1039 * Convenience function for finding a device with a particular
1040 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1041 * for those scenarios where you are using libusbx to knock up a quick test
1042 * application - it allows you to avoid calling libusb_get_device_list() and
1043 * worrying about traversing/freeing the list.
1045 * This function has limitations and is hence not intended for use in real
1046 * applications: if multiple devices have the same IDs it will only
1047 * give you the first one, etc.
1049 * \param ctx the context to operate on, or NULL for the default context
1050 * \param vendor_id the idVendor value to search for
1051 * \param product_id the idProduct value to search for
1052 * \returns a handle for the first found device, or NULL on error or if the
1053 * device could not be found. */
1054 DEFAULT_VISIBILITY
1055 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1056 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1058 struct libusb_device **devs;
1059 struct libusb_device *found = NULL;
1060 struct libusb_device *dev;
1061 struct libusb_device_handle *handle = NULL;
1062 size_t i = 0;
1063 int r;
1065 if (libusb_get_device_list(ctx, &devs) < 0)
1066 return NULL;
1068 while ((dev = devs[i++]) != NULL) {
1069 struct libusb_device_descriptor desc;
1070 r = libusb_get_device_descriptor(dev, &desc);
1071 if (r < 0)
1072 goto out;
1073 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1074 found = dev;
1075 break;
1079 if (found) {
1080 r = libusb_open(found, &handle);
1081 if (r < 0)
1082 handle = NULL;
1085 out:
1086 libusb_free_device_list(devs, 1);
1087 return handle;
1090 static void do_close(struct libusb_context *ctx,
1091 struct libusb_device_handle *dev_handle)
1093 struct usbi_transfer *itransfer;
1094 struct usbi_transfer *tmp;
1096 libusb_lock_events(ctx);
1098 /* remove any transfers in flight that are for this device */
1099 usbi_mutex_lock(&ctx->flying_transfers_lock);
1101 /* safe iteration because transfers may be being deleted */
1102 list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
1103 struct libusb_transfer *transfer =
1104 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1106 if (transfer->dev_handle != dev_handle)
1107 continue;
1109 if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1110 usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1112 if (itransfer->flags & USBI_TRANSFER_CANCELLING)
1113 usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1114 else
1115 usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1118 /* remove from the list of in-flight transfers and make sure
1119 * we don't accidentally use the device handle in the future
1120 * (or that such accesses will be easily caught and identified as a crash)
1122 usbi_mutex_lock(&itransfer->lock);
1123 list_del(&itransfer->list);
1124 transfer->dev_handle = NULL;
1125 usbi_mutex_unlock(&itransfer->lock);
1127 /* it is up to the user to free up the actual transfer struct. this is
1128 * just making sure that we don't attempt to process the transfer after
1129 * the device handle is invalid
1131 usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
1132 transfer, dev_handle);
1134 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1136 libusb_unlock_events(ctx);
1138 usbi_mutex_lock(&ctx->open_devs_lock);
1139 list_del(&dev_handle->list);
1140 usbi_mutex_unlock(&ctx->open_devs_lock);
1142 usbi_backend->close(dev_handle);
1143 libusb_unref_device(dev_handle->dev);
1144 usbi_mutex_destroy(&dev_handle->lock);
1145 free(dev_handle);
1148 /** \ingroup dev
1149 * Close a device handle. Should be called on all open handles before your
1150 * application exits.
1152 * Internally, this function destroys the reference that was added by
1153 * libusb_open() on the given device.
1155 * This is a non-blocking function; no requests are sent over the bus.
1157 * \param dev_handle the handle to close
1159 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1161 struct libusb_context *ctx;
1162 unsigned char dummy = 1;
1163 ssize_t r;
1165 if (!dev_handle)
1166 return;
1167 usbi_dbg("");
1169 ctx = HANDLE_CTX(dev_handle);
1171 /* Similarly to libusb_open(), we want to interrupt all event handlers
1172 * at this point. More importantly, we want to perform the actual close of
1173 * the device while holding the event handling lock (preventing any other
1174 * thread from doing event handling) because we will be removing a file
1175 * descriptor from the polling loop. */
1177 /* record that we are messing with poll fds */
1178 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1179 ctx->pollfd_modify++;
1180 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1182 /* write some data on control pipe to interrupt event handlers */
1183 r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1184 if (r <= 0) {
1185 usbi_warn(ctx, "internal signalling write failed, closing anyway");
1186 do_close(ctx, dev_handle);
1187 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1188 ctx->pollfd_modify--;
1189 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1190 return;
1193 /* take event handling lock */
1194 libusb_lock_events(ctx);
1196 /* read the dummy data */
1197 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1198 if (r <= 0)
1199 usbi_warn(ctx, "internal signalling read failed, closing anyway");
1201 /* Close the device */
1202 do_close(ctx, dev_handle);
1204 /* we're done with modifying poll fds */
1205 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1206 ctx->pollfd_modify--;
1207 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1209 /* Release event handling lock and wake up event waiters */
1210 libusb_unlock_events(ctx);
1213 /** \ingroup dev
1214 * Get the underlying device for a handle. This function does not modify
1215 * the reference count of the returned device, so do not feel compelled to
1216 * unreference it when you are done.
1217 * \param dev_handle a device handle
1218 * \returns the underlying device
1220 DEFAULT_VISIBILITY
1221 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1223 return dev_handle->dev;
1226 /** \ingroup dev
1227 * Determine the bConfigurationValue of the currently active configuration.
1229 * You could formulate your own control request to obtain this information,
1230 * but this function has the advantage that it may be able to retrieve the
1231 * information from operating system caches (no I/O involved).
1233 * If the OS does not cache this information, then this function will block
1234 * while a control transfer is submitted to retrieve the information.
1236 * This function will return a value of 0 in the <tt>config</tt> output
1237 * parameter if the device is in unconfigured state.
1239 * \param dev a device handle
1240 * \param config output location for the bConfigurationValue of the active
1241 * configuration (only valid for return code 0)
1242 * \returns 0 on success
1243 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1244 * \returns another LIBUSB_ERROR code on other failure
1246 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
1247 int *config)
1249 int r = LIBUSB_ERROR_NOT_SUPPORTED;
1251 usbi_dbg("");
1252 if (usbi_backend->get_configuration)
1253 r = usbi_backend->get_configuration(dev, config);
1255 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1256 uint8_t tmp = 0;
1257 usbi_dbg("falling back to control message");
1258 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1259 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1260 if (r == 0) {
1261 usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
1262 r = LIBUSB_ERROR_IO;
1263 } else if (r == 1) {
1264 r = 0;
1265 *config = tmp;
1266 } else {
1267 usbi_dbg("control failed, error %d", r);
1271 if (r == 0)
1272 usbi_dbg("active config %d", *config);
1274 return r;
1277 /** \ingroup dev
1278 * Set the active configuration for a device.
1280 * The operating system may or may not have already set an active
1281 * configuration on the device. It is up to your application to ensure the
1282 * correct configuration is selected before you attempt to claim interfaces
1283 * and perform other operations.
1285 * If you call this function on a device already configured with the selected
1286 * configuration, then this function will act as a lightweight device reset:
1287 * it will issue a SET_CONFIGURATION request using the current configuration,
1288 * causing most USB-related device state to be reset (altsetting reset to zero,
1289 * endpoint halts cleared, toggles reset).
1291 * You cannot change/reset configuration if your application has claimed
1292 * interfaces - you should free them with libusb_release_interface() first.
1293 * You cannot change/reset configuration if other applications or drivers have
1294 * claimed interfaces.
1296 * A configuration value of -1 will put the device in unconfigured state.
1297 * The USB specifications state that a configuration value of 0 does this,
1298 * however buggy devices exist which actually have a configuration 0.
1300 * You should always use this function rather than formulating your own
1301 * SET_CONFIGURATION control request. This is because the underlying operating
1302 * system needs to know when such changes happen.
1304 * This is a blocking function.
1306 * \param dev a device handle
1307 * \param configuration the bConfigurationValue of the configuration you
1308 * wish to activate, or -1 if you wish to put the device in unconfigured state
1309 * \returns 0 on success
1310 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1311 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1312 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1313 * \returns another LIBUSB_ERROR code on other failure
1315 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
1316 int configuration)
1318 usbi_dbg("configuration %d", configuration);
1319 return usbi_backend->set_configuration(dev, configuration);
1322 /** \ingroup dev
1323 * Claim an interface on a given device handle. You must claim the interface
1324 * you wish to use before you can perform I/O on any of its endpoints.
1326 * It is legal to attempt to claim an already-claimed interface, in which
1327 * case libusbx just returns 0 without doing anything.
1329 * Claiming of interfaces is a purely logical operation; it does not cause
1330 * any requests to be sent over the bus. Interface claiming is used to
1331 * instruct the underlying operating system that your application wishes
1332 * to take ownership of the interface.
1334 * This is a non-blocking function.
1336 * \param dev a device handle
1337 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1338 * wish to claim
1339 * \returns 0 on success
1340 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1341 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1342 * interface
1343 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1344 * \returns a LIBUSB_ERROR code on other failure
1346 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
1347 int interface_number)
1349 int r = 0;
1351 usbi_dbg("interface %d", interface_number);
1352 if (interface_number >= USB_MAXINTERFACES)
1353 return LIBUSB_ERROR_INVALID_PARAM;
1355 usbi_mutex_lock(&dev->lock);
1356 if (dev->claimed_interfaces & (1 << interface_number))
1357 goto out;
1359 r = usbi_backend->claim_interface(dev, interface_number);
1360 if (r == 0)
1361 dev->claimed_interfaces |= 1 << interface_number;
1363 out:
1364 usbi_mutex_unlock(&dev->lock);
1365 return r;
1368 /** \ingroup dev
1369 * Release an interface previously claimed with libusb_claim_interface(). You
1370 * should release all claimed interfaces before closing a device handle.
1372 * This is a blocking function. A SET_INTERFACE control request will be sent
1373 * to the device, resetting interface state to the first alternate setting.
1375 * \param dev a device handle
1376 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1377 * previously-claimed interface
1378 * \returns 0 on success
1379 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1380 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1381 * \returns another LIBUSB_ERROR code on other failure
1383 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
1384 int interface_number)
1386 int r;
1388 usbi_dbg("interface %d", interface_number);
1389 if (interface_number >= USB_MAXINTERFACES)
1390 return LIBUSB_ERROR_INVALID_PARAM;
1392 usbi_mutex_lock(&dev->lock);
1393 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1394 r = LIBUSB_ERROR_NOT_FOUND;
1395 goto out;
1398 r = usbi_backend->release_interface(dev, interface_number);
1399 if (r == 0)
1400 dev->claimed_interfaces &= ~(1 << interface_number);
1402 out:
1403 usbi_mutex_unlock(&dev->lock);
1404 return r;
1407 /** \ingroup dev
1408 * Activate an alternate setting for an interface. The interface must have
1409 * been previously claimed with libusb_claim_interface().
1411 * You should always use this function rather than formulating your own
1412 * SET_INTERFACE control request. This is because the underlying operating
1413 * system needs to know when such changes happen.
1415 * This is a blocking function.
1417 * \param dev a device handle
1418 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1419 * previously-claimed interface
1420 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1421 * setting to activate
1422 * \returns 0 on success
1423 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1424 * requested alternate setting does not exist
1425 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1426 * \returns another LIBUSB_ERROR code on other failure
1428 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
1429 int interface_number, int alternate_setting)
1431 usbi_dbg("interface %d altsetting %d",
1432 interface_number, alternate_setting);
1433 if (interface_number >= USB_MAXINTERFACES)
1434 return LIBUSB_ERROR_INVALID_PARAM;
1436 usbi_mutex_lock(&dev->lock);
1437 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1438 usbi_mutex_unlock(&dev->lock);
1439 return LIBUSB_ERROR_NOT_FOUND;
1441 usbi_mutex_unlock(&dev->lock);
1443 return usbi_backend->set_interface_altsetting(dev, interface_number,
1444 alternate_setting);
1447 /** \ingroup dev
1448 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1449 * are unable to receive or transmit data until the halt condition is stalled.
1451 * You should cancel all pending transfers before attempting to clear the halt
1452 * condition.
1454 * This is a blocking function.
1456 * \param dev a device handle
1457 * \param endpoint the endpoint to clear halt status
1458 * \returns 0 on success
1459 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1460 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1461 * \returns another LIBUSB_ERROR code on other failure
1463 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
1464 unsigned char endpoint)
1466 usbi_dbg("endpoint %x", endpoint);
1467 return usbi_backend->clear_halt(dev, endpoint);
1470 /** \ingroup dev
1471 * Perform a USB port reset to reinitialize a device. The system will attempt
1472 * to restore the previous configuration and alternate settings after the
1473 * reset has completed.
1475 * If the reset fails, the descriptors change, or the previous state cannot be
1476 * restored, the device will appear to be disconnected and reconnected. This
1477 * means that the device handle is no longer valid (you should close it) and
1478 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1479 * when this is the case.
1481 * This is a blocking function which usually incurs a noticeable delay.
1483 * \param dev a handle of the device to reset
1484 * \returns 0 on success
1485 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1486 * device has been disconnected
1487 * \returns another LIBUSB_ERROR code on other failure
1489 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
1491 usbi_dbg("");
1492 return usbi_backend->reset_device(dev);
1495 /** \ingroup dev
1496 * Determine if a kernel driver is active on an interface. If a kernel driver
1497 * is active, you cannot claim the interface, and libusbx will be unable to
1498 * perform I/O.
1500 * This functionality is not available on Windows.
1502 * \param dev a device handle
1503 * \param interface_number the interface to check
1504 * \returns 0 if no kernel driver is active
1505 * \returns 1 if a kernel driver is active
1506 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1507 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1508 * is not available
1509 * \returns another LIBUSB_ERROR code on other failure
1510 * \see libusb_detach_kernel_driver()
1512 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
1513 int interface_number)
1515 usbi_dbg("interface %d", interface_number);
1516 if (usbi_backend->kernel_driver_active)
1517 return usbi_backend->kernel_driver_active(dev, interface_number);
1518 else
1519 return LIBUSB_ERROR_NOT_SUPPORTED;
1522 /** \ingroup dev
1523 * Detach a kernel driver from an interface. If successful, you will then be
1524 * able to claim the interface and perform I/O.
1526 * This functionality is not available on Darwin or Windows.
1528 * Note that libusbx itself also talks to the device through a special kernel
1529 * driver, if this driver is already attached to the device, this call will
1530 * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1532 * \param dev a device handle
1533 * \param interface_number the interface to detach the driver from
1534 * \returns 0 on success
1535 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1536 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1537 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1538 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1539 * is not available
1540 * \returns another LIBUSB_ERROR code on other failure
1541 * \see libusb_kernel_driver_active()
1543 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
1544 int interface_number)
1546 usbi_dbg("interface %d", interface_number);
1547 if (usbi_backend->detach_kernel_driver)
1548 return usbi_backend->detach_kernel_driver(dev, interface_number);
1549 else
1550 return LIBUSB_ERROR_NOT_SUPPORTED;
1553 /** \ingroup dev
1554 * Re-attach an interface's kernel driver, which was previously detached
1555 * using libusb_detach_kernel_driver(). This call is only effective on
1556 * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1558 * This functionality is not available on Darwin or Windows.
1560 * \param dev a device handle
1561 * \param interface_number the interface to attach the driver from
1562 * \returns 0 on success
1563 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1564 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1565 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1566 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1567 * is not available
1568 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1569 * interface is claimed by a program or driver
1570 * \returns another LIBUSB_ERROR code on other failure
1571 * \see libusb_kernel_driver_active()
1573 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
1574 int interface_number)
1576 usbi_dbg("interface %d", interface_number);
1577 if (usbi_backend->attach_kernel_driver)
1578 return usbi_backend->attach_kernel_driver(dev, interface_number);
1579 else
1580 return LIBUSB_ERROR_NOT_SUPPORTED;
1583 /** \ingroup lib
1584 * Set log message verbosity.
1586 * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
1587 * printed. If you choose to increase the message verbosity level, ensure
1588 * that your application does not close the stdout/stderr file descriptors.
1590 * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusbx is conservative
1591 * with its message logging and most of the time, will only log messages that
1592 * explain error conditions and other oddities. This will help you debug
1593 * your software.
1595 * If the LIBUSB_DEBUG environment variable was set when libusbx was
1596 * initialized, this function does nothing: the message verbosity is fixed
1597 * to the value in the environment variable.
1599 * If libusbx was compiled without any message logging, this function does
1600 * nothing: you'll never get any messages.
1602 * If libusbx was compiled with verbose debug message logging, this function
1603 * does nothing: you'll always get messages from all levels.
1605 * \param ctx the context to operate on, or NULL for the default context
1606 * \param level debug level to set
1608 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
1610 USBI_GET_CONTEXT(ctx);
1611 if (!ctx->debug_fixed)
1612 ctx->debug = level;
1615 /** \ingroup lib
1616 * Initialize libusb. This function must be called before calling any other
1617 * libusbx function.
1619 * If you do not provide an output location for a context pointer, a default
1620 * context will be created. If there was already a default context, it will
1621 * be reused (and nothing will be initialized/reinitialized).
1623 * \param context Optional output location for context pointer.
1624 * Only valid on return code 0.
1625 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1626 * \see contexts
1628 int API_EXPORTED libusb_init(libusb_context **context)
1630 char *dbg;
1631 struct libusb_context *ctx;
1632 int r = 0;
1634 usbi_mutex_static_lock(&default_context_lock);
1636 if (!timestamp_origin.tv_sec) {
1637 usbi_gettimeofday(&timestamp_origin, NULL);
1640 if (!context && usbi_default_context) {
1641 usbi_dbg("reusing default context");
1642 default_context_refcnt++;
1643 usbi_mutex_static_unlock(&default_context_lock);
1644 return 0;
1647 ctx = calloc(1, sizeof(*ctx));
1648 if (!ctx) {
1649 r = LIBUSB_ERROR_NO_MEM;
1650 goto err_unlock;
1653 #ifdef ENABLE_DEBUG_LOGGING
1654 ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
1655 #endif
1657 dbg = getenv("LIBUSB_DEBUG");
1658 if (dbg) {
1659 ctx->debug = atoi(dbg);
1660 if (ctx->debug)
1661 ctx->debug_fixed = 1;
1664 /* default context should be initialized before calling usbi_dbg */
1665 if (!usbi_default_context) {
1666 usbi_default_context = ctx;
1667 default_context_refcnt++;
1668 usbi_dbg("created default context");
1671 usbi_dbg("libusbx v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
1672 libusb_version_internal.micro, libusb_version_internal.nano);
1674 if (usbi_backend->init) {
1675 r = usbi_backend->init(ctx);
1676 if (r)
1677 goto err_free_ctx;
1680 usbi_mutex_init(&ctx->usb_devs_lock, NULL);
1681 usbi_mutex_init(&ctx->open_devs_lock, NULL);
1682 list_init(&ctx->usb_devs);
1683 list_init(&ctx->open_devs);
1685 r = usbi_io_init(ctx);
1686 if (r < 0) {
1687 if (usbi_backend->exit)
1688 usbi_backend->exit();
1689 goto err_destroy_mutex;
1692 if (context) {
1693 *context = ctx;
1695 usbi_mutex_static_unlock(&default_context_lock);
1697 return 0;
1699 err_destroy_mutex:
1700 usbi_mutex_destroy(&ctx->open_devs_lock);
1701 usbi_mutex_destroy(&ctx->usb_devs_lock);
1702 err_free_ctx:
1703 free(ctx);
1704 err_unlock:
1705 usbi_mutex_static_unlock(&default_context_lock);
1706 return r;
1709 /** \ingroup lib
1710 * Deinitialize libusb. Should be called after closing all open devices and
1711 * before your application terminates.
1712 * \param ctx the context to deinitialize, or NULL for the default context
1714 void API_EXPORTED libusb_exit(struct libusb_context *ctx)
1716 usbi_dbg("");
1717 USBI_GET_CONTEXT(ctx);
1719 /* if working with default context, only actually do the deinitialization
1720 * if we're the last user */
1721 if (ctx == usbi_default_context) {
1722 usbi_mutex_static_lock(&default_context_lock);
1723 if (--default_context_refcnt > 0) {
1724 usbi_dbg("not destroying default context");
1725 usbi_mutex_static_unlock(&default_context_lock);
1726 return;
1728 usbi_dbg("destroying default context");
1729 usbi_default_context = NULL;
1730 usbi_mutex_static_unlock(&default_context_lock);
1733 /* a little sanity check. doesn't bother with open_devs locking because
1734 * unless there is an application bug, nobody will be accessing this. */
1735 if (!list_empty(&ctx->open_devs))
1736 usbi_warn(ctx, "application left some devices open");
1738 usbi_io_exit(ctx);
1739 if (usbi_backend->exit)
1740 usbi_backend->exit();
1742 usbi_mutex_destroy(&ctx->open_devs_lock);
1743 usbi_mutex_destroy(&ctx->usb_devs_lock);
1744 free(ctx);
1747 /** \ingroup misc
1748 * Check at runtime if the loaded library has a given capability.
1750 * \param capability the \ref libusb_capability to check for
1751 * \returns 1 if the running library has the capability, 0 otherwise
1753 int API_EXPORTED libusb_has_capability(uint32_t capability)
1755 switch (capability) {
1756 case LIBUSB_CAP_HAS_CAPABILITY:
1757 return 1;
1759 return 0;
1762 /* this is defined in libusbi.h if needed */
1763 #ifdef LIBUSB_GETTIMEOFDAY_WIN32
1765 * gettimeofday
1766 * Implementation according to:
1767 * The Open Group Base Specifications Issue 6
1768 * IEEE Std 1003.1, 2004 Edition
1772 * THIS SOFTWARE IS NOT COPYRIGHTED
1774 * This source code is offered for use in the public domain. You may
1775 * use, modify or distribute it freely.
1777 * This code is distributed in the hope that it will be useful but
1778 * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
1779 * DISCLAIMED. This includes but is not limited to warranties of
1780 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1782 * Contributed by:
1783 * Danny Smith <dannysmith@users.sourceforge.net>
1786 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
1787 #define _W32_FT_OFFSET (116444736000000000)
1789 int usbi_gettimeofday(struct timeval *tp, void *tzp)
1791 union {
1792 unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
1793 FILETIME ft;
1794 } _now;
1795 UNUSED(tzp);
1797 if(tp) {
1798 #if defined(OS_WINCE)
1799 SYSTEMTIME st;
1800 GetSystemTime(&st);
1801 SystemTimeToFileTime(&st, &_now.ft);
1802 #else
1803 GetSystemTimeAsFileTime (&_now.ft);
1804 #endif
1805 tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
1806 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
1808 /* Always return 0 as per Open Group Base Specifications Issue 6.
1809 Do not set errno on error. */
1810 return 0;
1812 #endif
1814 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
1815 const char *function, const char *format, va_list args)
1817 const char *prefix = "";
1818 struct timeval now;
1819 int global_debug;
1820 static int has_debug_header_been_displayed = 0;
1822 #ifdef ENABLE_DEBUG_LOGGING
1823 global_debug = 1;
1824 UNUSED(ctx);
1825 #else
1826 USBI_GET_CONTEXT(ctx);
1827 if (ctx == NULL)
1828 return;
1829 global_debug = (ctx->debug == LIBUSB_LOG_LEVEL_DEBUG);
1830 if (!ctx->debug)
1831 return;
1832 if (level == LIBUSB_LOG_LEVEL_WARNING && ctx->debug < LIBUSB_LOG_LEVEL_WARNING)
1833 return;
1834 if (level == LIBUSB_LOG_LEVEL_INFO && ctx->debug < LIBUSB_LOG_LEVEL_INFO)
1835 return;
1836 if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx->debug < LIBUSB_LOG_LEVEL_DEBUG)
1837 return;
1838 #endif
1840 usbi_gettimeofday(&now, NULL);
1841 if ((global_debug) && (!has_debug_header_been_displayed)) {
1842 has_debug_header_been_displayed = 1;
1843 fprintf(stderr, "[timestamp] [threadID] facility level [function call] <message>\n");
1844 fprintf(stderr, "--------------------------------------------------------------------------------\n");
1846 if (now.tv_usec < timestamp_origin.tv_usec) {
1847 now.tv_sec--;
1848 now.tv_usec += 1000000;
1850 now.tv_sec -= timestamp_origin.tv_sec;
1851 now.tv_usec -= timestamp_origin.tv_usec;
1853 switch (level) {
1854 case LIBUSB_LOG_LEVEL_INFO:
1855 prefix = "info";
1856 break;
1857 case LIBUSB_LOG_LEVEL_WARNING:
1858 prefix = "warning";
1859 break;
1860 case LIBUSB_LOG_LEVEL_ERROR:
1861 prefix = "error";
1862 break;
1863 case LIBUSB_LOG_LEVEL_DEBUG:
1864 prefix = "debug";
1865 break;
1866 case LIBUSB_LOG_LEVEL_NONE:
1867 break;
1868 default:
1869 prefix = "unknown";
1870 break;
1873 if (global_debug) {
1874 fprintf(stderr, "[%2d.%06d] [%08x] libusbx: %s [%s] ",
1875 (int)now.tv_sec, (int)now.tv_usec, usbi_get_tid(), prefix, function);
1876 } else {
1877 fprintf(stderr, "libusbx: %s [%s] ", prefix, function);
1880 vfprintf(stderr, format, args);
1882 fprintf(stderr, "\n");
1885 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
1886 const char *function, const char *format, ...)
1888 va_list args;
1890 va_start (args, format);
1891 usbi_log_v(ctx, level, function, format, args);
1892 va_end (args);
1895 /** \ingroup misc
1896 * Returns a constant NULL-terminated string with the ASCII name of a libusb
1897 * error or transfer status code. The caller must not free() the returned
1898 * string.
1900 * \param error_code The \ref libusb_error or libusb_transfer_status code to
1901 * return the name of.
1902 * \returns The error name, or the string **UNKNOWN** if the value of
1903 * error_code is not a known error / status code.
1905 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
1907 switch (error_code) {
1908 case LIBUSB_ERROR_IO:
1909 return "LIBUSB_ERROR_IO";
1910 case LIBUSB_ERROR_INVALID_PARAM:
1911 return "LIBUSB_ERROR_INVALID_PARAM";
1912 case LIBUSB_ERROR_ACCESS:
1913 return "LIBUSB_ERROR_ACCESS";
1914 case LIBUSB_ERROR_NO_DEVICE:
1915 return "LIBUSB_ERROR_NO_DEVICE";
1916 case LIBUSB_ERROR_NOT_FOUND:
1917 return "LIBUSB_ERROR_NOT_FOUND";
1918 case LIBUSB_ERROR_BUSY:
1919 return "LIBUSB_ERROR_BUSY";
1920 case LIBUSB_ERROR_TIMEOUT:
1921 return "LIBUSB_ERROR_TIMEOUT";
1922 case LIBUSB_ERROR_OVERFLOW:
1923 return "LIBUSB_ERROR_OVERFLOW";
1924 case LIBUSB_ERROR_PIPE:
1925 return "LIBUSB_ERROR_PIPE";
1926 case LIBUSB_ERROR_INTERRUPTED:
1927 return "LIBUSB_ERROR_INTERRUPTED";
1928 case LIBUSB_ERROR_NO_MEM:
1929 return "LIBUSB_ERROR_NO_MEM";
1930 case LIBUSB_ERROR_NOT_SUPPORTED:
1931 return "LIBUSB_ERROR_NOT_SUPPORTED";
1932 case LIBUSB_ERROR_OTHER:
1933 return "LIBUSB_ERROR_OTHER";
1935 case LIBUSB_TRANSFER_ERROR:
1936 return "LIBUSB_TRANSFER_ERROR";
1937 case LIBUSB_TRANSFER_TIMED_OUT:
1938 return "LIBUSB_TRANSFER_TIMED_OUT";
1939 case LIBUSB_TRANSFER_CANCELLED:
1940 return "LIBUSB_TRANSFER_CANCELLED";
1941 case LIBUSB_TRANSFER_STALL:
1942 return "LIBUSB_TRANSFER_STALL";
1943 case LIBUSB_TRANSFER_NO_DEVICE:
1944 return "LIBUSB_TRANSFER_NO_DEVICE";
1945 case LIBUSB_TRANSFER_OVERFLOW:
1946 return "LIBUSB_TRANSFER_OVERFLOW";
1948 case 0:
1949 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
1950 default:
1951 return "**UNKNOWN**";
1955 /** \ingroup misc
1956 * Returns a pointer to const struct libusb_version with the version
1957 * (major, minor, micro, nano and rc) of the running library.
1959 DEFAULT_VISIBILITY
1960 const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
1962 return &libusb_version_internal;