1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
3 * Core functions for libusb
4 * Copyright © 2012-2013 Nathan Hjelm <hjelmn@cs.unm.edu>
5 * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
6 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
33 #ifdef HAVE_SYS_TIME_H
41 #include <android/log.h>
48 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
49 #elif defined(OS_DARWIN)
50 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
51 #elif defined(OS_OPENBSD)
52 const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
53 #elif defined(OS_NETBSD)
54 const struct usbi_os_backend * const usbi_backend = &netbsd_backend;
55 #elif defined(OS_WINDOWS)
57 #if defined(USE_USBDK)
58 const struct usbi_os_backend * const usbi_backend = &usbdk_backend;
60 const struct usbi_os_backend * const usbi_backend = &windows_backend;
63 #elif defined(OS_WINCE)
64 const struct usbi_os_backend * const usbi_backend = &wince_backend;
65 #elif defined(OS_HAIKU)
66 const struct usbi_os_backend * const usbi_backend = &haiku_usb_raw_backend;
68 #error "Unsupported OS"
71 struct libusb_context *usbi_default_context = NULL;
72 static const struct libusb_version libusb_version_internal =
73 { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
74 LIBUSB_RC, "http://libusb.info" };
75 static int default_context_refcnt = 0;
76 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
77 static struct timeval timestamp_origin = { 0, 0 };
79 usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
80 struct list_head active_contexts_list;
83 * \mainpage libusb-1.0 API Reference
85 * \section intro Introduction
87 * libusb is an open source library that allows you to communicate with USB
88 * devices from userspace. For more info, see the
89 * <a href="http://libusb.info">libusb homepage</a>.
91 * This documentation is aimed at application developers wishing to
92 * communicate with USB peripherals from their own software. After reviewing
93 * this documentation, feedback and questions can be sent to the
94 * <a href="http://mailing-list.libusb.info">libusb-devel mailing list</a>.
96 * This documentation assumes knowledge of how to operate USB devices from
97 * a software standpoint (descriptors, configurations, interfaces, endpoints,
98 * control/bulk/interrupt/isochronous transfers, etc). Full information
99 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
100 * Specification</a> which is available for free download. You can probably
101 * find less verbose introductions by searching the web.
103 * \section API Application Programming Interface (API)
105 * See the \ref libusb_api page for a complete list of the libusb functions.
107 * \section features Library features
109 * - All transfer types supported (control/bulk/interrupt/isochronous)
110 * - 2 transfer interfaces:
111 * -# Synchronous (simple)
112 * -# Asynchronous (more complicated, but more powerful)
113 * - Thread safe (although the asynchronous interface means that you
114 * usually won't need to thread)
115 * - Lightweight with lean API
116 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
117 * - Hotplug support (on some platforms). See \ref libusb_hotplug.
119 * \section gettingstarted Getting Started
121 * To begin reading the API documentation, start with the Modules page which
122 * links to the different categories of libusb's functionality.
124 * One decision you will have to make is whether to use the synchronous
125 * or the asynchronous data transfer interface. The \ref libusb_io documentation
126 * provides some insight into this topic.
128 * Some example programs can be found in the libusb source distribution under
129 * the "examples" subdirectory. The libusb homepage includes a list of
130 * real-life project examples which use libusb.
132 * \section errorhandling Error handling
134 * libusb functions typically return 0 on success or a negative error code
135 * on failure. These negative error codes relate to LIBUSB_ERROR constants
136 * which are listed on the \ref libusb_misc "miscellaneous" documentation page.
138 * \section msglog Debug message logging
140 * libusb uses stderr for all logging. By default, logging is set to NONE,
141 * which means that no output will be produced. However, unless the library
142 * has been compiled with logging disabled, then any application calls to
143 * libusb_set_debug(), or the setting of the environmental variable
144 * LIBUSB_DEBUG outside of the application, can result in logging being
145 * produced. Your application should therefore not close stderr, but instead
146 * direct it to the null device if its output is undesirable.
148 * The libusb_set_debug() function can be used to enable logging of certain
149 * messages. Under standard configuration, libusb doesn't really log much
150 * so you are advised to use this function to enable all error/warning/
151 * informational messages. It will help debug problems with your software.
153 * The logged messages are unstructured. There is no one-to-one correspondence
154 * between messages being logged and success or failure return codes from
155 * libusb functions. There is no format to the messages, so you should not
156 * try to capture or parse them. They are not and will not be localized.
157 * These messages are not intended to being passed to your application user;
158 * instead, you should interpret the error codes returned from libusb functions
159 * and provide appropriate notification to the user. The messages are simply
160 * there to aid you as a programmer, and if you're confused because you're
161 * getting a strange error code from a libusb function, enabling message
162 * logging may give you a suitable explanation.
164 * The LIBUSB_DEBUG environment variable can be used to enable message logging
165 * at run-time. This environment variable should be set to a log level number,
166 * which is interpreted the same as the libusb_set_debug() parameter. When this
167 * environment variable is set, the message logging verbosity level is fixed
168 * and libusb_set_debug() effectively does nothing.
170 * libusb can be compiled without any logging functions, useful for embedded
171 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
172 * variable have no effects.
174 * libusb can also be compiled with verbose debugging messages always. When
175 * the library is compiled in this way, all messages of all verbosities are
176 * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
179 * \section remarks Other remarks
181 * libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts
186 * \page libusb_caveats Caveats
188 * \section devresets Device resets
190 * The libusb_reset_device() function allows you to reset a device. If your
191 * program has to call such a function, it should obviously be aware that
192 * the reset will cause device state to change (e.g. register values may be
195 * The problem is that any other program could reset the device your program
196 * is working with, at any time. libusb does not offer a mechanism to inform
197 * you when this has happened, so if someone else resets your device it will
198 * not be clear to your own program why the device state has changed.
200 * Ultimately, this is a limitation of writing drivers in userspace.
201 * Separation from the USB stack in the underlying kernel makes it difficult
202 * for the operating system to deliver such notifications to your program.
203 * The Linux kernel USB stack allows such reset notifications to be delivered
204 * to in-kernel USB drivers, but it is not clear how such notifications could
205 * be delivered to second-class drivers that live in userspace.
207 * \section blockonly Blocking-only functionality
209 * The functionality listed below is only available through synchronous,
210 * blocking functions. There are no asynchronous/non-blocking alternatives,
211 * and no clear ways of implementing these.
213 * - Configuration activation (libusb_set_configuration())
214 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
215 * - Releasing of interfaces (libusb_release_interface())
216 * - Clearing of halt/stall condition (libusb_clear_halt())
217 * - Device resets (libusb_reset_device())
219 * \section configsel Configuration selection and handling
221 * When libusb presents a device handle to an application, there is a chance
222 * that the corresponding device may be in unconfigured state. For devices
223 * with multiple configurations, there is also a chance that the configuration
224 * currently selected is not the one that the application wants to use.
226 * The obvious solution is to add a call to libusb_set_configuration() early
227 * on during your device initialization routines, but there are caveats to
229 * -# If the device is already in the desired configuration, calling
230 * libusb_set_configuration() using the same configuration value will cause
231 * a lightweight device reset. This may not be desirable behaviour.
232 * -# In the case where the desired configuration is already active, libusb
233 * may not even be able to perform a lightweight device reset. For example,
234 * take my USB keyboard with fingerprint reader: I'm interested in driving
235 * the fingerprint reader interface through libusb, but the kernel's
236 * USB-HID driver will almost always have claimed the keyboard interface.
237 * Because the kernel has claimed an interface, it is not even possible to
238 * perform the lightweight device reset, so libusb_set_configuration() will
239 * fail. (Luckily the device in question only has a single configuration.)
240 * -# libusb will be unable to set a configuration if other programs or
241 * drivers have claimed interfaces. In particular, this means that kernel
242 * drivers must be detached from all the interfaces before
243 * libusb_set_configuration() may succeed.
245 * One solution to some of the above problems is to consider the currently
246 * active configuration. If the configuration we want is already active, then
247 * we don't have to select any configuration:
250 libusb_get_configuration(dev, &cfg);
252 libusb_set_configuration(dev, desired);
255 * This is probably suitable for most scenarios, but is inherently racy:
256 * another application or driver may change the selected configuration
257 * <em>after</em> the libusb_get_configuration() call.
259 * Even in cases where libusb_set_configuration() succeeds, consider that other
260 * applications or drivers may change configuration after your application
261 * calls libusb_set_configuration().
263 * One possible way to lock your device into a specific configuration is as
265 * -# Set the desired configuration (or use the logic above to realise that
266 * it is already in the desired configuration)
267 * -# Claim the interface that you wish to use
268 * -# Check that the currently active configuration is the one that you want
271 * The above method works because once an interface is claimed, no application
272 * or driver is able to select another configuration.
274 * \section earlycomp Early transfer completion
276 * NOTE: This section is currently Linux-centric. I am not sure if any of these
277 * considerations apply to Darwin or other platforms.
279 * When a transfer completes early (i.e. when less data is received/sent in
280 * any one packet than the transfer buffer allows for) then libusb is designed
281 * to terminate the transfer immediately, not transferring or receiving any
282 * more data unless other transfers have been queued by the user.
284 * On legacy platforms, libusb is unable to do this in all situations. After
285 * the incomplete packet occurs, "surplus" data may be transferred. For recent
286 * versions of libusb, this information is kept (the data length of the
287 * transfer is updated) and, for device-to-host transfers, any surplus data was
288 * added to the buffer. Still, this is not a nice solution because it loses the
289 * information about the end of the short packet, and the user probably wanted
290 * that surplus data to arrive in the next logical transfer.
293 * \section zlp Zero length packets
295 * - libusb is able to send a packet of zero length to an endpoint simply by
296 * submitting a transfer of zero length.
297 * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
298 * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
302 * \page libusb_contexts Contexts
304 * It is possible that libusb may be used simultaneously from two independent
305 * libraries linked into the same executable. For example, if your application
306 * has a plugin-like system which allows the user to dynamically load a range
307 * of modules into your program, it is feasible that two independently
308 * developed modules may both use libusb.
310 * libusb is written to allow for these multiple user scenarios. The two
311 * "instances" of libusb will not interfere: libusb_set_debug() calls
312 * from one user will not affect the same settings for other users, other
313 * users can continue using libusb after one of them calls libusb_exit(), etc.
315 * This is made possible through libusb's <em>context</em> concept. When you
316 * call libusb_init(), you are (optionally) given a context. You can then pass
317 * this context pointer back into future libusb functions.
319 * In order to keep things simple for more simplistic applications, it is
320 * legal to pass NULL to all functions requiring a context pointer (as long as
321 * you're sure no other code will attempt to use libusb from the same process).
322 * When you pass NULL, the default context will be used. The default context
323 * is created the first time a process calls libusb_init() when no other
324 * context is alive. Contexts are destroyed during libusb_exit().
326 * The default context is reference-counted and can be shared. That means that
327 * if libusb_init(NULL) is called twice within the same process, the two
328 * users end up sharing the same context. The deinitialization and freeing of
329 * the default context will only happen when the last user calls libusb_exit().
330 * In other words, the default context is created and initialized when its
331 * reference count goes from 0 to 1, and is deinitialized and destroyed when
332 * its reference count goes from 1 to 0.
334 * You may be wondering why only a subset of libusb functions require a
335 * context pointer in their function definition. Internally, libusb stores
336 * context pointers in other objects (e.g. libusb_device instances) and hence
337 * can infer the context from those objects.
341 * \page libusb_api Application Programming Interface
343 * This is the complete list of libusb functions, structures and
344 * enumerations in alphabetical order.
347 * - libusb_alloc_streams()
348 * - libusb_alloc_transfer()
349 * - libusb_attach_kernel_driver()
350 * - libusb_bulk_transfer()
351 * - libusb_cancel_transfer()
352 * - libusb_claim_interface()
353 * - libusb_clear_halt()
355 * - libusb_control_transfer()
356 * - libusb_control_transfer_get_data()
357 * - libusb_control_transfer_get_setup()
358 * - libusb_cpu_to_le16()
359 * - libusb_detach_kernel_driver()
360 * - libusb_error_name()
361 * - libusb_event_handler_active()
362 * - libusb_event_handling_ok()
364 * - libusb_fill_bulk_stream_transfer()
365 * - libusb_fill_bulk_transfer()
366 * - libusb_fill_control_setup()
367 * - libusb_fill_control_transfer()
368 * - libusb_fill_interrupt_transfer()
369 * - libusb_fill_iso_transfer()
370 * - libusb_free_bos_descriptor()
371 * - libusb_free_config_descriptor()
372 * - libusb_free_container_id_descriptor()
373 * - libusb_free_device_list()
374 * - libusb_free_pollfds()
375 * - libusb_free_ss_endpoint_companion_descriptor()
376 * - libusb_free_ss_usb_device_capability_descriptor()
377 * - libusb_free_streams()
378 * - libusb_free_transfer()
379 * - libusb_free_usb_2_0_extension_descriptor()
380 * - libusb_get_active_config_descriptor()
381 * - libusb_get_bos_descriptor()
382 * - libusb_get_bus_number()
383 * - libusb_get_config_descriptor()
384 * - libusb_get_config_descriptor_by_value()
385 * - libusb_get_configuration()
386 * - libusb_get_container_id_descriptor()
387 * - libusb_get_descriptor()
388 * - libusb_get_device()
389 * - libusb_get_device_address()
390 * - libusb_get_device_descriptor()
391 * - libusb_get_device_list()
392 * - libusb_get_device_speed()
393 * - libusb_get_iso_packet_buffer()
394 * - libusb_get_iso_packet_buffer_simple()
395 * - libusb_get_max_iso_packet_size()
396 * - libusb_get_max_packet_size()
397 * - libusb_get_next_timeout()
398 * - libusb_get_parent()
399 * - libusb_get_pollfds()
400 * - libusb_get_port_number()
401 * - libusb_get_port_numbers()
402 * - libusb_get_port_path()
403 * - libusb_get_ss_endpoint_companion_descriptor()
404 * - libusb_get_ss_usb_device_capability_descriptor()
405 * - libusb_get_string_descriptor()
406 * - libusb_get_string_descriptor_ascii()
407 * - libusb_get_usb_2_0_extension_descriptor()
408 * - libusb_get_version()
409 * - libusb_handle_events()
410 * - libusb_handle_events_completed()
411 * - libusb_handle_events_locked()
412 * - libusb_handle_events_timeout()
413 * - libusb_handle_events_timeout_completed()
414 * - libusb_has_capability()
415 * - libusb_hotplug_deregister_callback()
416 * - libusb_hotplug_register_callback()
418 * - libusb_interrupt_event_handler()
419 * - libusb_interrupt_transfer()
420 * - libusb_kernel_driver_active()
421 * - libusb_lock_events()
422 * - libusb_lock_event_waiters()
424 * - libusb_open_device_with_vid_pid()
425 * - libusb_pollfds_handle_timeouts()
426 * - libusb_ref_device()
427 * - libusb_release_interface()
428 * - libusb_reset_device()
429 * - libusb_set_auto_detach_kernel_driver()
430 * - libusb_set_configuration()
431 * - libusb_set_debug()
432 * - libusb_set_interface_alt_setting()
433 * - libusb_set_iso_packet_lengths()
434 * - libusb_setlocale()
435 * - libusb_set_pollfd_notifiers()
436 * - libusb_strerror()
437 * - libusb_submit_transfer()
438 * - libusb_transfer_get_stream_id()
439 * - libusb_transfer_set_stream_id()
440 * - libusb_try_lock_events()
441 * - libusb_unlock_events()
442 * - libusb_unlock_event_waiters()
443 * - libusb_unref_device()
444 * - libusb_wait_for_event()
446 * \section Structures
447 * - libusb_bos_descriptor
448 * - libusb_bos_dev_capability_descriptor
449 * - libusb_config_descriptor
450 * - libusb_container_id_descriptor
451 * - \ref libusb_context
452 * - libusb_control_setup
453 * - \ref libusb_device
454 * - libusb_device_descriptor
455 * - \ref libusb_device_handle
456 * - libusb_endpoint_descriptor
458 * - libusb_interface_descriptor
459 * - libusb_iso_packet_descriptor
461 * - libusb_ss_endpoint_companion_descriptor
462 * - libusb_ss_usb_device_capability_descriptor
464 * - libusb_usb_2_0_extension_descriptor
468 * - \ref libusb_bos_type
469 * - \ref libusb_capability
470 * - \ref libusb_class_code
471 * - \ref libusb_descriptor_type
472 * - \ref libusb_endpoint_direction
473 * - \ref libusb_error
474 * - \ref libusb_iso_sync_type
475 * - \ref libusb_iso_usage_type
476 * - \ref libusb_log_level
477 * - \ref libusb_request_recipient
478 * - \ref libusb_request_type
479 * - \ref libusb_speed
480 * - \ref libusb_ss_usb_device_capability_attributes
481 * - \ref libusb_standard_request
482 * - \ref libusb_supported_speed
483 * - \ref libusb_transfer_flags
484 * - \ref libusb_transfer_status
485 * - \ref libusb_transfer_type
486 * - \ref libusb_usb_2_0_extension_attributes
490 * @defgroup libusb_lib Library initialization/deinitialization
491 * This page details how to initialize and deinitialize libusb. Initialization
492 * must be performed before using any libusb functionality, and similarly you
493 * must not call any libusb functions after deinitialization.
497 * @defgroup libusb_dev Device handling and enumeration
498 * The functionality documented below is designed to help with the following
500 * - Enumerating the USB devices currently attached to the system
501 * - Choosing a device to operate from your software
502 * - Opening and closing the chosen device
504 * \section nutshell In a nutshell...
506 * The description below really makes things sound more complicated than they
507 * actually are. The following sequence of function calls will be suitable
508 * for almost all scenarios and does not require you to have such a deep
509 * understanding of the resource management issues:
512 libusb_device **list;
513 libusb_device *found = NULL;
514 ssize_t cnt = libusb_get_device_list(NULL, &list);
520 for (i = 0; i < cnt; i++) {
521 libusb_device *device = list[i];
522 if (is_interesting(device)) {
529 libusb_device_handle *handle;
531 err = libusb_open(found, &handle);
537 libusb_free_device_list(list, 1);
540 * The two important points:
541 * - You asked libusb_free_device_list() to unreference the devices (2nd
543 * - You opened the device before freeing the list and unreferencing the
546 * If you ended up with a handle, you can now proceed to perform I/O on the
549 * \section devshandles Devices and device handles
550 * libusb has a concept of a USB device, represented by the
551 * \ref libusb_device opaque type. A device represents a USB device that
552 * is currently or was previously connected to the system. Using a reference
553 * to a device, you can determine certain information about the device (e.g.
554 * you can read the descriptor data).
556 * The libusb_get_device_list() function can be used to obtain a list of
557 * devices currently connected to the system. This is known as device
560 * Just because you have a reference to a device does not mean it is
561 * necessarily usable. The device may have been unplugged, you may not have
562 * permission to operate such device, or another program or driver may be
565 * When you've found a device that you'd like to operate, you must ask
566 * libusb to open the device using the libusb_open() function. Assuming
567 * success, libusb then returns you a <em>device handle</em>
568 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
569 * operate on the handle rather than the original device pointer.
571 * \section devref Device discovery and reference counting
573 * Device discovery (i.e. calling libusb_get_device_list()) returns a
574 * freshly-allocated list of devices. The list itself must be freed when
575 * you are done with it. libusb also needs to know when it is OK to free
576 * the contents of the list - the devices themselves.
578 * To handle these issues, libusb provides you with two separate items:
579 * - A function to free the list itself
580 * - A reference counting system for the devices inside
582 * New devices presented by the libusb_get_device_list() function all have a
583 * reference count of 1. You can increase and decrease reference count using
584 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
585 * its reference count reaches 0.
587 * With the above information in mind, the process of opening a device can
588 * be viewed as follows:
589 * -# Discover devices using libusb_get_device_list().
590 * -# Choose the device that you want to operate, and call libusb_open().
591 * -# Unref all devices in the discovered device list.
592 * -# Free the discovered device list.
594 * The order is important - you must not unreference the device before
595 * attempting to open it, because unreferencing it may destroy the device.
597 * For convenience, the libusb_free_device_list() function includes a
598 * parameter to optionally unreference all the devices in the list before
599 * freeing the list itself. This combines steps 3 and 4 above.
601 * As an implementation detail, libusb_open() actually adds a reference to
602 * the device in question. This is because the device remains available
603 * through the handle via libusb_get_device(). The reference is deleted during
607 /** @defgroup libusb_misc Miscellaneous */
609 /* we traverse usbfs without knowing how many devices we are going to find.
610 * so we create this discovered_devs model which is similar to a linked-list
611 * which grows when required. it can be freed once discovery has completed,
612 * eliminating the need for a list node in the libusb_device structure
614 #define DISCOVERED_DEVICES_SIZE_STEP 8
616 static struct discovered_devs *discovered_devs_alloc(void)
618 struct discovered_devs *ret =
619 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
623 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
628 /* append a device to the discovered devices collection. may realloc itself,
629 * returning new discdevs. returns NULL on realloc failure. */
630 struct discovered_devs *discovered_devs_append(
631 struct discovered_devs *discdevs, struct libusb_device *dev)
633 size_t len = discdevs->len;
636 /* if there is space, just append the device */
637 if (len < discdevs->capacity) {
638 discdevs->devices[len] = libusb_ref_device(dev);
643 /* exceeded capacity, need to grow */
644 usbi_dbg("need to increase capacity");
645 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
646 discdevs = usbi_reallocf(discdevs,
647 sizeof(*discdevs) + (sizeof(void *) * capacity));
649 discdevs->capacity = capacity;
650 discdevs->devices[len] = libusb_ref_device(dev);
657 static void discovered_devs_free(struct discovered_devs *discdevs)
661 for (i = 0; i < discdevs->len; i++)
662 libusb_unref_device(discdevs->devices[i]);
667 /* Allocate a new device with a specific session ID. The returned device has
668 * a reference count of 1. */
669 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
670 unsigned long session_id)
672 size_t priv_size = usbi_backend->device_priv_size;
673 struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
679 r = usbi_mutex_init(&dev->lock);
687 dev->session_data = session_id;
688 dev->speed = LIBUSB_SPEED_UNKNOWN;
690 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
691 usbi_connect_device (dev);
697 void usbi_connect_device(struct libusb_device *dev)
699 struct libusb_context *ctx = DEVICE_CTX(dev);
703 usbi_mutex_lock(&dev->ctx->usb_devs_lock);
704 list_add(&dev->list, &dev->ctx->usb_devs);
705 usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
707 /* Signal that an event has occurred for this device if we support hotplug AND
708 * the hotplug message list is ready. This prevents an event from getting raised
709 * during initial enumeration. */
710 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
711 usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED);
715 void usbi_disconnect_device(struct libusb_device *dev)
717 struct libusb_context *ctx = DEVICE_CTX(dev);
719 usbi_mutex_lock(&dev->lock);
721 usbi_mutex_unlock(&dev->lock);
723 usbi_mutex_lock(&ctx->usb_devs_lock);
724 list_del(&dev->list);
725 usbi_mutex_unlock(&ctx->usb_devs_lock);
727 /* Signal that an event has occurred for this device if we support hotplug AND
728 * the hotplug message list is ready. This prevents an event from getting raised
729 * during initial enumeration. libusb_handle_events will take care of dereferencing
731 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
732 usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);
736 /* Perform some final sanity checks on a newly discovered device. If this
737 * function fails (negative return code), the device should not be added
738 * to the discovered device list. */
739 int usbi_sanitize_device(struct libusb_device *dev)
742 uint8_t num_configurations;
744 r = usbi_device_cache_descriptor(dev);
748 num_configurations = dev->device_descriptor.bNumConfigurations;
749 if (num_configurations > USB_MAXCONFIG) {
750 usbi_err(DEVICE_CTX(dev), "too many configurations");
751 return LIBUSB_ERROR_IO;
752 } else if (0 == num_configurations)
753 usbi_dbg("zero configurations, maybe an unauthorized device");
755 dev->num_configurations = num_configurations;
759 /* Examine libusb's internal list of known devices, looking for one with
760 * a specific session ID. Returns the matching device if it was found, and
762 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
763 unsigned long session_id)
765 struct libusb_device *dev;
766 struct libusb_device *ret = NULL;
768 usbi_mutex_lock(&ctx->usb_devs_lock);
769 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
770 if (dev->session_data == session_id) {
771 ret = libusb_ref_device(dev);
774 usbi_mutex_unlock(&ctx->usb_devs_lock);
779 /** @ingroup libusb_dev
780 * Returns a list of USB devices currently attached to the system. This is
781 * your entry point into finding a USB device to operate.
783 * You are expected to unreference all the devices when you are done with
784 * them, and then free the list with libusb_free_device_list(). Note that
785 * libusb_free_device_list() can unref all the devices for you. Be careful
786 * not to unreference a device you are about to open until after you have
789 * This return value of this function indicates the number of devices in
790 * the resultant list. The list is actually one element larger, as it is
793 * \param ctx the context to operate on, or NULL for the default context
794 * \param list output location for a list of devices. Must be later freed with
795 * libusb_free_device_list().
796 * \returns the number of devices in the outputted list, or any
797 * \ref libusb_error according to errors encountered by the backend.
799 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
800 libusb_device ***list)
802 struct discovered_devs *discdevs = discovered_devs_alloc();
803 struct libusb_device **ret;
806 USBI_GET_CONTEXT(ctx);
810 return LIBUSB_ERROR_NO_MEM;
812 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
813 /* backend provides hotplug support */
814 struct libusb_device *dev;
816 if (usbi_backend->hotplug_poll)
817 usbi_backend->hotplug_poll();
819 usbi_mutex_lock(&ctx->usb_devs_lock);
820 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
821 discdevs = discovered_devs_append(discdevs, dev);
824 r = LIBUSB_ERROR_NO_MEM;
828 usbi_mutex_unlock(&ctx->usb_devs_lock);
830 /* backend does not provide hotplug support */
831 r = usbi_backend->get_device_list(ctx, &discdevs);
839 /* convert discovered_devs into a list */
841 ret = calloc(len + 1, sizeof(struct libusb_device *));
843 len = LIBUSB_ERROR_NO_MEM;
848 for (i = 0; i < len; i++) {
849 struct libusb_device *dev = discdevs->devices[i];
850 ret[i] = libusb_ref_device(dev);
855 discovered_devs_free(discdevs);
859 /** \ingroup libusb_dev
860 * Frees a list of devices previously discovered using
861 * libusb_get_device_list(). If the unref_devices parameter is set, the
862 * reference count of each device in the list is decremented by 1.
863 * \param list the list to free
864 * \param unref_devices whether to unref the devices in the list
866 void API_EXPORTED libusb_free_device_list(libusb_device **list,
874 struct libusb_device *dev;
876 while ((dev = list[i++]) != NULL)
877 libusb_unref_device(dev);
882 /** \ingroup libusb_dev
883 * Get the number of the bus that a device is connected to.
884 * \param dev a device
885 * \returns the bus number
887 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
889 return dev->bus_number;
892 /** \ingroup libusb_dev
893 * Get the number of the port that a device is connected to.
894 * Unless the OS does something funky, or you are hot-plugging USB extension cards,
895 * the port number returned by this call is usually guaranteed to be uniquely tied
896 * to a physical port, meaning that different devices plugged on the same physical
897 * port should return the same port number.
899 * But outside of this, there is no guarantee that the port number returned by this
900 * call will remain the same, or even match the order in which ports have been
901 * numbered by the HUB/HCD manufacturer.
903 * \param dev a device
904 * \returns the port number (0 if not available)
906 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
908 return dev->port_number;
911 /** \ingroup libusb_dev
912 * Get the list of all port numbers from root for the specified device
914 * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
915 * \param dev a device
916 * \param port_numbers the array that should contain the port numbers
917 * \param port_numbers_len the maximum length of the array. As per the USB 3.0
918 * specs, the current maximum limit for the depth is 7.
919 * \returns the number of elements filled
920 * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
922 int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
923 uint8_t* port_numbers, int port_numbers_len)
925 int i = port_numbers_len;
926 struct libusb_context *ctx = DEVICE_CTX(dev);
928 if (port_numbers_len <= 0)
929 return LIBUSB_ERROR_INVALID_PARAM;
931 // HCDs can be listed as devices with port #0
932 while((dev) && (dev->port_number != 0)) {
934 usbi_warn(ctx, "port numbers array is too small");
935 return LIBUSB_ERROR_OVERFLOW;
937 port_numbers[i] = dev->port_number;
938 dev = dev->parent_dev;
940 if (i < port_numbers_len)
941 memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
942 return port_numbers_len - i;
945 /** \ingroup libusb_dev
946 * Deprecated please use libusb_get_port_numbers instead.
948 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
949 uint8_t* port_numbers, uint8_t port_numbers_len)
953 return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
956 /** \ingroup libusb_dev
957 * Get the the parent from the specified device.
958 * \param dev a device
959 * \returns the device parent or NULL if not available
960 * You should issue a \ref libusb_get_device_list() before calling this
961 * function and make sure that you only access the parent before issuing
962 * \ref libusb_free_device_list(). The reason is that libusb currently does
963 * not maintain a permanent list of device instances, and therefore can
964 * only guarantee that parents are fully instantiated within a
965 * libusb_get_device_list() - libusb_free_device_list() block.
968 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
970 return dev->parent_dev;
973 /** \ingroup libusb_dev
974 * Get the address of the device on the bus it is connected to.
975 * \param dev a device
976 * \returns the device address
978 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
980 return dev->device_address;
983 /** \ingroup libusb_dev
984 * Get the negotiated connection speed for a device.
985 * \param dev a device
986 * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
987 * the OS doesn't know or doesn't support returning the negotiated speed.
989 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
994 static const struct libusb_endpoint_descriptor *find_endpoint(
995 struct libusb_config_descriptor *config, unsigned char endpoint)
998 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
999 const struct libusb_interface *iface = &config->interface[iface_idx];
1002 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
1004 const struct libusb_interface_descriptor *altsetting
1005 = &iface->altsetting[altsetting_idx];
1008 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
1009 const struct libusb_endpoint_descriptor *ep =
1010 &altsetting->endpoint[ep_idx];
1011 if (ep->bEndpointAddress == endpoint)
1019 /** \ingroup libusb_dev
1020 * Convenience function to retrieve the wMaxPacketSize value for a particular
1021 * endpoint in the active device configuration.
1023 * This function was originally intended to be of assistance when setting up
1024 * isochronous transfers, but a design mistake resulted in this function
1025 * instead. It simply returns the wMaxPacketSize value without considering
1026 * its contents. If you're dealing with isochronous transfers, you probably
1027 * want libusb_get_max_iso_packet_size() instead.
1029 * \param dev a device
1030 * \param endpoint address of the endpoint in question
1031 * \returns the wMaxPacketSize value
1032 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1033 * \returns LIBUSB_ERROR_OTHER on other failure
1035 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
1036 unsigned char endpoint)
1038 struct libusb_config_descriptor *config;
1039 const struct libusb_endpoint_descriptor *ep;
1042 r = libusb_get_active_config_descriptor(dev, &config);
1044 usbi_err(DEVICE_CTX(dev),
1045 "could not retrieve active config descriptor");
1046 return LIBUSB_ERROR_OTHER;
1049 ep = find_endpoint(config, endpoint);
1051 r = LIBUSB_ERROR_NOT_FOUND;
1055 r = ep->wMaxPacketSize;
1058 libusb_free_config_descriptor(config);
1062 /** \ingroup libusb_dev
1063 * Calculate the maximum packet size which a specific endpoint is capable is
1064 * sending or receiving in the duration of 1 microframe
1066 * Only the active configuration is examined. The calculation is based on the
1067 * wMaxPacketSize field in the endpoint descriptor as described in section
1068 * 9.6.6 in the USB 2.0 specifications.
1070 * If acting on an isochronous or interrupt endpoint, this function will
1071 * multiply the value found in bits 0:10 by the number of transactions per
1072 * microframe (determined by bits 11:12). Otherwise, this function just
1073 * returns the numeric value found in bits 0:10.
1075 * This function is useful for setting up isochronous transfers, for example
1076 * you might pass the return value from this function to
1077 * libusb_set_iso_packet_lengths() in order to set the length field of every
1078 * isochronous packet in a transfer.
1082 * \param dev a device
1083 * \param endpoint address of the endpoint in question
1084 * \returns the maximum packet size which can be sent/received on this endpoint
1085 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1086 * \returns LIBUSB_ERROR_OTHER on other failure
1088 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
1089 unsigned char endpoint)
1091 struct libusb_config_descriptor *config;
1092 const struct libusb_endpoint_descriptor *ep;
1093 enum libusb_transfer_type ep_type;
1097 r = libusb_get_active_config_descriptor(dev, &config);
1099 usbi_err(DEVICE_CTX(dev),
1100 "could not retrieve active config descriptor");
1101 return LIBUSB_ERROR_OTHER;
1104 ep = find_endpoint(config, endpoint);
1106 r = LIBUSB_ERROR_NOT_FOUND;
1110 val = ep->wMaxPacketSize;
1111 ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
1114 if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
1115 || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1116 r *= (1 + ((val >> 11) & 3));
1119 libusb_free_config_descriptor(config);
1123 /** \ingroup libusb_dev
1124 * Increment the reference count of a device.
1125 * \param dev the device to reference
1126 * \returns the same device
1129 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
1131 usbi_mutex_lock(&dev->lock);
1133 usbi_mutex_unlock(&dev->lock);
1137 /** \ingroup libusb_dev
1138 * Decrement the reference count of a device. If the decrement operation
1139 * causes the reference count to reach zero, the device shall be destroyed.
1140 * \param dev the device to unreference
1142 void API_EXPORTED libusb_unref_device(libusb_device *dev)
1149 usbi_mutex_lock(&dev->lock);
1150 refcnt = --dev->refcnt;
1151 usbi_mutex_unlock(&dev->lock);
1154 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
1156 libusb_unref_device(dev->parent_dev);
1158 if (usbi_backend->destroy_device)
1159 usbi_backend->destroy_device(dev);
1161 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1162 /* backend does not support hotplug */
1163 usbi_disconnect_device(dev);
1166 usbi_mutex_destroy(&dev->lock);
1172 * Signal the event pipe so that the event handling thread will be
1173 * interrupted to process an internal event.
1175 int usbi_signal_event(struct libusb_context *ctx)
1177 unsigned char dummy = 1;
1180 /* write some data on event pipe to interrupt event handlers */
1181 r = usbi_write(ctx->event_pipe[1], &dummy, sizeof(dummy));
1182 if (r != sizeof(dummy)) {
1183 usbi_warn(ctx, "internal signalling write failed");
1184 return LIBUSB_ERROR_IO;
1191 * Clear the event pipe so that the event handling will no longer be
1194 int usbi_clear_event(struct libusb_context *ctx)
1196 unsigned char dummy;
1199 /* read some data on event pipe to clear it */
1200 r = usbi_read(ctx->event_pipe[0], &dummy, sizeof(dummy));
1201 if (r != sizeof(dummy)) {
1202 usbi_warn(ctx, "internal signalling read failed");
1203 return LIBUSB_ERROR_IO;
1209 /** \ingroup libusb_dev
1210 * Open a device and obtain a device handle. A handle allows you to perform
1211 * I/O on the device in question.
1213 * Internally, this function adds a reference to the device and makes it
1214 * available to you through libusb_get_device(). This reference is removed
1215 * during libusb_close().
1217 * This is a non-blocking function; no requests are sent over the bus.
1219 * \param dev the device to open
1220 * \param dev_handle output location for the returned device handle pointer. Only
1221 * populated when the return code is 0.
1222 * \returns 0 on success
1223 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
1224 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1225 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1226 * \returns another LIBUSB_ERROR code on other failure
1228 int API_EXPORTED libusb_open(libusb_device *dev,
1229 libusb_device_handle **dev_handle)
1231 struct libusb_context *ctx = DEVICE_CTX(dev);
1232 struct libusb_device_handle *_dev_handle;
1233 size_t priv_size = usbi_backend->device_handle_priv_size;
1235 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
1237 if (!dev->attached) {
1238 return LIBUSB_ERROR_NO_DEVICE;
1241 _dev_handle = malloc(sizeof(*_dev_handle) + priv_size);
1243 return LIBUSB_ERROR_NO_MEM;
1245 r = usbi_mutex_init(&_dev_handle->lock);
1248 return LIBUSB_ERROR_OTHER;
1251 _dev_handle->dev = libusb_ref_device(dev);
1252 _dev_handle->auto_detach_kernel_driver = 0;
1253 _dev_handle->claimed_interfaces = 0;
1254 memset(&_dev_handle->os_priv, 0, priv_size);
1256 r = usbi_backend->open(_dev_handle);
1258 usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
1259 libusb_unref_device(dev);
1260 usbi_mutex_destroy(&_dev_handle->lock);
1265 usbi_mutex_lock(&ctx->open_devs_lock);
1266 list_add(&_dev_handle->list, &ctx->open_devs);
1267 usbi_mutex_unlock(&ctx->open_devs_lock);
1268 *dev_handle = _dev_handle;
1273 /** \ingroup libusb_dev
1274 * Convenience function for finding a device with a particular
1275 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1276 * for those scenarios where you are using libusb to knock up a quick test
1277 * application - it allows you to avoid calling libusb_get_device_list() and
1278 * worrying about traversing/freeing the list.
1280 * This function has limitations and is hence not intended for use in real
1281 * applications: if multiple devices have the same IDs it will only
1282 * give you the first one, etc.
1284 * \param ctx the context to operate on, or NULL for the default context
1285 * \param vendor_id the idVendor value to search for
1286 * \param product_id the idProduct value to search for
1287 * \returns a device handle for the first found device, or NULL on error
1288 * or if the device could not be found. */
1290 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1291 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1293 struct libusb_device **devs;
1294 struct libusb_device *found = NULL;
1295 struct libusb_device *dev;
1296 struct libusb_device_handle *dev_handle = NULL;
1300 if (libusb_get_device_list(ctx, &devs) < 0)
1303 while ((dev = devs[i++]) != NULL) {
1304 struct libusb_device_descriptor desc;
1305 r = libusb_get_device_descriptor(dev, &desc);
1308 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1315 r = libusb_open(found, &dev_handle);
1321 libusb_free_device_list(devs, 1);
1325 static void do_close(struct libusb_context *ctx,
1326 struct libusb_device_handle *dev_handle)
1328 struct usbi_transfer *itransfer;
1329 struct usbi_transfer *tmp;
1331 libusb_lock_events(ctx);
1333 /* remove any transfers in flight that are for this device */
1334 usbi_mutex_lock(&ctx->flying_transfers_lock);
1336 /* safe iteration because transfers may be being deleted */
1337 list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
1338 struct libusb_transfer *transfer =
1339 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1341 if (transfer->dev_handle != dev_handle)
1344 if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1345 usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1347 if (itransfer->flags & USBI_TRANSFER_CANCELLING)
1348 usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1350 usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1353 /* remove from the list of in-flight transfers and make sure
1354 * we don't accidentally use the device handle in the future
1355 * (or that such accesses will be easily caught and identified as a crash)
1357 usbi_mutex_lock(&itransfer->lock);
1358 list_del(&itransfer->list);
1359 transfer->dev_handle = NULL;
1360 usbi_mutex_unlock(&itransfer->lock);
1362 /* it is up to the user to free up the actual transfer struct. this is
1363 * just making sure that we don't attempt to process the transfer after
1364 * the device handle is invalid
1366 usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
1367 transfer, dev_handle);
1369 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1371 libusb_unlock_events(ctx);
1373 usbi_mutex_lock(&ctx->open_devs_lock);
1374 list_del(&dev_handle->list);
1375 usbi_mutex_unlock(&ctx->open_devs_lock);
1377 usbi_backend->close(dev_handle);
1378 libusb_unref_device(dev_handle->dev);
1379 usbi_mutex_destroy(&dev_handle->lock);
1383 /** \ingroup libusb_dev
1384 * Close a device handle. Should be called on all open handles before your
1385 * application exits.
1387 * Internally, this function destroys the reference that was added by
1388 * libusb_open() on the given device.
1390 * This is a non-blocking function; no requests are sent over the bus.
1392 * \param dev_handle the device handle to close
1394 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1396 struct libusb_context *ctx;
1403 ctx = HANDLE_CTX(dev_handle);
1405 /* Similarly to libusb_open(), we want to interrupt all event handlers
1406 * at this point. More importantly, we want to perform the actual close of
1407 * the device while holding the event handling lock (preventing any other
1408 * thread from doing event handling) because we will be removing a file
1409 * descriptor from the polling loop. */
1411 /* Record that we are closing a device.
1412 * Only signal an event if there are no prior pending events. */
1413 usbi_mutex_lock(&ctx->event_data_lock);
1414 pending_events = usbi_pending_events(ctx);
1415 ctx->device_close++;
1416 if (!pending_events)
1417 usbi_signal_event(ctx);
1418 usbi_mutex_unlock(&ctx->event_data_lock);
1420 /* take event handling lock */
1421 libusb_lock_events(ctx);
1423 /* Close the device */
1424 do_close(ctx, dev_handle);
1426 /* We're done with closing this device.
1427 * Clear the event pipe if there are no further pending events. */
1428 usbi_mutex_lock(&ctx->event_data_lock);
1429 ctx->device_close--;
1430 pending_events = usbi_pending_events(ctx);
1431 if (!pending_events)
1432 usbi_clear_event(ctx);
1433 usbi_mutex_unlock(&ctx->event_data_lock);
1435 /* Release event handling lock and wake up event waiters */
1436 libusb_unlock_events(ctx);
1439 /** \ingroup libusb_dev
1440 * Get the underlying device for a device handle. This function does not modify
1441 * the reference count of the returned device, so do not feel compelled to
1442 * unreference it when you are done.
1443 * \param dev_handle a device handle
1444 * \returns the underlying device
1447 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1449 return dev_handle->dev;
1452 /** \ingroup libusb_dev
1453 * Determine the bConfigurationValue of the currently active configuration.
1455 * You could formulate your own control request to obtain this information,
1456 * but this function has the advantage that it may be able to retrieve the
1457 * information from operating system caches (no I/O involved).
1459 * If the OS does not cache this information, then this function will block
1460 * while a control transfer is submitted to retrieve the information.
1462 * This function will return a value of 0 in the <tt>config</tt> output
1463 * parameter if the device is in unconfigured state.
1465 * \param dev_handle a device handle
1466 * \param config output location for the bConfigurationValue of the active
1467 * configuration (only valid for return code 0)
1468 * \returns 0 on success
1469 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1470 * \returns another LIBUSB_ERROR code on other failure
1472 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev_handle,
1475 int r = LIBUSB_ERROR_NOT_SUPPORTED;
1478 if (usbi_backend->get_configuration)
1479 r = usbi_backend->get_configuration(dev_handle, config);
1481 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1483 usbi_dbg("falling back to control message");
1484 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
1485 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1487 usbi_err(HANDLE_CTX(dev_handle), "zero bytes returned in ctrl transfer?");
1488 r = LIBUSB_ERROR_IO;
1489 } else if (r == 1) {
1493 usbi_dbg("control failed, error %d", r);
1498 usbi_dbg("active config %d", *config);
1503 /** \ingroup libusb_dev
1504 * Set the active configuration for a device.
1506 * The operating system may or may not have already set an active
1507 * configuration on the device. It is up to your application to ensure the
1508 * correct configuration is selected before you attempt to claim interfaces
1509 * and perform other operations.
1511 * If you call this function on a device already configured with the selected
1512 * configuration, then this function will act as a lightweight device reset:
1513 * it will issue a SET_CONFIGURATION request using the current configuration,
1514 * causing most USB-related device state to be reset (altsetting reset to zero,
1515 * endpoint halts cleared, toggles reset).
1517 * You cannot change/reset configuration if your application has claimed
1518 * interfaces. It is advised to set the desired configuration before claiming
1521 * Alternatively you can call libusb_release_interface() first. Note if you
1522 * do things this way you must ensure that auto_detach_kernel_driver for
1523 * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
1524 * release the interface(s).
1526 * You cannot change/reset configuration if other applications or drivers have
1527 * claimed interfaces.
1529 * A configuration value of -1 will put the device in unconfigured state.
1530 * The USB specifications state that a configuration value of 0 does this,
1531 * however buggy devices exist which actually have a configuration 0.
1533 * You should always use this function rather than formulating your own
1534 * SET_CONFIGURATION control request. This is because the underlying operating
1535 * system needs to know when such changes happen.
1537 * This is a blocking function.
1539 * \param dev_handle a device handle
1540 * \param configuration the bConfigurationValue of the configuration you
1541 * wish to activate, or -1 if you wish to put the device in an unconfigured
1543 * \returns 0 on success
1544 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1545 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1546 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1547 * \returns another LIBUSB_ERROR code on other failure
1548 * \see libusb_set_auto_detach_kernel_driver()
1550 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev_handle,
1553 usbi_dbg("configuration %d", configuration);
1554 return usbi_backend->set_configuration(dev_handle, configuration);
1557 /** \ingroup libusb_dev
1558 * Claim an interface on a given device handle. You must claim the interface
1559 * you wish to use before you can perform I/O on any of its endpoints.
1561 * It is legal to attempt to claim an already-claimed interface, in which
1562 * case libusb just returns 0 without doing anything.
1564 * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
1565 * will be detached if necessary, on failure the detach error is returned.
1567 * Claiming of interfaces is a purely logical operation; it does not cause
1568 * any requests to be sent over the bus. Interface claiming is used to
1569 * instruct the underlying operating system that your application wishes
1570 * to take ownership of the interface.
1572 * This is a non-blocking function.
1574 * \param dev_handle a device handle
1575 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1577 * \returns 0 on success
1578 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1579 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1581 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1582 * \returns a LIBUSB_ERROR code on other failure
1583 * \see libusb_set_auto_detach_kernel_driver()
1585 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev_handle,
1586 int interface_number)
1590 usbi_dbg("interface %d", interface_number);
1591 if (interface_number >= USB_MAXINTERFACES)
1592 return LIBUSB_ERROR_INVALID_PARAM;
1594 if (!dev_handle->dev->attached)
1595 return LIBUSB_ERROR_NO_DEVICE;
1597 usbi_mutex_lock(&dev_handle->lock);
1598 if (dev_handle->claimed_interfaces & (1 << interface_number))
1601 r = usbi_backend->claim_interface(dev_handle, interface_number);
1603 dev_handle->claimed_interfaces |= 1 << interface_number;
1606 usbi_mutex_unlock(&dev_handle->lock);
1610 /** \ingroup libusb_dev
1611 * Release an interface previously claimed with libusb_claim_interface(). You
1612 * should release all claimed interfaces before closing a device handle.
1614 * This is a blocking function. A SET_INTERFACE control request will be sent
1615 * to the device, resetting interface state to the first alternate setting.
1617 * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
1618 * driver will be re-attached after releasing the interface.
1620 * \param dev_handle a device handle
1621 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1622 * previously-claimed interface
1623 * \returns 0 on success
1624 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1625 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1626 * \returns another LIBUSB_ERROR code on other failure
1627 * \see libusb_set_auto_detach_kernel_driver()
1629 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev_handle,
1630 int interface_number)
1634 usbi_dbg("interface %d", interface_number);
1635 if (interface_number >= USB_MAXINTERFACES)
1636 return LIBUSB_ERROR_INVALID_PARAM;
1638 usbi_mutex_lock(&dev_handle->lock);
1639 if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
1640 r = LIBUSB_ERROR_NOT_FOUND;
1644 r = usbi_backend->release_interface(dev_handle, interface_number);
1646 dev_handle->claimed_interfaces &= ~(1 << interface_number);
1649 usbi_mutex_unlock(&dev_handle->lock);
1653 /** \ingroup libusb_dev
1654 * Activate an alternate setting for an interface. The interface must have
1655 * been previously claimed with libusb_claim_interface().
1657 * You should always use this function rather than formulating your own
1658 * SET_INTERFACE control request. This is because the underlying operating
1659 * system needs to know when such changes happen.
1661 * This is a blocking function.
1663 * \param dev_handle a device handle
1664 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1665 * previously-claimed interface
1666 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1667 * setting to activate
1668 * \returns 0 on success
1669 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1670 * requested alternate setting does not exist
1671 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1672 * \returns another LIBUSB_ERROR code on other failure
1674 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
1675 int interface_number, int alternate_setting)
1677 usbi_dbg("interface %d altsetting %d",
1678 interface_number, alternate_setting);
1679 if (interface_number >= USB_MAXINTERFACES)
1680 return LIBUSB_ERROR_INVALID_PARAM;
1682 usbi_mutex_lock(&dev_handle->lock);
1683 if (!dev_handle->dev->attached) {
1684 usbi_mutex_unlock(&dev_handle->lock);
1685 return LIBUSB_ERROR_NO_DEVICE;
1688 if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
1689 usbi_mutex_unlock(&dev_handle->lock);
1690 return LIBUSB_ERROR_NOT_FOUND;
1692 usbi_mutex_unlock(&dev_handle->lock);
1694 return usbi_backend->set_interface_altsetting(dev_handle, interface_number,
1698 /** \ingroup libusb_dev
1699 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1700 * are unable to receive or transmit data until the halt condition is stalled.
1702 * You should cancel all pending transfers before attempting to clear the halt
1705 * This is a blocking function.
1707 * \param dev_handle a device handle
1708 * \param endpoint the endpoint to clear halt status
1709 * \returns 0 on success
1710 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1711 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1712 * \returns another LIBUSB_ERROR code on other failure
1714 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev_handle,
1715 unsigned char endpoint)
1717 usbi_dbg("endpoint %x", endpoint);
1718 if (!dev_handle->dev->attached)
1719 return LIBUSB_ERROR_NO_DEVICE;
1721 return usbi_backend->clear_halt(dev_handle, endpoint);
1724 /** \ingroup libusb_dev
1725 * Perform a USB port reset to reinitialize a device. The system will attempt
1726 * to restore the previous configuration and alternate settings after the
1727 * reset has completed.
1729 * If the reset fails, the descriptors change, or the previous state cannot be
1730 * restored, the device will appear to be disconnected and reconnected. This
1731 * means that the device handle is no longer valid (you should close it) and
1732 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1733 * when this is the case.
1735 * This is a blocking function which usually incurs a noticeable delay.
1737 * \param dev_handle a handle of the device to reset
1738 * \returns 0 on success
1739 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1740 * device has been disconnected
1741 * \returns another LIBUSB_ERROR code on other failure
1743 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev_handle)
1746 if (!dev_handle->dev->attached)
1747 return LIBUSB_ERROR_NO_DEVICE;
1749 return usbi_backend->reset_device(dev_handle);
1752 /** \ingroup libusb_asyncio
1753 * Allocate up to num_streams usb bulk streams on the specified endpoints. This
1754 * function takes an array of endpoints rather then a single endpoint because
1755 * some protocols require that endpoints are setup with similar stream ids.
1756 * All endpoints passed in must belong to the same interface.
1758 * Note this function may return less streams then requested. Also note that the
1759 * same number of streams are allocated for each endpoint in the endpoint array.
1761 * Stream id 0 is reserved, and should not be used to communicate with devices.
1762 * If libusb_alloc_streams() returns with a value of N, you may use stream ids
1765 * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1767 * \param dev_handle a device handle
1768 * \param num_streams number of streams to try to allocate
1769 * \param endpoints array of endpoints to allocate streams on
1770 * \param num_endpoints length of the endpoints array
1771 * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
1773 int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev_handle,
1774 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1776 usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints);
1778 if (!dev_handle->dev->attached)
1779 return LIBUSB_ERROR_NO_DEVICE;
1781 if (usbi_backend->alloc_streams)
1782 return usbi_backend->alloc_streams(dev_handle, num_streams, endpoints,
1785 return LIBUSB_ERROR_NOT_SUPPORTED;
1788 /** \ingroup libusb_asyncio
1789 * Free usb bulk streams allocated with libusb_alloc_streams().
1791 * Note streams are automatically free-ed when releasing an interface.
1793 * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1795 * \param dev_handle a device handle
1796 * \param endpoints array of endpoints to free streams on
1797 * \param num_endpoints length of the endpoints array
1798 * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1800 int API_EXPORTED libusb_free_streams(libusb_device_handle *dev_handle,
1801 unsigned char *endpoints, int num_endpoints)
1803 usbi_dbg("eps %d", num_endpoints);
1805 if (!dev_handle->dev->attached)
1806 return LIBUSB_ERROR_NO_DEVICE;
1808 if (usbi_backend->free_streams)
1809 return usbi_backend->free_streams(dev_handle, endpoints,
1812 return LIBUSB_ERROR_NOT_SUPPORTED;
1815 /** \ingroup libusb_dev
1816 * Determine if a kernel driver is active on an interface. If a kernel driver
1817 * is active, you cannot claim the interface, and libusb will be unable to
1820 * This functionality is not available on Windows.
1822 * \param dev_handle a device handle
1823 * \param interface_number the interface to check
1824 * \returns 0 if no kernel driver is active
1825 * \returns 1 if a kernel driver is active
1826 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1827 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1829 * \returns another LIBUSB_ERROR code on other failure
1830 * \see libusb_detach_kernel_driver()
1832 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev_handle,
1833 int interface_number)
1835 usbi_dbg("interface %d", interface_number);
1837 if (!dev_handle->dev->attached)
1838 return LIBUSB_ERROR_NO_DEVICE;
1840 if (usbi_backend->kernel_driver_active)
1841 return usbi_backend->kernel_driver_active(dev_handle, interface_number);
1843 return LIBUSB_ERROR_NOT_SUPPORTED;
1846 /** \ingroup libusb_dev
1847 * Detach a kernel driver from an interface. If successful, you will then be
1848 * able to claim the interface and perform I/O.
1850 * This functionality is not available on Darwin or Windows.
1852 * Note that libusb itself also talks to the device through a special kernel
1853 * driver, if this driver is already attached to the device, this call will
1854 * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1856 * \param dev_handle a device handle
1857 * \param interface_number the interface to detach the driver from
1858 * \returns 0 on success
1859 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1860 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1861 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1862 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1864 * \returns another LIBUSB_ERROR code on other failure
1865 * \see libusb_kernel_driver_active()
1867 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
1868 int interface_number)
1870 usbi_dbg("interface %d", interface_number);
1872 if (!dev_handle->dev->attached)
1873 return LIBUSB_ERROR_NO_DEVICE;
1875 if (usbi_backend->detach_kernel_driver)
1876 return usbi_backend->detach_kernel_driver(dev_handle, interface_number);
1878 return LIBUSB_ERROR_NOT_SUPPORTED;
1881 /** \ingroup libusb_dev
1882 * Re-attach an interface's kernel driver, which was previously detached
1883 * using libusb_detach_kernel_driver(). This call is only effective on
1884 * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1886 * This functionality is not available on Darwin or Windows.
1888 * \param dev_handle a device handle
1889 * \param interface_number the interface to attach the driver from
1890 * \returns 0 on success
1891 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1892 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1893 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1894 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1896 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1897 * interface is claimed by a program or driver
1898 * \returns another LIBUSB_ERROR code on other failure
1899 * \see libusb_kernel_driver_active()
1901 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
1902 int interface_number)
1904 usbi_dbg("interface %d", interface_number);
1906 if (!dev_handle->dev->attached)
1907 return LIBUSB_ERROR_NO_DEVICE;
1909 if (usbi_backend->attach_kernel_driver)
1910 return usbi_backend->attach_kernel_driver(dev_handle, interface_number);
1912 return LIBUSB_ERROR_NOT_SUPPORTED;
1915 /** \ingroup libusb_dev
1916 * Enable/disable libusb's automatic kernel driver detachment. When this is
1917 * enabled libusb will automatically detach the kernel driver on an interface
1918 * when claiming the interface, and attach it when releasing the interface.
1920 * Automatic kernel driver detachment is disabled on newly opened device
1921 * handles by default.
1923 * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
1924 * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
1925 * continue as if this function was never called.
1927 * \param dev_handle a device handle
1928 * \param enable whether to enable or disable auto kernel driver detachment
1930 * \returns LIBUSB_SUCCESS on success
1931 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1933 * \see libusb_claim_interface()
1934 * \see libusb_release_interface()
1935 * \see libusb_set_configuration()
1937 int API_EXPORTED libusb_set_auto_detach_kernel_driver(
1938 libusb_device_handle *dev_handle, int enable)
1940 if (!(usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
1941 return LIBUSB_ERROR_NOT_SUPPORTED;
1943 dev_handle->auto_detach_kernel_driver = enable;
1944 return LIBUSB_SUCCESS;
1947 /** \ingroup libusb_lib
1948 * Set log message verbosity.
1950 * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
1951 * printed. If you choose to increase the message verbosity level, ensure
1952 * that your application does not close the stdout/stderr file descriptors.
1954 * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusb is conservative
1955 * with its message logging and most of the time, will only log messages that
1956 * explain error conditions and other oddities. This will help you debug
1959 * If the LIBUSB_DEBUG environment variable was set when libusb was
1960 * initialized, this function does nothing: the message verbosity is fixed
1961 * to the value in the environment variable.
1963 * If libusb was compiled without any message logging, this function does
1964 * nothing: you'll never get any messages.
1966 * If libusb was compiled with verbose debug message logging, this function
1967 * does nothing: you'll always get messages from all levels.
1969 * \param ctx the context to operate on, or NULL for the default context
1970 * \param level debug level to set
1972 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
1974 USBI_GET_CONTEXT(ctx);
1975 if (!ctx->debug_fixed)
1979 /** \ingroup libusb_lib
1980 * Initialize libusb. This function must be called before calling any other
1983 * If you do not provide an output location for a context pointer, a default
1984 * context will be created. If there was already a default context, it will
1985 * be reused (and nothing will be initialized/reinitialized).
1987 * \param context Optional output location for context pointer.
1988 * Only valid on return code 0.
1989 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1990 * \see libusb_contexts
1992 int API_EXPORTED libusb_init(libusb_context **context)
1994 struct libusb_device *dev, *next;
1995 char *dbg = getenv("LIBUSB_DEBUG");
1996 struct libusb_context *ctx;
1997 static int first_init = 1;
2000 usbi_mutex_static_lock(&default_context_lock);
2002 if (!timestamp_origin.tv_sec) {
2003 usbi_gettimeofday(×tamp_origin, NULL);
2006 if (!context && usbi_default_context) {
2007 usbi_dbg("reusing default context");
2008 default_context_refcnt++;
2009 usbi_mutex_static_unlock(&default_context_lock);
2013 ctx = calloc(1, sizeof(*ctx));
2015 r = LIBUSB_ERROR_NO_MEM;
2019 #ifdef ENABLE_DEBUG_LOGGING
2020 ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
2024 ctx->debug = atoi(dbg);
2026 ctx->debug_fixed = 1;
2029 /* default context should be initialized before calling usbi_dbg */
2030 if (!usbi_default_context) {
2031 usbi_default_context = ctx;
2032 default_context_refcnt++;
2033 usbi_dbg("created default context");
2036 usbi_dbg("libusb v%u.%u.%u.%u%s", libusb_version_internal.major, libusb_version_internal.minor,
2037 libusb_version_internal.micro, libusb_version_internal.nano, libusb_version_internal.rc);
2039 usbi_mutex_init(&ctx->usb_devs_lock);
2040 usbi_mutex_init(&ctx->open_devs_lock);
2041 usbi_mutex_init(&ctx->hotplug_cbs_lock);
2042 list_init(&ctx->usb_devs);
2043 list_init(&ctx->open_devs);
2044 list_init(&ctx->hotplug_cbs);
2046 usbi_mutex_static_lock(&active_contexts_lock);
2049 list_init (&active_contexts_list);
2051 list_add (&ctx->list, &active_contexts_list);
2052 usbi_mutex_static_unlock(&active_contexts_lock);
2054 if (usbi_backend->init) {
2055 r = usbi_backend->init(ctx);
2060 r = usbi_io_init(ctx);
2062 goto err_backend_exit;
2064 usbi_mutex_static_unlock(&default_context_lock);
2072 if (usbi_backend->exit)
2073 usbi_backend->exit();
2075 if (ctx == usbi_default_context) {
2076 usbi_default_context = NULL;
2077 default_context_refcnt--;
2080 usbi_mutex_static_lock(&active_contexts_lock);
2081 list_del (&ctx->list);
2082 usbi_mutex_static_unlock(&active_contexts_lock);
2084 usbi_mutex_lock(&ctx->usb_devs_lock);
2085 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
2086 list_del(&dev->list);
2087 libusb_unref_device(dev);
2089 usbi_mutex_unlock(&ctx->usb_devs_lock);
2091 usbi_mutex_destroy(&ctx->open_devs_lock);
2092 usbi_mutex_destroy(&ctx->usb_devs_lock);
2093 usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2097 usbi_mutex_static_unlock(&default_context_lock);
2101 /** \ingroup libusb_lib
2102 * Deinitialize libusb. Should be called after closing all open devices and
2103 * before your application terminates.
2104 * \param ctx the context to deinitialize, or NULL for the default context
2106 void API_EXPORTED libusb_exit(struct libusb_context *ctx)
2108 struct libusb_device *dev, *next;
2109 struct timeval tv = { 0, 0 };
2112 USBI_GET_CONTEXT(ctx);
2114 /* if working with default context, only actually do the deinitialization
2115 * if we're the last user */
2116 usbi_mutex_static_lock(&default_context_lock);
2117 if (ctx == usbi_default_context) {
2118 if (--default_context_refcnt > 0) {
2119 usbi_dbg("not destroying default context");
2120 usbi_mutex_static_unlock(&default_context_lock);
2123 usbi_dbg("destroying default context");
2124 usbi_default_context = NULL;
2126 usbi_mutex_static_unlock(&default_context_lock);
2128 usbi_mutex_static_lock(&active_contexts_lock);
2129 list_del (&ctx->list);
2130 usbi_mutex_static_unlock(&active_contexts_lock);
2132 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
2133 usbi_hotplug_deregister_all(ctx);
2136 * Ensure any pending unplug events are read from the hotplug
2137 * pipe. The usb_device-s hold in the events are no longer part
2138 * of usb_devs, but the events still hold a reference!
2140 * Note we don't do this if the application has left devices
2141 * open (which implies a buggy app) to avoid packet completion
2142 * handlers running when the app does not expect them to run.
2144 if (list_empty(&ctx->open_devs))
2145 libusb_handle_events_timeout(ctx, &tv);
2147 usbi_mutex_lock(&ctx->usb_devs_lock);
2148 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
2149 list_del(&dev->list);
2150 libusb_unref_device(dev);
2152 usbi_mutex_unlock(&ctx->usb_devs_lock);
2155 /* a few sanity checks. don't bother with locking because unless
2156 * there is an application bug, nobody will be accessing these. */
2157 if (!list_empty(&ctx->usb_devs))
2158 usbi_warn(ctx, "some libusb_devices were leaked");
2159 if (!list_empty(&ctx->open_devs))
2160 usbi_warn(ctx, "application left some devices open");
2163 if (usbi_backend->exit)
2164 usbi_backend->exit();
2166 usbi_mutex_destroy(&ctx->open_devs_lock);
2167 usbi_mutex_destroy(&ctx->usb_devs_lock);
2168 usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2172 /** \ingroup libusb_misc
2173 * Check at runtime if the loaded library has a given capability.
2174 * This call should be performed after \ref libusb_init(), to ensure the
2175 * backend has updated its capability set.
2177 * \param capability the \ref libusb_capability to check for
2178 * \returns nonzero if the running library has the capability, 0 otherwise
2180 int API_EXPORTED libusb_has_capability(uint32_t capability)
2182 switch (capability) {
2183 case LIBUSB_CAP_HAS_CAPABILITY:
2185 case LIBUSB_CAP_HAS_HOTPLUG:
2186 return !(usbi_backend->get_device_list);
2187 case LIBUSB_CAP_HAS_HID_ACCESS:
2188 return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS);
2189 case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
2190 return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
2195 /* this is defined in libusbi.h if needed */
2196 #ifdef LIBUSB_GETTIMEOFDAY_WIN32
2199 * Implementation according to:
2200 * The Open Group Base Specifications Issue 6
2201 * IEEE Std 1003.1, 2004 Edition
2205 * THIS SOFTWARE IS NOT COPYRIGHTED
2207 * This source code is offered for use in the public domain. You may
2208 * use, modify or distribute it freely.
2210 * This code is distributed in the hope that it will be useful but
2211 * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
2212 * DISCLAIMED. This includes but is not limited to warranties of
2213 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2216 * Danny Smith <dannysmith@users.sourceforge.net>
2219 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
2220 #define _W32_FT_OFFSET (116444736000000000)
2222 int usbi_gettimeofday(struct timeval *tp, void *tzp)
2225 unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
2231 #if defined(OS_WINCE)
2234 SystemTimeToFileTime(&st, &_now.ft);
2236 GetSystemTimeAsFileTime (&_now.ft);
2238 tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
2239 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
2241 /* Always return 0 as per Open Group Base Specifications Issue 6.
2242 Do not set errno on error. */
2247 static void usbi_log_str(struct libusb_context *ctx,
2248 enum libusb_log_level level, const char * str)
2250 #if defined(USE_SYSTEM_LOGGING_FACILITY)
2251 #if defined(OS_WINDOWS) || defined(OS_WINCE)
2252 /* Windows CE only supports the Unicode version of OutputDebugString. */
2253 WCHAR wbuf[USBI_MAX_LOG_LEN];
2254 MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
2255 OutputDebugStringW(wbuf);
2256 #elif defined(__ANDROID__)
2257 int priority = ANDROID_LOG_UNKNOWN;
2259 case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
2260 case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
2261 case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
2262 case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
2264 __android_log_write(priority, "libusb", str);
2265 #elif defined(HAVE_SYSLOG_FUNC)
2266 int syslog_level = LOG_INFO;
2268 case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
2269 case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
2270 case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
2271 case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
2273 syslog(syslog_level, "%s", str);
2274 #else /* All of gcc, Clang, XCode seem to use #warning */
2275 #warning System logging is not supported on this platform. Logging to stderr will be used instead.
2280 #endif /* USE_SYSTEM_LOGGING_FACILITY */
2285 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
2286 const char *function, const char *format, va_list args)
2288 const char *prefix = "";
2289 char buf[USBI_MAX_LOG_LEN];
2291 int global_debug, header_len, text_len;
2292 static int has_debug_header_been_displayed = 0;
2294 #ifdef ENABLE_DEBUG_LOGGING
2300 USBI_GET_CONTEXT(ctx);
2302 ctx_level = ctx->debug;
2304 char *dbg = getenv("LIBUSB_DEBUG");
2306 ctx_level = atoi(dbg);
2308 global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
2311 if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING)
2313 if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO)
2315 if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG)
2319 usbi_gettimeofday(&now, NULL);
2320 if ((global_debug) && (!has_debug_header_been_displayed)) {
2321 has_debug_header_been_displayed = 1;
2322 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>" USBI_LOG_LINE_END);
2323 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END);
2325 if (now.tv_usec < timestamp_origin.tv_usec) {
2327 now.tv_usec += 1000000;
2329 now.tv_sec -= timestamp_origin.tv_sec;
2330 now.tv_usec -= timestamp_origin.tv_usec;
2333 case LIBUSB_LOG_LEVEL_INFO:
2336 case LIBUSB_LOG_LEVEL_WARNING:
2339 case LIBUSB_LOG_LEVEL_ERROR:
2342 case LIBUSB_LOG_LEVEL_DEBUG:
2345 case LIBUSB_LOG_LEVEL_NONE:
2353 header_len = snprintf(buf, sizeof(buf),
2354 "[%2d.%06d] [%08x] libusb: %s [%s] ",
2355 (int)now.tv_sec, (int)now.tv_usec, usbi_get_tid(), prefix, function);
2357 header_len = snprintf(buf, sizeof(buf),
2358 "libusb: %s [%s] ", prefix, function);
2361 if (header_len < 0 || header_len >= (int)sizeof(buf)) {
2362 /* Somehow snprintf failed to write to the buffer,
2363 * remove the header so something useful is output. */
2366 /* Make sure buffer is NUL terminated */
2367 buf[header_len] = '\0';
2368 text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
2370 if (text_len < 0 || text_len + header_len >= (int)sizeof(buf)) {
2371 /* Truncated log output. On some platforms a -1 return value means
2372 * that the output was truncated. */
2373 text_len = sizeof(buf) - header_len;
2375 if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
2376 /* Need to truncate the text slightly to fit on the terminator. */
2377 text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
2379 strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
2381 usbi_log_str(ctx, level, buf);
2384 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
2385 const char *function, const char *format, ...)
2389 va_start (args, format);
2390 usbi_log_v(ctx, level, function, format, args);
2394 /** \ingroup libusb_misc
2395 * Returns a constant NULL-terminated string with the ASCII name of a libusb
2396 * error or transfer status code. The caller must not free() the returned
2399 * \param error_code The \ref libusb_error or libusb_transfer_status code to
2400 * return the name of.
2401 * \returns The error name, or the string **UNKNOWN** if the value of
2402 * error_code is not a known error / status code.
2404 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
2406 switch (error_code) {
2407 case LIBUSB_ERROR_IO:
2408 return "LIBUSB_ERROR_IO";
2409 case LIBUSB_ERROR_INVALID_PARAM:
2410 return "LIBUSB_ERROR_INVALID_PARAM";
2411 case LIBUSB_ERROR_ACCESS:
2412 return "LIBUSB_ERROR_ACCESS";
2413 case LIBUSB_ERROR_NO_DEVICE:
2414 return "LIBUSB_ERROR_NO_DEVICE";
2415 case LIBUSB_ERROR_NOT_FOUND:
2416 return "LIBUSB_ERROR_NOT_FOUND";
2417 case LIBUSB_ERROR_BUSY:
2418 return "LIBUSB_ERROR_BUSY";
2419 case LIBUSB_ERROR_TIMEOUT:
2420 return "LIBUSB_ERROR_TIMEOUT";
2421 case LIBUSB_ERROR_OVERFLOW:
2422 return "LIBUSB_ERROR_OVERFLOW";
2423 case LIBUSB_ERROR_PIPE:
2424 return "LIBUSB_ERROR_PIPE";
2425 case LIBUSB_ERROR_INTERRUPTED:
2426 return "LIBUSB_ERROR_INTERRUPTED";
2427 case LIBUSB_ERROR_NO_MEM:
2428 return "LIBUSB_ERROR_NO_MEM";
2429 case LIBUSB_ERROR_NOT_SUPPORTED:
2430 return "LIBUSB_ERROR_NOT_SUPPORTED";
2431 case LIBUSB_ERROR_OTHER:
2432 return "LIBUSB_ERROR_OTHER";
2434 case LIBUSB_TRANSFER_ERROR:
2435 return "LIBUSB_TRANSFER_ERROR";
2436 case LIBUSB_TRANSFER_TIMED_OUT:
2437 return "LIBUSB_TRANSFER_TIMED_OUT";
2438 case LIBUSB_TRANSFER_CANCELLED:
2439 return "LIBUSB_TRANSFER_CANCELLED";
2440 case LIBUSB_TRANSFER_STALL:
2441 return "LIBUSB_TRANSFER_STALL";
2442 case LIBUSB_TRANSFER_NO_DEVICE:
2443 return "LIBUSB_TRANSFER_NO_DEVICE";
2444 case LIBUSB_TRANSFER_OVERFLOW:
2445 return "LIBUSB_TRANSFER_OVERFLOW";
2448 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
2450 return "**UNKNOWN**";
2454 /** \ingroup libusb_misc
2455 * Returns a pointer to const struct libusb_version with the version
2456 * (major, minor, micro, nano and rc) of the running library.
2459 const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
2461 return &libusb_version_internal;