WinCE: Post integration cleanup
[libusbx.git] / libusb / core.c
blobb3df73a6e336735ffdf6ed38008773a57128fac7
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 #ifdef HAVE_SYS_TYPES_H
29 #include <sys/types.h>
30 #endif
31 #ifdef HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
35 #include "libusbi.h"
37 #if defined(OS_LINUX)
38 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
39 #elif defined(OS_DARWIN)
40 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
41 #elif defined(OS_OPENBSD)
42 const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
43 #elif defined(OS_WINDOWS)
44 const struct usbi_os_backend * const usbi_backend = &windows_backend;
45 #elif defined(OS_WINCE)
46 const struct usbi_os_backend * const usbi_backend = &wince_backend;
47 #else
48 #error "Unsupported OS"
49 #endif
51 struct libusb_context *usbi_default_context = NULL;
52 const struct libusb_version libusb_version_internal =
53 { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
54 LIBUSB_RC, "http://libusbx.org" };
55 static int default_context_refcnt = 0;
56 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
57 static struct timeval timestamp_origin = { 0, 0 };
59 /**
60 * \mainpage libusbx-1.0 API Reference
62 * \section intro Introduction
64 * libusbx is an open source library that allows you to communicate with USB
65 * devices from userspace. For more info, see the
66 * <a href="http://libusbx.org">libusbx homepage</a>.
68 * This documentation is aimed at application developers wishing to
69 * communicate with USB peripherals from their own software. After reviewing
70 * this documentation, feedback and questions can be sent to the
71 * <a href="http://mailing-list.libusbx.org">libusbx-devel mailing list</a>.
73 * This documentation assumes knowledge of how to operate USB devices from
74 * a software standpoint (descriptors, configurations, interfaces, endpoints,
75 * control/bulk/interrupt/isochronous transfers, etc). Full information
76 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
77 * Specification</a> which is available for free download. You can probably
78 * find less verbose introductions by searching the web.
80 * \section features Library features
82 * - All transfer types supported (control/bulk/interrupt/isochronous)
83 * - 2 transfer interfaces:
84 * -# Synchronous (simple)
85 * -# Asynchronous (more complicated, but more powerful)
86 * - Thread safe (although the asynchronous interface means that you
87 * usually won't need to thread)
88 * - Lightweight with lean API
89 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
91 * \section gettingstarted Getting Started
93 * To begin reading the API documentation, start with the Modules page which
94 * links to the different categories of libusbx's functionality.
96 * One decision you will have to make is whether to use the synchronous
97 * or the asynchronous data transfer interface. The \ref io documentation
98 * provides some insight into this topic.
100 * Some example programs can be found in the libusbx source distribution under
101 * the "examples" subdirectory. The libusbx homepage includes a list of
102 * real-life project examples which use libusbx.
104 * \section errorhandling Error handling
106 * libusbx functions typically return 0 on success or a negative error code
107 * on failure. These negative error codes relate to LIBUSB_ERROR constants
108 * which are listed on the \ref misc "miscellaneous" documentation page.
110 * \section msglog Debug message logging
112 * libusbx uses stderr for all logging. By default, logging is set to NONE,
113 * which means that no output will be produced. However, unless the library
114 * has been compiled with logging disabled, then any application calls to
115 * libusb_set_debug(), or the setting of the environmental variable
116 * LIBUSB_DEBUG outside of the application, can result in logging being
117 * produced. Your application should therefore not close stderr, but instead
118 * direct it to the null device if its output is undesireable.
120 * The libusb_set_debug() function can be used to enable logging of certain
121 * messages. Under standard configuration, libusbx doesn't really log much
122 * so you are advised to use this function to enable all error/warning/
123 * informational messages. It will help debug problems with your software.
125 * The logged messages are unstructured. There is no one-to-one correspondence
126 * between messages being logged and success or failure return codes from
127 * libusbx functions. There is no format to the messages, so you should not
128 * try to capture or parse them. They are not and will not be localized.
129 * These messages are not intended to being passed to your application user;
130 * instead, you should interpret the error codes returned from libusbx functions
131 * and provide appropriate notification to the user. The messages are simply
132 * there to aid you as a programmer, and if you're confused because you're
133 * getting a strange error code from a libusbx function, enabling message
134 * logging may give you a suitable explanation.
136 * The LIBUSB_DEBUG environment variable can be used to enable message logging
137 * at run-time. This environment variable should be set to a log level number,
138 * which is interpreted the same as the libusb_set_debug() parameter. When this
139 * environment variable is set, the message logging verbosity level is fixed
140 * and libusb_set_debug() effectively does nothing.
142 * libusbx can be compiled without any logging functions, useful for embedded
143 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
144 * variable have no effects.
146 * libusbx can also be compiled with verbose debugging messages always. When
147 * the library is compiled in this way, all messages of all verbosities are
148 * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
149 * have no effects.
151 * \section remarks Other remarks
153 * libusbx does have imperfections. The \ref caveats "caveats" page attempts
154 * to document these.
158 * \page caveats Caveats
160 * \section devresets Device resets
162 * The libusb_reset_device() function allows you to reset a device. If your
163 * program has to call such a function, it should obviously be aware that
164 * the reset will cause device state to change (e.g. register values may be
165 * reset).
167 * The problem is that any other program could reset the device your program
168 * is working with, at any time. libusbx does not offer a mechanism to inform
169 * you when this has happened, so if someone else resets your device it will
170 * not be clear to your own program why the device state has changed.
172 * Ultimately, this is a limitation of writing drivers in userspace.
173 * Separation from the USB stack in the underlying kernel makes it difficult
174 * for the operating system to deliver such notifications to your program.
175 * The Linux kernel USB stack allows such reset notifications to be delivered
176 * to in-kernel USB drivers, but it is not clear how such notifications could
177 * be delivered to second-class drivers that live in userspace.
179 * \section blockonly Blocking-only functionality
181 * The functionality listed below is only available through synchronous,
182 * blocking functions. There are no asynchronous/non-blocking alternatives,
183 * and no clear ways of implementing these.
185 * - Configuration activation (libusb_set_configuration())
186 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
187 * - Releasing of interfaces (libusb_release_interface())
188 * - Clearing of halt/stall condition (libusb_clear_halt())
189 * - Device resets (libusb_reset_device())
191 * \section nohotplug No hotplugging
193 * libusbx-1.0 lacks functionality for providing notifications of when devices
194 * are added or removed. This functionality is planned to be implemented
195 * in a later version of libusbx.
197 * That said, there is basic disconnection handling for open device handles:
198 * - If there are ongoing transfers, libusbx's handle_events loop will detect
199 * disconnections and complete ongoing transfers with the
200 * LIBUSB_TRANSFER_NO_DEVICE status code.
201 * - Many functions such as libusb_set_configuration() return the special
202 * LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected.
204 * \section configsel Configuration selection and handling
206 * When libusbx presents a device handle to an application, there is a chance
207 * that the corresponding device may be in unconfigured state. For devices
208 * with multiple configurations, there is also a chance that the configuration
209 * currently selected is not the one that the application wants to use.
211 * The obvious solution is to add a call to libusb_set_configuration() early
212 * on during your device initialization routines, but there are caveats to
213 * be aware of:
214 * -# If the device is already in the desired configuration, calling
215 * libusb_set_configuration() using the same configuration value will cause
216 * a lightweight device reset. This may not be desirable behaviour.
217 * -# libusbx will be unable to change configuration if the device is in
218 * another configuration and other programs or drivers have claimed
219 * interfaces under that configuration.
220 * -# In the case where the desired configuration is already active, libusbx
221 * may not even be able to perform a lightweight device reset. For example,
222 * take my USB keyboard with fingerprint reader: I'm interested in driving
223 * the fingerprint reader interface through libusbx, but the kernel's
224 * USB-HID driver will almost always have claimed the keyboard interface.
225 * Because the kernel has claimed an interface, it is not even possible to
226 * perform the lightweight device reset, so libusb_set_configuration() will
227 * fail. (Luckily the device in question only has a single configuration.)
229 * One solution to some of the above problems is to consider the currently
230 * active configuration. If the configuration we want is already active, then
231 * we don't have to select any configuration:
232 \code
233 cfg = libusb_get_configuration(dev);
234 if (cfg != desired)
235 libusb_set_configuration(dev, desired);
236 \endcode
238 * This is probably suitable for most scenarios, but is inherently racy:
239 * another application or driver may change the selected configuration
240 * <em>after</em> the libusb_get_configuration() call.
242 * Even in cases where libusb_set_configuration() succeeds, consider that other
243 * applications or drivers may change configuration after your application
244 * calls libusb_set_configuration().
246 * One possible way to lock your device into a specific configuration is as
247 * follows:
248 * -# Set the desired configuration (or use the logic above to realise that
249 * it is already in the desired configuration)
250 * -# Claim the interface that you wish to use
251 * -# Check that the currently active configuration is the one that you want
252 * to use.
254 * The above method works because once an interface is claimed, no application
255 * or driver is able to select another configuration.
257 * \section earlycomp Early transfer completion
259 * NOTE: This section is currently Linux-centric. I am not sure if any of these
260 * considerations apply to Darwin or other platforms.
262 * When a transfer completes early (i.e. when less data is received/sent in
263 * any one packet than the transfer buffer allows for) then libusbx is designed
264 * to terminate the transfer immediately, not transferring or receiving any
265 * more data unless other transfers have been queued by the user.
267 * On legacy platforms, libusbx is unable to do this in all situations. After
268 * the incomplete packet occurs, "surplus" data may be transferred. For recent
269 * versions of libusbx, this information is kept (the data length of the
270 * transfer is updated) and, for device-to-host transfers, any surplus data was
271 * added to the buffer. Still, this is not a nice solution because it loses the
272 * information about the end of the short packet, and the user probably wanted
273 * that surplus data to arrive in the next logical transfer.
276 * \section zlp Zero length packets
278 * - libusbx is able to send a packet of zero length to an endpoint simply by
279 * submitting a transfer of zero length.
280 * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
281 * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
285 * \page contexts Contexts
287 * It is possible that libusbx may be used simultaneously from two independent
288 * libraries linked into the same executable. For example, if your application
289 * has a plugin-like system which allows the user to dynamically load a range
290 * of modules into your program, it is feasible that two independently
291 * developed modules may both use libusbx.
293 * libusbx is written to allow for these multiple user scenarios. The two
294 * "instances" of libusbx will not interfere: libusb_set_debug() calls
295 * from one user will not affect the same settings for other users, other
296 * users can continue using libusbx after one of them calls libusb_exit(), etc.
298 * This is made possible through libusbx's <em>context</em> concept. When you
299 * call libusb_init(), you are (optionally) given a context. You can then pass
300 * this context pointer back into future libusbx functions.
302 * In order to keep things simple for more simplistic applications, it is
303 * legal to pass NULL to all functions requiring a context pointer (as long as
304 * you're sure no other code will attempt to use libusbx from the same process).
305 * When you pass NULL, the default context will be used. The default context
306 * is created the first time a process calls libusb_init() when no other
307 * context is alive. Contexts are destroyed during libusb_exit().
309 * The default context is reference-counted and can be shared. That means that
310 * if libusb_init(NULL) is called twice within the same process, the two
311 * users end up sharing the same context. The deinitialization and freeing of
312 * the default context will only happen when the last user calls libusb_exit().
313 * In other words, the default context is created and initialized when its
314 * reference count goes from 0 to 1, and is deinitialized and destroyed when
315 * its reference count goes from 1 to 0.
317 * You may be wondering why only a subset of libusbx functions require a
318 * context pointer in their function definition. Internally, libusbx stores
319 * context pointers in other objects (e.g. libusb_device instances) and hence
320 * can infer the context from those objects.
324 * @defgroup lib Library initialization/deinitialization
325 * This page details how to initialize and deinitialize libusbx. Initialization
326 * must be performed before using any libusbx functionality, and similarly you
327 * must not call any libusbx functions after deinitialization.
331 * @defgroup dev Device handling and enumeration
332 * The functionality documented below is designed to help with the following
333 * operations:
334 * - Enumerating the USB devices currently attached to the system
335 * - Choosing a device to operate from your software
336 * - Opening and closing the chosen device
338 * \section nutshell In a nutshell...
340 * The description below really makes things sound more complicated than they
341 * actually are. The following sequence of function calls will be suitable
342 * for almost all scenarios and does not require you to have such a deep
343 * understanding of the resource management issues:
344 * \code
345 // discover devices
346 libusb_device **list;
347 libusb_device *found = NULL;
348 ssize_t cnt = libusb_get_device_list(NULL, &list);
349 ssize_t i = 0;
350 int err = 0;
351 if (cnt < 0)
352 error();
354 for (i = 0; i < cnt; i++) {
355 libusb_device *device = list[i];
356 if (is_interesting(device)) {
357 found = device;
358 break;
362 if (found) {
363 libusb_device_handle *handle;
365 err = libusb_open(found, &handle);
366 if (err)
367 error();
368 // etc
371 libusb_free_device_list(list, 1);
372 \endcode
374 * The two important points:
375 * - You asked libusb_free_device_list() to unreference the devices (2nd
376 * parameter)
377 * - You opened the device before freeing the list and unreferencing the
378 * devices
380 * If you ended up with a handle, you can now proceed to perform I/O on the
381 * device.
383 * \section devshandles Devices and device handles
384 * libusbx has a concept of a USB device, represented by the
385 * \ref libusb_device opaque type. A device represents a USB device that
386 * is currently or was previously connected to the system. Using a reference
387 * to a device, you can determine certain information about the device (e.g.
388 * you can read the descriptor data).
390 * The libusb_get_device_list() function can be used to obtain a list of
391 * devices currently connected to the system. This is known as device
392 * discovery.
394 * Just because you have a reference to a device does not mean it is
395 * necessarily usable. The device may have been unplugged, you may not have
396 * permission to operate such device, or another program or driver may be
397 * using the device.
399 * When you've found a device that you'd like to operate, you must ask
400 * libusbx to open the device using the libusb_open() function. Assuming
401 * success, libusbx then returns you a <em>device handle</em>
402 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
403 * operate on the handle rather than the original device pointer.
405 * \section devref Device discovery and reference counting
407 * Device discovery (i.e. calling libusb_get_device_list()) returns a
408 * freshly-allocated list of devices. The list itself must be freed when
409 * you are done with it. libusbx also needs to know when it is OK to free
410 * the contents of the list - the devices themselves.
412 * To handle these issues, libusbx provides you with two separate items:
413 * - A function to free the list itself
414 * - A reference counting system for the devices inside
416 * New devices presented by the libusb_get_device_list() function all have a
417 * reference count of 1. You can increase and decrease reference count using
418 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
419 * its reference count reaches 0.
421 * With the above information in mind, the process of opening a device can
422 * be viewed as follows:
423 * -# Discover devices using libusb_get_device_list().
424 * -# Choose the device that you want to operate, and call libusb_open().
425 * -# Unref all devices in the discovered device list.
426 * -# Free the discovered device list.
428 * The order is important - you must not unreference the device before
429 * attempting to open it, because unreferencing it may destroy the device.
431 * For convenience, the libusb_free_device_list() function includes a
432 * parameter to optionally unreference all the devices in the list before
433 * freeing the list itself. This combines steps 3 and 4 above.
435 * As an implementation detail, libusb_open() actually adds a reference to
436 * the device in question. This is because the device remains available
437 * through the handle via libusb_get_device(). The reference is deleted during
438 * libusb_close().
441 /** @defgroup misc Miscellaneous */
443 /* we traverse usbfs without knowing how many devices we are going to find.
444 * so we create this discovered_devs model which is similar to a linked-list
445 * which grows when required. it can be freed once discovery has completed,
446 * eliminating the need for a list node in the libusb_device structure
447 * itself. */
448 #define DISCOVERED_DEVICES_SIZE_STEP 8
450 static struct discovered_devs *discovered_devs_alloc(void)
452 struct discovered_devs *ret =
453 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
455 if (ret) {
456 ret->len = 0;
457 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
459 return ret;
462 /* append a device to the discovered devices collection. may realloc itself,
463 * returning new discdevs. returns NULL on realloc failure. */
464 struct discovered_devs *discovered_devs_append(
465 struct discovered_devs *discdevs, struct libusb_device *dev)
467 size_t len = discdevs->len;
468 size_t capacity;
470 /* if there is space, just append the device */
471 if (len < discdevs->capacity) {
472 discdevs->devices[len] = libusb_ref_device(dev);
473 discdevs->len++;
474 return discdevs;
477 /* exceeded capacity, need to grow */
478 usbi_dbg("need to increase capacity");
479 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
480 discdevs = usbi_reallocf(discdevs,
481 sizeof(*discdevs) + (sizeof(void *) * capacity));
482 if (discdevs) {
483 discdevs->capacity = capacity;
484 discdevs->devices[len] = libusb_ref_device(dev);
485 discdevs->len++;
488 return discdevs;
491 static void discovered_devs_free(struct discovered_devs *discdevs)
493 size_t i;
495 for (i = 0; i < discdevs->len; i++)
496 libusb_unref_device(discdevs->devices[i]);
498 free(discdevs);
501 /* Allocate a new device with a specific session ID. The returned device has
502 * a reference count of 1. */
503 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
504 unsigned long session_id)
506 size_t priv_size = usbi_backend->device_priv_size;
507 struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
508 int r;
510 if (!dev)
511 return NULL;
513 r = usbi_mutex_init(&dev->lock, NULL);
514 if (r) {
515 free(dev);
516 return NULL;
519 dev->ctx = ctx;
520 dev->refcnt = 1;
521 dev->session_data = session_id;
522 dev->speed = LIBUSB_SPEED_UNKNOWN;
523 memset(&dev->os_priv, 0, priv_size);
525 usbi_mutex_lock(&ctx->usb_devs_lock);
526 list_add(&dev->list, &ctx->usb_devs);
527 usbi_mutex_unlock(&ctx->usb_devs_lock);
528 return dev;
531 /* Perform some final sanity checks on a newly discovered device. If this
532 * function fails (negative return code), the device should not be added
533 * to the discovered device list. */
534 int usbi_sanitize_device(struct libusb_device *dev)
536 int r;
537 unsigned char raw_desc[DEVICE_DESC_LENGTH];
538 uint8_t num_configurations;
539 int host_endian;
541 r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
542 if (r < 0)
543 return r;
545 num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
546 if (num_configurations > USB_MAXCONFIG) {
547 usbi_err(DEVICE_CTX(dev), "too many configurations");
548 return LIBUSB_ERROR_IO;
549 } else if (0 == num_configurations)
550 usbi_dbg("zero configurations, maybe an unauthorized device");
552 dev->num_configurations = num_configurations;
553 return 0;
556 /* Examine libusbx's internal list of known devices, looking for one with
557 * a specific session ID. Returns the matching device if it was found, and
558 * NULL otherwise. */
559 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
560 unsigned long session_id)
562 struct libusb_device *dev;
563 struct libusb_device *ret = NULL;
565 usbi_mutex_lock(&ctx->usb_devs_lock);
566 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
567 if (dev->session_data == session_id) {
568 ret = dev;
569 break;
571 usbi_mutex_unlock(&ctx->usb_devs_lock);
573 return ret;
576 /** @ingroup dev
577 * Returns a list of USB devices currently attached to the system. This is
578 * your entry point into finding a USB device to operate.
580 * You are expected to unreference all the devices when you are done with
581 * them, and then free the list with libusb_free_device_list(). Note that
582 * libusb_free_device_list() can unref all the devices for you. Be careful
583 * not to unreference a device you are about to open until after you have
584 * opened it.
586 * This return value of this function indicates the number of devices in
587 * the resultant list. The list is actually one element larger, as it is
588 * NULL-terminated.
590 * \param ctx the context to operate on, or NULL for the default context
591 * \param list output location for a list of devices. Must be later freed with
592 * libusb_free_device_list().
593 * \returns the number of devices in the outputted list, or any
594 * \ref libusb_error according to errors encountered by the backend.
596 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
597 libusb_device ***list)
599 struct discovered_devs *discdevs = discovered_devs_alloc();
600 struct libusb_device **ret;
601 int r = 0;
602 ssize_t i, len;
603 USBI_GET_CONTEXT(ctx);
604 usbi_dbg("");
606 if (!discdevs)
607 return LIBUSB_ERROR_NO_MEM;
609 r = usbi_backend->get_device_list(ctx, &discdevs);
610 if (r < 0) {
611 len = r;
612 goto out;
615 /* convert discovered_devs into a list */
616 len = discdevs->len;
617 ret = calloc(len + 1, sizeof(struct libusb_device *));
618 if (!ret) {
619 len = LIBUSB_ERROR_NO_MEM;
620 goto out;
623 ret[len] = NULL;
624 for (i = 0; i < len; i++) {
625 struct libusb_device *dev = discdevs->devices[i];
626 ret[i] = libusb_ref_device(dev);
628 *list = ret;
630 out:
631 discovered_devs_free(discdevs);
632 return len;
635 /** \ingroup dev
636 * Frees a list of devices previously discovered using
637 * libusb_get_device_list(). If the unref_devices parameter is set, the
638 * reference count of each device in the list is decremented by 1.
639 * \param list the list to free
640 * \param unref_devices whether to unref the devices in the list
642 void API_EXPORTED libusb_free_device_list(libusb_device **list,
643 int unref_devices)
645 if (!list)
646 return;
648 if (unref_devices) {
649 int i = 0;
650 struct libusb_device *dev;
652 while ((dev = list[i++]) != NULL)
653 libusb_unref_device(dev);
655 free(list);
658 /** \ingroup dev
659 * Get the number of the bus that a device is connected to.
660 * \param dev a device
661 * \returns the bus number
663 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
665 return dev->bus_number;
668 /** \ingroup dev
669 * Get the number of the port that a device is connected to
670 * \param dev a device
671 * \returns the port number (0 if not available)
673 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
675 return dev->port_number;
678 /** \ingroup dev
679 * Get the list of all port numbers from root for the specified device
680 * \param ctx the context to operate on, or NULL for the default context
681 * \param dev a device
682 * \param path the array that should contain the port numbers
683 * \param path_len the maximum length of the array. As per the USB 3.0
684 * specs, the current maximum limit for the depth is 7.
685 * \returns the number of elements filled
686 * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
688 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t* path, uint8_t path_len)
690 int i = path_len;
691 ssize_t r;
692 struct libusb_device **devs = NULL;
694 /* The device needs to be open, else the parents may have been destroyed */
695 r = libusb_get_device_list(ctx, &devs);
696 if (r < 0)
697 return (int)r;
699 while(dev) {
700 // HCDs can be listed as devices and would have port #0
701 // TODO: see how the other backends want to implement HCDs as parents
702 if (dev->port_number == 0)
703 break;
704 i--;
705 if (i < 0) {
706 libusb_free_device_list(devs, 1);
707 return LIBUSB_ERROR_OVERFLOW;
709 path[i] = dev->port_number;
710 dev = dev->parent_dev;
712 libusb_free_device_list(devs, 1);
713 memmove(path, &path[i], path_len-i);
714 return path_len-i;
717 /** \ingroup dev
718 * Get the the parent from the specified device [EXPERIMENTAL]
719 * \param dev a device
720 * \returns the device parent or NULL if not available
721 * You should issue a libusb_get_device_list() before calling this
722 * function and make sure that you only access the parent before issuing
723 * libusb_free_device_list(). The reason is that libusbx currently does
724 * not maintain a permanent list of device instances, and therefore can
725 * only guarantee that parents are fully instantiated within a
726 * libusb_get_device_list() - libusb_free_device_list() block.
728 DEFAULT_VISIBILITY
729 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
731 return dev->parent_dev;
734 /** \ingroup dev
735 * Get the address of the device on the bus it is connected to.
736 * \param dev a device
737 * \returns the device address
739 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
741 return dev->device_address;
744 /** \ingroup dev
745 * Get the negotiated connection speed for a device.
746 * \param dev a device
747 * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
748 * the OS doesn't know or doesn't support returning the negotiated speed.
750 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
752 return dev->speed;
755 static const struct libusb_endpoint_descriptor *find_endpoint(
756 struct libusb_config_descriptor *config, unsigned char endpoint)
758 int iface_idx;
759 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
760 const struct libusb_interface *iface = &config->interface[iface_idx];
761 int altsetting_idx;
763 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
764 altsetting_idx++) {
765 const struct libusb_interface_descriptor *altsetting
766 = &iface->altsetting[altsetting_idx];
767 int ep_idx;
769 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
770 const struct libusb_endpoint_descriptor *ep =
771 &altsetting->endpoint[ep_idx];
772 if (ep->bEndpointAddress == endpoint)
773 return ep;
777 return NULL;
780 /** \ingroup dev
781 * Convenience function to retrieve the wMaxPacketSize value for a particular
782 * endpoint in the active device configuration.
784 * This function was originally intended to be of assistance when setting up
785 * isochronous transfers, but a design mistake resulted in this function
786 * instead. It simply returns the wMaxPacketSize value without considering
787 * its contents. If you're dealing with isochronous transfers, you probably
788 * want libusb_get_max_iso_packet_size() instead.
790 * \param dev a device
791 * \param endpoint address of the endpoint in question
792 * \returns the wMaxPacketSize value
793 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
794 * \returns LIBUSB_ERROR_OTHER on other failure
796 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
797 unsigned char endpoint)
799 struct libusb_config_descriptor *config;
800 const struct libusb_endpoint_descriptor *ep;
801 int r;
803 r = libusb_get_active_config_descriptor(dev, &config);
804 if (r < 0) {
805 usbi_err(DEVICE_CTX(dev),
806 "could not retrieve active config descriptor");
807 return LIBUSB_ERROR_OTHER;
810 ep = find_endpoint(config, endpoint);
811 if (!ep)
812 return LIBUSB_ERROR_NOT_FOUND;
814 r = ep->wMaxPacketSize;
815 libusb_free_config_descriptor(config);
816 return r;
819 /** \ingroup dev
820 * Calculate the maximum packet size which a specific endpoint is capable is
821 * sending or receiving in the duration of 1 microframe
823 * Only the active configution is examined. The calculation is based on the
824 * wMaxPacketSize field in the endpoint descriptor as described in section
825 * 9.6.6 in the USB 2.0 specifications.
827 * If acting on an isochronous or interrupt endpoint, this function will
828 * multiply the value found in bits 0:10 by the number of transactions per
829 * microframe (determined by bits 11:12). Otherwise, this function just
830 * returns the numeric value found in bits 0:10.
832 * This function is useful for setting up isochronous transfers, for example
833 * you might pass the return value from this function to
834 * libusb_set_iso_packet_lengths() in order to set the length field of every
835 * isochronous packet in a transfer.
837 * Since v1.0.3.
839 * \param dev a device
840 * \param endpoint address of the endpoint in question
841 * \returns the maximum packet size which can be sent/received on this endpoint
842 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
843 * \returns LIBUSB_ERROR_OTHER on other failure
845 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
846 unsigned char endpoint)
848 struct libusb_config_descriptor *config;
849 const struct libusb_endpoint_descriptor *ep;
850 enum libusb_transfer_type ep_type;
851 uint16_t val;
852 int r;
854 r = libusb_get_active_config_descriptor(dev, &config);
855 if (r < 0) {
856 usbi_err(DEVICE_CTX(dev),
857 "could not retrieve active config descriptor");
858 return LIBUSB_ERROR_OTHER;
861 ep = find_endpoint(config, endpoint);
862 if (!ep)
863 return LIBUSB_ERROR_NOT_FOUND;
865 val = ep->wMaxPacketSize;
866 ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
867 libusb_free_config_descriptor(config);
869 r = val & 0x07ff;
870 if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
871 || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
872 r *= (1 + ((val >> 11) & 3));
873 return r;
876 /** \ingroup dev
877 * Increment the reference count of a device.
878 * \param dev the device to reference
879 * \returns the same device
881 DEFAULT_VISIBILITY
882 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
884 usbi_mutex_lock(&dev->lock);
885 dev->refcnt++;
886 usbi_mutex_unlock(&dev->lock);
887 return dev;
890 /** \ingroup dev
891 * Decrement the reference count of a device. If the decrement operation
892 * causes the reference count to reach zero, the device shall be destroyed.
893 * \param dev the device to unreference
895 void API_EXPORTED libusb_unref_device(libusb_device *dev)
897 int refcnt;
899 if (!dev)
900 return;
902 usbi_mutex_lock(&dev->lock);
903 refcnt = --dev->refcnt;
904 usbi_mutex_unlock(&dev->lock);
906 if (refcnt == 0) {
907 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
909 if (usbi_backend->destroy_device)
910 usbi_backend->destroy_device(dev);
912 usbi_mutex_lock(&dev->ctx->usb_devs_lock);
913 list_del(&dev->list);
914 usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
916 usbi_mutex_destroy(&dev->lock);
917 free(dev);
922 * Interrupt the iteration of the event handling thread, so that it picks
923 * up the new fd.
925 void usbi_fd_notification(struct libusb_context *ctx)
927 unsigned char dummy = 1;
928 ssize_t r;
930 if (ctx == NULL)
931 return;
933 /* record that we are messing with poll fds */
934 usbi_mutex_lock(&ctx->pollfd_modify_lock);
935 ctx->pollfd_modify++;
936 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
938 /* write some data on control pipe to interrupt event handlers */
939 r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
940 if (r <= 0) {
941 usbi_warn(ctx, "internal signalling write failed");
942 usbi_mutex_lock(&ctx->pollfd_modify_lock);
943 ctx->pollfd_modify--;
944 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
945 return;
948 /* take event handling lock */
949 libusb_lock_events(ctx);
951 /* read the dummy data */
952 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
953 if (r <= 0)
954 usbi_warn(ctx, "internal signalling read failed");
956 /* we're done with modifying poll fds */
957 usbi_mutex_lock(&ctx->pollfd_modify_lock);
958 ctx->pollfd_modify--;
959 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
961 /* Release event handling lock and wake up event waiters */
962 libusb_unlock_events(ctx);
965 /** \ingroup dev
966 * Open a device and obtain a device handle. A handle allows you to perform
967 * I/O on the device in question.
969 * Internally, this function adds a reference to the device and makes it
970 * available to you through libusb_get_device(). This reference is removed
971 * during libusb_close().
973 * This is a non-blocking function; no requests are sent over the bus.
975 * \param dev the device to open
976 * \param handle output location for the returned device handle pointer. Only
977 * populated when the return code is 0.
978 * \returns 0 on success
979 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
980 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
981 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
982 * \returns another LIBUSB_ERROR code on other failure
984 int API_EXPORTED libusb_open(libusb_device *dev,
985 libusb_device_handle **handle)
987 struct libusb_context *ctx = DEVICE_CTX(dev);
988 struct libusb_device_handle *_handle;
989 size_t priv_size = usbi_backend->device_handle_priv_size;
990 int r;
991 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
993 _handle = malloc(sizeof(*_handle) + priv_size);
994 if (!_handle)
995 return LIBUSB_ERROR_NO_MEM;
997 r = usbi_mutex_init(&_handle->lock, NULL);
998 if (r) {
999 free(_handle);
1000 return LIBUSB_ERROR_OTHER;
1003 _handle->dev = libusb_ref_device(dev);
1004 _handle->claimed_interfaces = 0;
1005 memset(&_handle->os_priv, 0, priv_size);
1007 r = usbi_backend->open(_handle);
1008 if (r < 0) {
1009 usbi_dbg("could not open device: %s", libusb_error_name(r));
1010 libusb_unref_device(dev);
1011 usbi_mutex_destroy(&_handle->lock);
1012 free(_handle);
1013 return r;
1016 usbi_mutex_lock(&ctx->open_devs_lock);
1017 list_add(&_handle->list, &ctx->open_devs);
1018 usbi_mutex_unlock(&ctx->open_devs_lock);
1019 *handle = _handle;
1021 /* At this point, we want to interrupt any existing event handlers so
1022 * that they realise the addition of the new device's poll fd. One
1023 * example when this is desirable is if the user is running a separate
1024 * dedicated libusbx events handling thread, which is running with a long
1025 * or infinite timeout. We want to interrupt that iteration of the loop,
1026 * so that it picks up the new fd, and then continues. */
1027 usbi_fd_notification(ctx);
1029 return 0;
1032 /** \ingroup dev
1033 * Convenience function for finding a device with a particular
1034 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1035 * for those scenarios where you are using libusbx to knock up a quick test
1036 * application - it allows you to avoid calling libusb_get_device_list() and
1037 * worrying about traversing/freeing the list.
1039 * This function has limitations and is hence not intended for use in real
1040 * applications: if multiple devices have the same IDs it will only
1041 * give you the first one, etc.
1043 * \param ctx the context to operate on, or NULL for the default context
1044 * \param vendor_id the idVendor value to search for
1045 * \param product_id the idProduct value to search for
1046 * \returns a handle for the first found device, or NULL on error or if the
1047 * device could not be found. */
1048 DEFAULT_VISIBILITY
1049 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1050 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1052 struct libusb_device **devs;
1053 struct libusb_device *found = NULL;
1054 struct libusb_device *dev;
1055 struct libusb_device_handle *handle = NULL;
1056 size_t i = 0;
1057 int r;
1059 if (libusb_get_device_list(ctx, &devs) < 0)
1060 return NULL;
1062 while ((dev = devs[i++]) != NULL) {
1063 struct libusb_device_descriptor desc;
1064 r = libusb_get_device_descriptor(dev, &desc);
1065 if (r < 0)
1066 goto out;
1067 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1068 found = dev;
1069 break;
1073 if (found) {
1074 r = libusb_open(found, &handle);
1075 if (r < 0)
1076 handle = NULL;
1079 out:
1080 libusb_free_device_list(devs, 1);
1081 return handle;
1084 static void do_close(struct libusb_context *ctx,
1085 struct libusb_device_handle *dev_handle)
1087 struct usbi_transfer *itransfer;
1088 struct usbi_transfer *tmp;
1090 libusb_lock_events(ctx);
1092 /* remove any transfers in flight that are for this device */
1093 usbi_mutex_lock(&ctx->flying_transfers_lock);
1095 /* safe iteration because transfers may be being deleted */
1096 list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
1097 struct libusb_transfer *transfer =
1098 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1100 if (transfer->dev_handle != dev_handle)
1101 continue;
1103 if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1104 usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1106 if (itransfer->flags & USBI_TRANSFER_CANCELLING)
1107 usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1108 else
1109 usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1112 /* remove from the list of in-flight transfers and make sure
1113 * we don't accidentally use the device handle in the future
1114 * (or that such accesses will be easily caught and identified as a crash)
1116 usbi_mutex_lock(&itransfer->lock);
1117 list_del(&itransfer->list);
1118 transfer->dev_handle = NULL;
1119 usbi_mutex_unlock(&itransfer->lock);
1121 /* it is up to the user to free up the actual transfer struct. this is
1122 * just making sure that we don't attempt to process the transfer after
1123 * the device handle is invalid
1125 usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
1126 transfer, dev_handle);
1128 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1130 libusb_unlock_events(ctx);
1132 usbi_mutex_lock(&ctx->open_devs_lock);
1133 list_del(&dev_handle->list);
1134 usbi_mutex_unlock(&ctx->open_devs_lock);
1136 usbi_backend->close(dev_handle);
1137 libusb_unref_device(dev_handle->dev);
1138 usbi_mutex_destroy(&dev_handle->lock);
1139 free(dev_handle);
1142 /** \ingroup dev
1143 * Close a device handle. Should be called on all open handles before your
1144 * application exits.
1146 * Internally, this function destroys the reference that was added by
1147 * libusb_open() on the given device.
1149 * This is a non-blocking function; no requests are sent over the bus.
1151 * \param dev_handle the handle to close
1153 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1155 struct libusb_context *ctx;
1156 unsigned char dummy = 1;
1157 ssize_t r;
1159 if (!dev_handle)
1160 return;
1161 usbi_dbg("");
1163 ctx = HANDLE_CTX(dev_handle);
1165 /* Similarly to libusb_open(), we want to interrupt all event handlers
1166 * at this point. More importantly, we want to perform the actual close of
1167 * the device while holding the event handling lock (preventing any other
1168 * thread from doing event handling) because we will be removing a file
1169 * descriptor from the polling loop. */
1171 /* record that we are messing with poll fds */
1172 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1173 ctx->pollfd_modify++;
1174 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1176 /* write some data on control pipe to interrupt event handlers */
1177 r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1178 if (r <= 0) {
1179 usbi_warn(ctx, "internal signalling write failed, closing anyway");
1180 do_close(ctx, dev_handle);
1181 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1182 ctx->pollfd_modify--;
1183 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1184 return;
1187 /* take event handling lock */
1188 libusb_lock_events(ctx);
1190 /* read the dummy data */
1191 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1192 if (r <= 0)
1193 usbi_warn(ctx, "internal signalling read failed, closing anyway");
1195 /* Close the device */
1196 do_close(ctx, dev_handle);
1198 /* we're done with modifying poll fds */
1199 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1200 ctx->pollfd_modify--;
1201 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1203 /* Release event handling lock and wake up event waiters */
1204 libusb_unlock_events(ctx);
1207 /** \ingroup dev
1208 * Get the underlying device for a handle. This function does not modify
1209 * the reference count of the returned device, so do not feel compelled to
1210 * unreference it when you are done.
1211 * \param dev_handle a device handle
1212 * \returns the underlying device
1214 DEFAULT_VISIBILITY
1215 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1217 return dev_handle->dev;
1220 /** \ingroup dev
1221 * Determine the bConfigurationValue of the currently active configuration.
1223 * You could formulate your own control request to obtain this information,
1224 * but this function has the advantage that it may be able to retrieve the
1225 * information from operating system caches (no I/O involved).
1227 * If the OS does not cache this information, then this function will block
1228 * while a control transfer is submitted to retrieve the information.
1230 * This function will return a value of 0 in the <tt>config</tt> output
1231 * parameter if the device is in unconfigured state.
1233 * \param dev a device handle
1234 * \param config output location for the bConfigurationValue of the active
1235 * configuration (only valid for return code 0)
1236 * \returns 0 on success
1237 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1238 * \returns another LIBUSB_ERROR code on other failure
1240 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
1241 int *config)
1243 int r = LIBUSB_ERROR_NOT_SUPPORTED;
1245 usbi_dbg("");
1246 if (usbi_backend->get_configuration)
1247 r = usbi_backend->get_configuration(dev, config);
1249 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1250 uint8_t tmp = 0;
1251 usbi_dbg("falling back to control message");
1252 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1253 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1254 if (r == 0) {
1255 usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
1256 r = LIBUSB_ERROR_IO;
1257 } else if (r == 1) {
1258 r = 0;
1259 *config = tmp;
1260 } else {
1261 usbi_dbg("control failed, error %d", r);
1265 if (r == 0)
1266 usbi_dbg("active config %d", *config);
1268 return r;
1271 /** \ingroup dev
1272 * Set the active configuration for a device.
1274 * The operating system may or may not have already set an active
1275 * configuration on the device. It is up to your application to ensure the
1276 * correct configuration is selected before you attempt to claim interfaces
1277 * and perform other operations.
1279 * If you call this function on a device already configured with the selected
1280 * configuration, then this function will act as a lightweight device reset:
1281 * it will issue a SET_CONFIGURATION request using the current configuration,
1282 * causing most USB-related device state to be reset (altsetting reset to zero,
1283 * endpoint halts cleared, toggles reset).
1285 * You cannot change/reset configuration if your application has claimed
1286 * interfaces - you should free them with libusb_release_interface() first.
1287 * You cannot change/reset configuration if other applications or drivers have
1288 * claimed interfaces.
1290 * A configuration value of -1 will put the device in unconfigured state.
1291 * The USB specifications state that a configuration value of 0 does this,
1292 * however buggy devices exist which actually have a configuration 0.
1294 * You should always use this function rather than formulating your own
1295 * SET_CONFIGURATION control request. This is because the underlying operating
1296 * system needs to know when such changes happen.
1298 * This is a blocking function.
1300 * \param dev a device handle
1301 * \param configuration the bConfigurationValue of the configuration you
1302 * wish to activate, or -1 if you wish to put the device in unconfigured state
1303 * \returns 0 on success
1304 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1305 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1306 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1307 * \returns another LIBUSB_ERROR code on other failure
1309 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
1310 int configuration)
1312 usbi_dbg("configuration %d", configuration);
1313 return usbi_backend->set_configuration(dev, configuration);
1316 /** \ingroup dev
1317 * Claim an interface on a given device handle. You must claim the interface
1318 * you wish to use before you can perform I/O on any of its endpoints.
1320 * It is legal to attempt to claim an already-claimed interface, in which
1321 * case libusbx just returns 0 without doing anything.
1323 * Claiming of interfaces is a purely logical operation; it does not cause
1324 * any requests to be sent over the bus. Interface claiming is used to
1325 * instruct the underlying operating system that your application wishes
1326 * to take ownership of the interface.
1328 * This is a non-blocking function.
1330 * \param dev a device handle
1331 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1332 * wish to claim
1333 * \returns 0 on success
1334 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1335 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1336 * interface
1337 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1338 * \returns a LIBUSB_ERROR code on other failure
1340 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
1341 int interface_number)
1343 int r = 0;
1345 usbi_dbg("interface %d", interface_number);
1346 if (interface_number >= USB_MAXINTERFACES)
1347 return LIBUSB_ERROR_INVALID_PARAM;
1349 usbi_mutex_lock(&dev->lock);
1350 if (dev->claimed_interfaces & (1 << interface_number))
1351 goto out;
1353 r = usbi_backend->claim_interface(dev, interface_number);
1354 if (r == 0)
1355 dev->claimed_interfaces |= 1 << interface_number;
1357 out:
1358 usbi_mutex_unlock(&dev->lock);
1359 return r;
1362 /** \ingroup dev
1363 * Release an interface previously claimed with libusb_claim_interface(). You
1364 * should release all claimed interfaces before closing a device handle.
1366 * This is a blocking function. A SET_INTERFACE control request will be sent
1367 * to the device, resetting interface state to the first alternate setting.
1369 * \param dev a device handle
1370 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1371 * previously-claimed interface
1372 * \returns 0 on success
1373 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1374 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1375 * \returns another LIBUSB_ERROR code on other failure
1377 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
1378 int interface_number)
1380 int r;
1382 usbi_dbg("interface %d", interface_number);
1383 if (interface_number >= USB_MAXINTERFACES)
1384 return LIBUSB_ERROR_INVALID_PARAM;
1386 usbi_mutex_lock(&dev->lock);
1387 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1388 r = LIBUSB_ERROR_NOT_FOUND;
1389 goto out;
1392 r = usbi_backend->release_interface(dev, interface_number);
1393 if (r == 0)
1394 dev->claimed_interfaces &= ~(1 << interface_number);
1396 out:
1397 usbi_mutex_unlock(&dev->lock);
1398 return r;
1401 /** \ingroup dev
1402 * Activate an alternate setting for an interface. The interface must have
1403 * been previously claimed with libusb_claim_interface().
1405 * You should always use this function rather than formulating your own
1406 * SET_INTERFACE control request. This is because the underlying operating
1407 * system needs to know when such changes happen.
1409 * This is a blocking function.
1411 * \param dev a device handle
1412 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1413 * previously-claimed interface
1414 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1415 * setting to activate
1416 * \returns 0 on success
1417 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1418 * requested alternate setting does not exist
1419 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1420 * \returns another LIBUSB_ERROR code on other failure
1422 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
1423 int interface_number, int alternate_setting)
1425 usbi_dbg("interface %d altsetting %d",
1426 interface_number, alternate_setting);
1427 if (interface_number >= USB_MAXINTERFACES)
1428 return LIBUSB_ERROR_INVALID_PARAM;
1430 usbi_mutex_lock(&dev->lock);
1431 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1432 usbi_mutex_unlock(&dev->lock);
1433 return LIBUSB_ERROR_NOT_FOUND;
1435 usbi_mutex_unlock(&dev->lock);
1437 return usbi_backend->set_interface_altsetting(dev, interface_number,
1438 alternate_setting);
1441 /** \ingroup dev
1442 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1443 * are unable to receive or transmit data until the halt condition is stalled.
1445 * You should cancel all pending transfers before attempting to clear the halt
1446 * condition.
1448 * This is a blocking function.
1450 * \param dev a device handle
1451 * \param endpoint the endpoint to clear halt status
1452 * \returns 0 on success
1453 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1454 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1455 * \returns another LIBUSB_ERROR code on other failure
1457 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
1458 unsigned char endpoint)
1460 usbi_dbg("endpoint %x", endpoint);
1461 return usbi_backend->clear_halt(dev, endpoint);
1464 /** \ingroup dev
1465 * Perform a USB port reset to reinitialize a device. The system will attempt
1466 * to restore the previous configuration and alternate settings after the
1467 * reset has completed.
1469 * If the reset fails, the descriptors change, or the previous state cannot be
1470 * restored, the device will appear to be disconnected and reconnected. This
1471 * means that the device handle is no longer valid (you should close it) and
1472 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1473 * when this is the case.
1475 * This is a blocking function which usually incurs a noticeable delay.
1477 * \param dev a handle of the device to reset
1478 * \returns 0 on success
1479 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1480 * device has been disconnected
1481 * \returns another LIBUSB_ERROR code on other failure
1483 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
1485 usbi_dbg("");
1486 return usbi_backend->reset_device(dev);
1489 /** \ingroup dev
1490 * Determine if a kernel driver is active on an interface. If a kernel driver
1491 * is active, you cannot claim the interface, and libusbx will be unable to
1492 * perform I/O.
1494 * This functionality is not available on Windows.
1496 * \param dev a device handle
1497 * \param interface_number the interface to check
1498 * \returns 0 if no kernel driver is active
1499 * \returns 1 if a kernel driver is active
1500 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1501 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1502 * is not available
1503 * \returns another LIBUSB_ERROR code on other failure
1504 * \see libusb_detach_kernel_driver()
1506 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
1507 int interface_number)
1509 usbi_dbg("interface %d", interface_number);
1510 if (usbi_backend->kernel_driver_active)
1511 return usbi_backend->kernel_driver_active(dev, interface_number);
1512 else
1513 return LIBUSB_ERROR_NOT_SUPPORTED;
1516 /** \ingroup dev
1517 * Detach a kernel driver from an interface. If successful, you will then be
1518 * able to claim the interface and perform I/O.
1520 * This functionality is not available on Darwin or Windows.
1522 * Note that libusbx itself also talks to the device through a special kernel
1523 * driver, if this driver is already attached to the device, this call will
1524 * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1526 * \param dev a device handle
1527 * \param interface_number the interface to detach the driver from
1528 * \returns 0 on success
1529 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1530 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1531 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1532 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1533 * is not available
1534 * \returns another LIBUSB_ERROR code on other failure
1535 * \see libusb_kernel_driver_active()
1537 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
1538 int interface_number)
1540 usbi_dbg("interface %d", interface_number);
1541 if (usbi_backend->detach_kernel_driver)
1542 return usbi_backend->detach_kernel_driver(dev, interface_number);
1543 else
1544 return LIBUSB_ERROR_NOT_SUPPORTED;
1547 /** \ingroup dev
1548 * Re-attach an interface's kernel driver, which was previously detached
1549 * using libusb_detach_kernel_driver(). This call is only effective on
1550 * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1552 * This functionality is not available on Darwin or Windows.
1554 * \param dev a device handle
1555 * \param interface_number the interface to attach the driver from
1556 * \returns 0 on success
1557 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1558 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1559 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1560 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1561 * is not available
1562 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1563 * interface is claimed by a program or driver
1564 * \returns another LIBUSB_ERROR code on other failure
1565 * \see libusb_kernel_driver_active()
1567 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
1568 int interface_number)
1570 usbi_dbg("interface %d", interface_number);
1571 if (usbi_backend->attach_kernel_driver)
1572 return usbi_backend->attach_kernel_driver(dev, interface_number);
1573 else
1574 return LIBUSB_ERROR_NOT_SUPPORTED;
1577 /** \ingroup lib
1578 * Set log message verbosity.
1580 * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
1581 * printed. If you choose to increase the message verbosity level, ensure
1582 * that your application does not close the stdout/stderr file descriptors.
1584 * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusbx is conservative
1585 * with its message logging and most of the time, will only log messages that
1586 * explain error conditions and other oddities. This will help you debug
1587 * your software.
1589 * If the LIBUSB_DEBUG environment variable was set when libusbx was
1590 * initialized, this function does nothing: the message verbosity is fixed
1591 * to the value in the environment variable.
1593 * If libusbx was compiled without any message logging, this function does
1594 * nothing: you'll never get any messages.
1596 * If libusbx was compiled with verbose debug message logging, this function
1597 * does nothing: you'll always get messages from all levels.
1599 * \param ctx the context to operate on, or NULL for the default context
1600 * \param level debug level to set
1602 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
1604 USBI_GET_CONTEXT(ctx);
1605 if (!ctx->debug_fixed)
1606 ctx->debug = level;
1609 /** \ingroup lib
1610 * Initialize libusb. This function must be called before calling any other
1611 * libusbx function.
1613 * If you do not provide an output location for a context pointer, a default
1614 * context will be created. If there was already a default context, it will
1615 * be reused (and nothing will be initialized/reinitialized).
1617 * \param context Optional output location for context pointer.
1618 * Only valid on return code 0.
1619 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1620 * \see contexts
1622 int API_EXPORTED libusb_init(libusb_context **context)
1624 char *dbg;
1625 struct libusb_context *ctx;
1626 int r = 0;
1628 usbi_mutex_static_lock(&default_context_lock);
1630 if (!timestamp_origin.tv_sec) {
1631 usbi_gettimeofday(&timestamp_origin, NULL);
1634 if (!context && usbi_default_context) {
1635 usbi_dbg("reusing default context");
1636 default_context_refcnt++;
1637 usbi_mutex_static_unlock(&default_context_lock);
1638 return 0;
1641 ctx = calloc(1, sizeof(*ctx));
1642 if (!ctx) {
1643 r = LIBUSB_ERROR_NO_MEM;
1644 goto err_unlock;
1647 #ifdef ENABLE_DEBUG_LOGGING
1648 ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
1649 #endif
1651 dbg = getenv("LIBUSB_DEBUG");
1652 if (dbg) {
1653 ctx->debug = atoi(dbg);
1654 if (ctx->debug)
1655 ctx->debug_fixed = 1;
1658 /* default context should be initialized before calling usbi_dbg */
1659 if (!usbi_default_context) {
1660 usbi_default_context = ctx;
1661 default_context_refcnt++;
1662 usbi_dbg("created default context");
1665 usbi_dbg("libusbx v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
1666 libusb_version_internal.micro, libusb_version_internal.nano);
1668 if (usbi_backend->init) {
1669 r = usbi_backend->init(ctx);
1670 if (r)
1671 goto err_free_ctx;
1674 usbi_mutex_init(&ctx->usb_devs_lock, NULL);
1675 usbi_mutex_init(&ctx->open_devs_lock, NULL);
1676 list_init(&ctx->usb_devs);
1677 list_init(&ctx->open_devs);
1679 r = usbi_io_init(ctx);
1680 if (r < 0) {
1681 if (usbi_backend->exit)
1682 usbi_backend->exit();
1683 goto err_destroy_mutex;
1686 if (context) {
1687 *context = ctx;
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 #if defined(OS_WINCE)
1793 SYSTEMTIME st;
1794 GetSystemTime(&st);
1795 SystemTimeToFileTime(&st, &_now.ft);
1796 #else
1797 GetSystemTimeAsFileTime (&_now.ft);
1798 #endif
1799 tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
1800 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
1802 /* Always return 0 as per Open Group Base Specifications Issue 6.
1803 Do not set errno on error. */
1804 return 0;
1806 #endif
1808 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
1809 const char *function, const char *format, va_list args)
1811 const char *prefix = "";
1812 struct timeval now;
1813 int global_debug;
1814 static int has_debug_header_been_displayed = 0;
1816 #ifdef ENABLE_DEBUG_LOGGING
1817 global_debug = 1;
1818 UNUSED(ctx);
1819 #else
1820 USBI_GET_CONTEXT(ctx);
1821 if (ctx == NULL)
1822 return;
1823 global_debug = (ctx->debug == LIBUSB_LOG_LEVEL_DEBUG);
1824 if (!ctx->debug)
1825 return;
1826 if (level == LIBUSB_LOG_LEVEL_WARNING && ctx->debug < LIBUSB_LOG_LEVEL_WARNING)
1827 return;
1828 if (level == LIBUSB_LOG_LEVEL_INFO && ctx->debug < LIBUSB_LOG_LEVEL_INFO)
1829 return;
1830 if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx->debug < LIBUSB_LOG_LEVEL_DEBUG)
1831 return;
1832 #endif
1834 usbi_gettimeofday(&now, NULL);
1835 if ((global_debug) && (!has_debug_header_been_displayed)) {
1836 has_debug_header_been_displayed = 1;
1837 fprintf(stderr, "[timestamp] [threadID] facility level [function call] <message>\n");
1838 fprintf(stderr, "--------------------------------------------------------------------------------\n");
1840 if (now.tv_usec < timestamp_origin.tv_usec) {
1841 now.tv_sec--;
1842 now.tv_usec += 1000000;
1844 now.tv_sec -= timestamp_origin.tv_sec;
1845 now.tv_usec -= timestamp_origin.tv_usec;
1847 switch (level) {
1848 case LIBUSB_LOG_LEVEL_INFO:
1849 prefix = "info";
1850 break;
1851 case LIBUSB_LOG_LEVEL_WARNING:
1852 prefix = "warning";
1853 break;
1854 case LIBUSB_LOG_LEVEL_ERROR:
1855 prefix = "error";
1856 break;
1857 case LIBUSB_LOG_LEVEL_DEBUG:
1858 prefix = "debug";
1859 break;
1860 case LIBUSB_LOG_LEVEL_NONE:
1861 break;
1862 default:
1863 prefix = "unknown";
1864 break;
1867 if (global_debug) {
1868 fprintf(stderr, "[%2d.%06d] [%08x] libusbx: %s [%s] ",
1869 (int)now.tv_sec, (int)now.tv_usec, usbi_get_tid(), prefix, function);
1870 } else {
1871 fprintf(stderr, "libusbx: %s [%s] ", prefix, function);
1874 vfprintf(stderr, format, args);
1876 fprintf(stderr, "\n");
1879 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
1880 const char *function, const char *format, ...)
1882 va_list args;
1884 va_start (args, format);
1885 usbi_log_v(ctx, level, function, format, args);
1886 va_end (args);
1889 /** \ingroup misc
1890 * Returns a constant NULL-terminated string with the ASCII name of a libusb
1891 * error or transfer status code. The caller must not free() the returned
1892 * string.
1894 * \param error_code The \ref libusb_error or libusb_transfer_status code to
1895 * return the name of.
1896 * \returns The error name, or the string **UNKNOWN** if the value of
1897 * error_code is not a known error / status code.
1899 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
1901 switch (error_code) {
1902 case LIBUSB_ERROR_IO:
1903 return "LIBUSB_ERROR_IO";
1904 case LIBUSB_ERROR_INVALID_PARAM:
1905 return "LIBUSB_ERROR_INVALID_PARAM";
1906 case LIBUSB_ERROR_ACCESS:
1907 return "LIBUSB_ERROR_ACCESS";
1908 case LIBUSB_ERROR_NO_DEVICE:
1909 return "LIBUSB_ERROR_NO_DEVICE";
1910 case LIBUSB_ERROR_NOT_FOUND:
1911 return "LIBUSB_ERROR_NOT_FOUND";
1912 case LIBUSB_ERROR_BUSY:
1913 return "LIBUSB_ERROR_BUSY";
1914 case LIBUSB_ERROR_TIMEOUT:
1915 return "LIBUSB_ERROR_TIMEOUT";
1916 case LIBUSB_ERROR_OVERFLOW:
1917 return "LIBUSB_ERROR_OVERFLOW";
1918 case LIBUSB_ERROR_PIPE:
1919 return "LIBUSB_ERROR_PIPE";
1920 case LIBUSB_ERROR_INTERRUPTED:
1921 return "LIBUSB_ERROR_INTERRUPTED";
1922 case LIBUSB_ERROR_NO_MEM:
1923 return "LIBUSB_ERROR_NO_MEM";
1924 case LIBUSB_ERROR_NOT_SUPPORTED:
1925 return "LIBUSB_ERROR_NOT_SUPPORTED";
1926 case LIBUSB_ERROR_OTHER:
1927 return "LIBUSB_ERROR_OTHER";
1929 case LIBUSB_TRANSFER_ERROR:
1930 return "LIBUSB_TRANSFER_ERROR";
1931 case LIBUSB_TRANSFER_TIMED_OUT:
1932 return "LIBUSB_TRANSFER_TIMED_OUT";
1933 case LIBUSB_TRANSFER_CANCELLED:
1934 return "LIBUSB_TRANSFER_CANCELLED";
1935 case LIBUSB_TRANSFER_STALL:
1936 return "LIBUSB_TRANSFER_STALL";
1937 case LIBUSB_TRANSFER_NO_DEVICE:
1938 return "LIBUSB_TRANSFER_NO_DEVICE";
1939 case LIBUSB_TRANSFER_OVERFLOW:
1940 return "LIBUSB_TRANSFER_OVERFLOW";
1942 case 0:
1943 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
1944 default:
1945 return "**UNKNOWN**";
1949 /** \ingroup misc
1950 * Returns a pointer to const struct libusb_version with the version
1951 * (major, minor, micro, nano and rc) of the running library.
1953 DEFAULT_VISIBILITY
1954 const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
1956 return &libusb_version_internal;