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;
67 #elif defined (OS_SUNOS)
68 const struct usbi_os_backend * const usbi_backend = &sunos_backend;
70 #error "Unsupported OS"
73 struct libusb_context *usbi_default_context = NULL;
74 static const struct libusb_version libusb_version_internal =
75 { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
76 LIBUSB_RC, "http://libusb.info" };
77 static int default_context_refcnt = 0;
78 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
79 static struct timespec timestamp_origin = { 0, 0 };
81 usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
82 struct list_head active_contexts_list;
85 * \mainpage libusb-1.0 API Reference
87 * \section intro Introduction
89 * libusb is an open source library that allows you to communicate with USB
90 * devices from userspace. For more info, see the
91 * <a href="http://libusb.info">libusb homepage</a>.
93 * This documentation is aimed at application developers wishing to
94 * communicate with USB peripherals from their own software. After reviewing
95 * this documentation, feedback and questions can be sent to the
96 * <a href="http://mailing-list.libusb.info">libusb-devel mailing list</a>.
98 * This documentation assumes knowledge of how to operate USB devices from
99 * a software standpoint (descriptors, configurations, interfaces, endpoints,
100 * control/bulk/interrupt/isochronous transfers, etc). Full information
101 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
102 * Specification</a> which is available for free download. You can probably
103 * find less verbose introductions by searching the web.
105 * \section API Application Programming Interface (API)
107 * See the \ref libusb_api page for a complete list of the libusb functions.
109 * \section features Library features
111 * - All transfer types supported (control/bulk/interrupt/isochronous)
112 * - 2 transfer interfaces:
113 * -# Synchronous (simple)
114 * -# Asynchronous (more complicated, but more powerful)
115 * - Thread safe (although the asynchronous interface means that you
116 * usually won't need to thread)
117 * - Lightweight with lean API
118 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
119 * - Hotplug support (on some platforms). See \ref libusb_hotplug.
121 * \section gettingstarted Getting Started
123 * To begin reading the API documentation, start with the Modules page which
124 * links to the different categories of libusb's functionality.
126 * One decision you will have to make is whether to use the synchronous
127 * or the asynchronous data transfer interface. The \ref libusb_io documentation
128 * provides some insight into this topic.
130 * Some example programs can be found in the libusb source distribution under
131 * the "examples" subdirectory. The libusb homepage includes a list of
132 * real-life project examples which use libusb.
134 * \section errorhandling Error handling
136 * libusb functions typically return 0 on success or a negative error code
137 * on failure. These negative error codes relate to LIBUSB_ERROR constants
138 * which are listed on the \ref libusb_misc "miscellaneous" documentation page.
140 * \section msglog Debug message logging
142 * libusb uses stderr for all logging. By default, logging is set to NONE,
143 * which means that no output will be produced. However, unless the library
144 * has been compiled with logging disabled, then any application calls to
145 * libusb_set_debug(), or the setting of the environmental variable
146 * LIBUSB_DEBUG outside of the application, can result in logging being
147 * produced. Your application should therefore not close stderr, but instead
148 * direct it to the null device if its output is undesirable.
150 * The libusb_set_debug() function can be used to enable logging of certain
151 * messages. Under standard configuration, libusb doesn't really log much
152 * so you are advised to use this function to enable all error/warning/
153 * informational messages. It will help debug problems with your software.
155 * The logged messages are unstructured. There is no one-to-one correspondence
156 * between messages being logged and success or failure return codes from
157 * libusb functions. There is no format to the messages, so you should not
158 * try to capture or parse them. They are not and will not be localized.
159 * These messages are not intended to being passed to your application user;
160 * instead, you should interpret the error codes returned from libusb functions
161 * and provide appropriate notification to the user. The messages are simply
162 * there to aid you as a programmer, and if you're confused because you're
163 * getting a strange error code from a libusb function, enabling message
164 * logging may give you a suitable explanation.
166 * The LIBUSB_DEBUG environment variable can be used to enable message logging
167 * at run-time. This environment variable should be set to a log level number,
168 * which is interpreted the same as the libusb_set_debug() parameter. When this
169 * environment variable is set, the message logging verbosity level is fixed
170 * and libusb_set_debug() effectively does nothing.
172 * libusb can be compiled without any logging functions, useful for embedded
173 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
174 * variable have no effects.
176 * libusb can also be compiled with verbose debugging messages always. When
177 * the library is compiled in this way, all messages of all verbosities are
178 * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
181 * \section remarks Other remarks
183 * libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts
188 * \page libusb_caveats Caveats
190 * \section devresets Device resets
192 * The libusb_reset_device() function allows you to reset a device. If your
193 * program has to call such a function, it should obviously be aware that
194 * the reset will cause device state to change (e.g. register values may be
197 * The problem is that any other program could reset the device your program
198 * is working with, at any time. libusb does not offer a mechanism to inform
199 * you when this has happened, so if someone else resets your device it will
200 * not be clear to your own program why the device state has changed.
202 * Ultimately, this is a limitation of writing drivers in userspace.
203 * Separation from the USB stack in the underlying kernel makes it difficult
204 * for the operating system to deliver such notifications to your program.
205 * The Linux kernel USB stack allows such reset notifications to be delivered
206 * to in-kernel USB drivers, but it is not clear how such notifications could
207 * be delivered to second-class drivers that live in userspace.
209 * \section blockonly Blocking-only functionality
211 * The functionality listed below is only available through synchronous,
212 * blocking functions. There are no asynchronous/non-blocking alternatives,
213 * and no clear ways of implementing these.
215 * - Configuration activation (libusb_set_configuration())
216 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
217 * - Releasing of interfaces (libusb_release_interface())
218 * - Clearing of halt/stall condition (libusb_clear_halt())
219 * - Device resets (libusb_reset_device())
221 * \section configsel Configuration selection and handling
223 * When libusb presents a device handle to an application, there is a chance
224 * that the corresponding device may be in unconfigured state. For devices
225 * with multiple configurations, there is also a chance that the configuration
226 * currently selected is not the one that the application wants to use.
228 * The obvious solution is to add a call to libusb_set_configuration() early
229 * on during your device initialization routines, but there are caveats to
231 * -# If the device is already in the desired configuration, calling
232 * libusb_set_configuration() using the same configuration value will cause
233 * a lightweight device reset. This may not be desirable behaviour.
234 * -# In the case where the desired configuration is already active, libusb
235 * may not even be able to perform a lightweight device reset. For example,
236 * take my USB keyboard with fingerprint reader: I'm interested in driving
237 * the fingerprint reader interface through libusb, but the kernel's
238 * USB-HID driver will almost always have claimed the keyboard interface.
239 * Because the kernel has claimed an interface, it is not even possible to
240 * perform the lightweight device reset, so libusb_set_configuration() will
241 * fail. (Luckily the device in question only has a single configuration.)
242 * -# libusb will be unable to set a configuration if other programs or
243 * drivers have claimed interfaces. In particular, this means that kernel
244 * drivers must be detached from all the interfaces before
245 * libusb_set_configuration() may succeed.
247 * One solution to some of the above problems is to consider the currently
248 * active configuration. If the configuration we want is already active, then
249 * we don't have to select any configuration:
252 libusb_get_configuration(dev, &cfg);
254 libusb_set_configuration(dev, desired);
257 * This is probably suitable for most scenarios, but is inherently racy:
258 * another application or driver may change the selected configuration
259 * <em>after</em> the libusb_get_configuration() call.
261 * Even in cases where libusb_set_configuration() succeeds, consider that other
262 * applications or drivers may change configuration after your application
263 * calls libusb_set_configuration().
265 * One possible way to lock your device into a specific configuration is as
267 * -# Set the desired configuration (or use the logic above to realise that
268 * it is already in the desired configuration)
269 * -# Claim the interface that you wish to use
270 * -# Check that the currently active configuration is the one that you want
273 * The above method works because once an interface is claimed, no application
274 * or driver is able to select another configuration.
276 * \section earlycomp Early transfer completion
278 * NOTE: This section is currently Linux-centric. I am not sure if any of these
279 * considerations apply to Darwin or other platforms.
281 * When a transfer completes early (i.e. when less data is received/sent in
282 * any one packet than the transfer buffer allows for) then libusb is designed
283 * to terminate the transfer immediately, not transferring or receiving any
284 * more data unless other transfers have been queued by the user.
286 * On legacy platforms, libusb is unable to do this in all situations. After
287 * the incomplete packet occurs, "surplus" data may be transferred. For recent
288 * versions of libusb, this information is kept (the data length of the
289 * transfer is updated) and, for device-to-host transfers, any surplus data was
290 * added to the buffer. Still, this is not a nice solution because it loses the
291 * information about the end of the short packet, and the user probably wanted
292 * that surplus data to arrive in the next logical transfer.
295 * \section zlp Zero length packets
297 * - libusb is able to send a packet of zero length to an endpoint simply by
298 * submitting a transfer of zero length.
299 * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
300 * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
304 * \page libusb_contexts Contexts
306 * It is possible that libusb may be used simultaneously from two independent
307 * libraries linked into the same executable. For example, if your application
308 * has a plugin-like system which allows the user to dynamically load a range
309 * of modules into your program, it is feasible that two independently
310 * developed modules may both use libusb.
312 * libusb is written to allow for these multiple user scenarios. The two
313 * "instances" of libusb will not interfere: libusb_set_debug() calls
314 * from one user will not affect the same settings for other users, other
315 * users can continue using libusb after one of them calls libusb_exit(), etc.
317 * This is made possible through libusb's <em>context</em> concept. When you
318 * call libusb_init(), you are (optionally) given a context. You can then pass
319 * this context pointer back into future libusb functions.
321 * In order to keep things simple for more simplistic applications, it is
322 * legal to pass NULL to all functions requiring a context pointer (as long as
323 * you're sure no other code will attempt to use libusb from the same process).
324 * When you pass NULL, the default context will be used. The default context
325 * is created the first time a process calls libusb_init() when no other
326 * context is alive. Contexts are destroyed during libusb_exit().
328 * The default context is reference-counted and can be shared. That means that
329 * if libusb_init(NULL) is called twice within the same process, the two
330 * users end up sharing the same context. The deinitialization and freeing of
331 * the default context will only happen when the last user calls libusb_exit().
332 * In other words, the default context is created and initialized when its
333 * reference count goes from 0 to 1, and is deinitialized and destroyed when
334 * its reference count goes from 1 to 0.
336 * You may be wondering why only a subset of libusb functions require a
337 * context pointer in their function definition. Internally, libusb stores
338 * context pointers in other objects (e.g. libusb_device instances) and hence
339 * can infer the context from those objects.
343 * \page libusb_api Application Programming Interface
345 * This is the complete list of libusb functions, structures and
346 * enumerations in alphabetical order.
349 * - libusb_alloc_streams()
350 * - libusb_alloc_transfer()
351 * - libusb_attach_kernel_driver()
352 * - libusb_bulk_transfer()
353 * - libusb_cancel_transfer()
354 * - libusb_claim_interface()
355 * - libusb_clear_halt()
357 * - libusb_control_transfer()
358 * - libusb_control_transfer_get_data()
359 * - libusb_control_transfer_get_setup()
360 * - libusb_cpu_to_le16()
361 * - libusb_detach_kernel_driver()
362 * - libusb_dev_mem_alloc()
363 * - libusb_dev_mem_free()
364 * - libusb_error_name()
365 * - libusb_event_handler_active()
366 * - libusb_event_handling_ok()
368 * - libusb_fill_bulk_stream_transfer()
369 * - libusb_fill_bulk_transfer()
370 * - libusb_fill_control_setup()
371 * - libusb_fill_control_transfer()
372 * - libusb_fill_interrupt_transfer()
373 * - libusb_fill_iso_transfer()
374 * - libusb_free_bos_descriptor()
375 * - libusb_free_config_descriptor()
376 * - libusb_free_container_id_descriptor()
377 * - libusb_free_device_list()
378 * - libusb_free_pollfds()
379 * - libusb_free_ss_endpoint_companion_descriptor()
380 * - libusb_free_ss_usb_device_capability_descriptor()
381 * - libusb_free_streams()
382 * - libusb_free_transfer()
383 * - libusb_free_usb_2_0_extension_descriptor()
384 * - libusb_get_active_config_descriptor()
385 * - libusb_get_bos_descriptor()
386 * - libusb_get_bus_number()
387 * - libusb_get_config_descriptor()
388 * - libusb_get_config_descriptor_by_value()
389 * - libusb_get_configuration()
390 * - libusb_get_container_id_descriptor()
391 * - libusb_get_descriptor()
392 * - libusb_get_device()
393 * - libusb_get_device_address()
394 * - libusb_get_device_descriptor()
395 * - libusb_get_device_list()
396 * - libusb_get_device_speed()
397 * - libusb_get_iso_packet_buffer()
398 * - libusb_get_iso_packet_buffer_simple()
399 * - libusb_get_max_iso_packet_size()
400 * - libusb_get_max_packet_size()
401 * - libusb_get_next_timeout()
402 * - libusb_get_parent()
403 * - libusb_get_pollfds()
404 * - libusb_get_port_number()
405 * - libusb_get_port_numbers()
406 * - libusb_get_port_path()
407 * - libusb_get_ss_endpoint_companion_descriptor()
408 * - libusb_get_ss_usb_device_capability_descriptor()
409 * - libusb_get_string_descriptor()
410 * - libusb_get_string_descriptor_ascii()
411 * - libusb_get_usb_2_0_extension_descriptor()
412 * - libusb_get_version()
413 * - libusb_handle_events()
414 * - libusb_handle_events_completed()
415 * - libusb_handle_events_locked()
416 * - libusb_handle_events_timeout()
417 * - libusb_handle_events_timeout_completed()
418 * - libusb_has_capability()
419 * - libusb_hotplug_deregister_callback()
420 * - libusb_hotplug_register_callback()
422 * - libusb_interrupt_event_handler()
423 * - libusb_interrupt_transfer()
424 * - libusb_kernel_driver_active()
425 * - libusb_lock_events()
426 * - libusb_lock_event_waiters()
428 * - libusb_open_device_with_vid_pid()
429 * - libusb_pollfds_handle_timeouts()
430 * - libusb_ref_device()
431 * - libusb_release_interface()
432 * - libusb_reset_device()
433 * - libusb_set_auto_detach_kernel_driver()
434 * - libusb_set_configuration()
435 * - libusb_set_debug()
436 * - libusb_set_interface_alt_setting()
437 * - libusb_set_iso_packet_lengths()
438 * - libusb_setlocale()
439 * - libusb_set_pollfd_notifiers()
440 * - libusb_strerror()
441 * - libusb_submit_transfer()
442 * - libusb_transfer_get_stream_id()
443 * - libusb_transfer_set_stream_id()
444 * - libusb_try_lock_events()
445 * - libusb_unlock_events()
446 * - libusb_unlock_event_waiters()
447 * - libusb_unref_device()
448 * - libusb_wait_for_event()
450 * \section Structures
451 * - libusb_bos_descriptor
452 * - libusb_bos_dev_capability_descriptor
453 * - libusb_config_descriptor
454 * - libusb_container_id_descriptor
455 * - \ref libusb_context
456 * - libusb_control_setup
457 * - \ref libusb_device
458 * - libusb_device_descriptor
459 * - \ref libusb_device_handle
460 * - libusb_endpoint_descriptor
462 * - libusb_interface_descriptor
463 * - libusb_iso_packet_descriptor
465 * - libusb_ss_endpoint_companion_descriptor
466 * - libusb_ss_usb_device_capability_descriptor
468 * - libusb_usb_2_0_extension_descriptor
472 * - \ref libusb_bos_type
473 * - \ref libusb_capability
474 * - \ref libusb_class_code
475 * - \ref libusb_descriptor_type
476 * - \ref libusb_endpoint_direction
477 * - \ref libusb_error
478 * - \ref libusb_iso_sync_type
479 * - \ref libusb_iso_usage_type
480 * - \ref libusb_log_level
481 * - \ref libusb_request_recipient
482 * - \ref libusb_request_type
483 * - \ref libusb_speed
484 * - \ref libusb_ss_usb_device_capability_attributes
485 * - \ref libusb_standard_request
486 * - \ref libusb_supported_speed
487 * - \ref libusb_transfer_flags
488 * - \ref libusb_transfer_status
489 * - \ref libusb_transfer_type
490 * - \ref libusb_usb_2_0_extension_attributes
494 * @defgroup libusb_lib Library initialization/deinitialization
495 * This page details how to initialize and deinitialize libusb. Initialization
496 * must be performed before using any libusb functionality, and similarly you
497 * must not call any libusb functions after deinitialization.
501 * @defgroup libusb_dev Device handling and enumeration
502 * The functionality documented below is designed to help with the following
504 * - Enumerating the USB devices currently attached to the system
505 * - Choosing a device to operate from your software
506 * - Opening and closing the chosen device
508 * \section nutshell In a nutshell...
510 * The description below really makes things sound more complicated than they
511 * actually are. The following sequence of function calls will be suitable
512 * for almost all scenarios and does not require you to have such a deep
513 * understanding of the resource management issues:
516 libusb_device **list;
517 libusb_device *found = NULL;
518 ssize_t cnt = libusb_get_device_list(NULL, &list);
524 for (i = 0; i < cnt; i++) {
525 libusb_device *device = list[i];
526 if (is_interesting(device)) {
533 libusb_device_handle *handle;
535 err = libusb_open(found, &handle);
541 libusb_free_device_list(list, 1);
544 * The two important points:
545 * - You asked libusb_free_device_list() to unreference the devices (2nd
547 * - You opened the device before freeing the list and unreferencing the
550 * If you ended up with a handle, you can now proceed to perform I/O on the
553 * \section devshandles Devices and device handles
554 * libusb has a concept of a USB device, represented by the
555 * \ref libusb_device opaque type. A device represents a USB device that
556 * is currently or was previously connected to the system. Using a reference
557 * to a device, you can determine certain information about the device (e.g.
558 * you can read the descriptor data).
560 * The libusb_get_device_list() function can be used to obtain a list of
561 * devices currently connected to the system. This is known as device
564 * Just because you have a reference to a device does not mean it is
565 * necessarily usable. The device may have been unplugged, you may not have
566 * permission to operate such device, or another program or driver may be
569 * When you've found a device that you'd like to operate, you must ask
570 * libusb to open the device using the libusb_open() function. Assuming
571 * success, libusb then returns you a <em>device handle</em>
572 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
573 * operate on the handle rather than the original device pointer.
575 * \section devref Device discovery and reference counting
577 * Device discovery (i.e. calling libusb_get_device_list()) returns a
578 * freshly-allocated list of devices. The list itself must be freed when
579 * you are done with it. libusb also needs to know when it is OK to free
580 * the contents of the list - the devices themselves.
582 * To handle these issues, libusb provides you with two separate items:
583 * - A function to free the list itself
584 * - A reference counting system for the devices inside
586 * New devices presented by the libusb_get_device_list() function all have a
587 * reference count of 1. You can increase and decrease reference count using
588 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
589 * its reference count reaches 0.
591 * With the above information in mind, the process of opening a device can
592 * be viewed as follows:
593 * -# Discover devices using libusb_get_device_list().
594 * -# Choose the device that you want to operate, and call libusb_open().
595 * -# Unref all devices in the discovered device list.
596 * -# Free the discovered device list.
598 * The order is important - you must not unreference the device before
599 * attempting to open it, because unreferencing it may destroy the device.
601 * For convenience, the libusb_free_device_list() function includes a
602 * parameter to optionally unreference all the devices in the list before
603 * freeing the list itself. This combines steps 3 and 4 above.
605 * As an implementation detail, libusb_open() actually adds a reference to
606 * the device in question. This is because the device remains available
607 * through the handle via libusb_get_device(). The reference is deleted during
611 /** @defgroup libusb_misc Miscellaneous */
613 /* we traverse usbfs without knowing how many devices we are going to find.
614 * so we create this discovered_devs model which is similar to a linked-list
615 * which grows when required. it can be freed once discovery has completed,
616 * eliminating the need for a list node in the libusb_device structure
618 #define DISCOVERED_DEVICES_SIZE_STEP 8
620 static struct discovered_devs *discovered_devs_alloc(void)
622 struct discovered_devs *ret =
623 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
627 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
632 static void discovered_devs_free(struct discovered_devs *discdevs)
636 for (i = 0; i < discdevs->len; i++)
637 libusb_unref_device(discdevs->devices[i]);
642 /* append a device to the discovered devices collection. may realloc itself,
643 * returning new discdevs. returns NULL on realloc failure. */
644 struct discovered_devs *discovered_devs_append(
645 struct discovered_devs *discdevs, struct libusb_device *dev)
647 size_t len = discdevs->len;
649 struct discovered_devs *new_discdevs;
651 /* if there is space, just append the device */
652 if (len < discdevs->capacity) {
653 discdevs->devices[len] = libusb_ref_device(dev);
658 /* exceeded capacity, need to grow */
659 usbi_dbg("need to increase capacity");
660 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
661 /* can't use usbi_reallocf here because in failure cases it would
662 * free the existing discdevs without unreferencing its devices. */
663 new_discdevs = realloc(discdevs,
664 sizeof(*discdevs) + (sizeof(void *) * capacity));
666 discovered_devs_free(discdevs);
670 discdevs = new_discdevs;
671 discdevs->capacity = capacity;
672 discdevs->devices[len] = libusb_ref_device(dev);
678 /* Allocate a new device with a specific session ID. The returned device has
679 * a reference count of 1. */
680 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
681 unsigned long session_id)
683 size_t priv_size = usbi_backend->device_priv_size;
684 struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
690 r = usbi_mutex_init(&dev->lock);
698 dev->session_data = session_id;
699 dev->speed = LIBUSB_SPEED_UNKNOWN;
701 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
702 usbi_connect_device (dev);
708 void usbi_connect_device(struct libusb_device *dev)
710 struct libusb_context *ctx = DEVICE_CTX(dev);
714 usbi_mutex_lock(&dev->ctx->usb_devs_lock);
715 list_add(&dev->list, &dev->ctx->usb_devs);
716 usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
718 /* Signal that an event has occurred for this device if we support hotplug AND
719 * the hotplug message list is ready. This prevents an event from getting raised
720 * during initial enumeration. */
721 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
722 usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED);
726 void usbi_disconnect_device(struct libusb_device *dev)
728 struct libusb_context *ctx = DEVICE_CTX(dev);
730 usbi_mutex_lock(&dev->lock);
732 usbi_mutex_unlock(&dev->lock);
734 usbi_mutex_lock(&ctx->usb_devs_lock);
735 list_del(&dev->list);
736 usbi_mutex_unlock(&ctx->usb_devs_lock);
738 /* Signal that an event has occurred for this device if we support hotplug AND
739 * the hotplug message list is ready. This prevents an event from getting raised
740 * during initial enumeration. libusb_handle_events will take care of dereferencing
742 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
743 usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);
747 /* Perform some final sanity checks on a newly discovered device. If this
748 * function fails (negative return code), the device should not be added
749 * to the discovered device list. */
750 int usbi_sanitize_device(struct libusb_device *dev)
753 uint8_t num_configurations;
755 r = usbi_device_cache_descriptor(dev);
759 num_configurations = dev->device_descriptor.bNumConfigurations;
760 if (num_configurations > USB_MAXCONFIG) {
761 usbi_err(DEVICE_CTX(dev), "too many configurations");
762 return LIBUSB_ERROR_IO;
763 } else if (0 == num_configurations)
764 usbi_dbg("zero configurations, maybe an unauthorized device");
766 dev->num_configurations = num_configurations;
770 /* Examine libusb's internal list of known devices, looking for one with
771 * a specific session ID. Returns the matching device if it was found, and
773 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
774 unsigned long session_id)
776 struct libusb_device *dev;
777 struct libusb_device *ret = NULL;
779 usbi_mutex_lock(&ctx->usb_devs_lock);
780 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
781 if (dev->session_data == session_id) {
782 ret = libusb_ref_device(dev);
785 usbi_mutex_unlock(&ctx->usb_devs_lock);
790 /** @ingroup libusb_dev
791 * Returns a list of USB devices currently attached to the system. This is
792 * your entry point into finding a USB device to operate.
794 * You are expected to unreference all the devices when you are done with
795 * them, and then free the list with libusb_free_device_list(). Note that
796 * libusb_free_device_list() can unref all the devices for you. Be careful
797 * not to unreference a device you are about to open until after you have
800 * This return value of this function indicates the number of devices in
801 * the resultant list. The list is actually one element larger, as it is
804 * \param ctx the context to operate on, or NULL for the default context
805 * \param list output location for a list of devices. Must be later freed with
806 * libusb_free_device_list().
807 * \returns the number of devices in the outputted list, or any
808 * \ref libusb_error according to errors encountered by the backend.
810 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
811 libusb_device ***list)
813 struct discovered_devs *discdevs = discovered_devs_alloc();
814 struct libusb_device **ret;
817 USBI_GET_CONTEXT(ctx);
821 return LIBUSB_ERROR_NO_MEM;
823 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
824 /* backend provides hotplug support */
825 struct libusb_device *dev;
827 if (usbi_backend->hotplug_poll)
828 usbi_backend->hotplug_poll();
830 usbi_mutex_lock(&ctx->usb_devs_lock);
831 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
832 discdevs = discovered_devs_append(discdevs, dev);
835 r = LIBUSB_ERROR_NO_MEM;
839 usbi_mutex_unlock(&ctx->usb_devs_lock);
841 /* backend does not provide hotplug support */
842 r = usbi_backend->get_device_list(ctx, &discdevs);
850 /* convert discovered_devs into a list */
852 ret = calloc(len + 1, sizeof(struct libusb_device *));
854 len = LIBUSB_ERROR_NO_MEM;
859 for (i = 0; i < len; i++) {
860 struct libusb_device *dev = discdevs->devices[i];
861 ret[i] = libusb_ref_device(dev);
867 discovered_devs_free(discdevs);
871 /** \ingroup libusb_dev
872 * Frees a list of devices previously discovered using
873 * libusb_get_device_list(). If the unref_devices parameter is set, the
874 * reference count of each device in the list is decremented by 1.
875 * \param list the list to free
876 * \param unref_devices whether to unref the devices in the list
878 void API_EXPORTED libusb_free_device_list(libusb_device **list,
886 struct libusb_device *dev;
888 while ((dev = list[i++]) != NULL)
889 libusb_unref_device(dev);
894 /** \ingroup libusb_dev
895 * Get the number of the bus that a device is connected to.
896 * \param dev a device
897 * \returns the bus number
899 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
901 return dev->bus_number;
904 /** \ingroup libusb_dev
905 * Get the number of the port that a device is connected to.
906 * Unless the OS does something funky, or you are hot-plugging USB extension cards,
907 * the port number returned by this call is usually guaranteed to be uniquely tied
908 * to a physical port, meaning that different devices plugged on the same physical
909 * port should return the same port number.
911 * But outside of this, there is no guarantee that the port number returned by this
912 * call will remain the same, or even match the order in which ports have been
913 * numbered by the HUB/HCD manufacturer.
915 * \param dev a device
916 * \returns the port number (0 if not available)
918 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
920 return dev->port_number;
923 /** \ingroup libusb_dev
924 * Get the list of all port numbers from root for the specified device
926 * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
927 * \param dev a device
928 * \param port_numbers the array that should contain the port numbers
929 * \param port_numbers_len the maximum length of the array. As per the USB 3.0
930 * specs, the current maximum limit for the depth is 7.
931 * \returns the number of elements filled
932 * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
934 int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
935 uint8_t* port_numbers, int port_numbers_len)
937 int i = port_numbers_len;
938 struct libusb_context *ctx = DEVICE_CTX(dev);
940 if (port_numbers_len <= 0)
941 return LIBUSB_ERROR_INVALID_PARAM;
943 // HCDs can be listed as devices with port #0
944 while((dev) && (dev->port_number != 0)) {
946 usbi_warn(ctx, "port numbers array is too small");
947 return LIBUSB_ERROR_OVERFLOW;
949 port_numbers[i] = dev->port_number;
950 dev = dev->parent_dev;
952 if (i < port_numbers_len)
953 memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
954 return port_numbers_len - i;
957 /** \ingroup libusb_dev
958 * Deprecated please use libusb_get_port_numbers instead.
960 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
961 uint8_t* port_numbers, uint8_t port_numbers_len)
965 return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
968 /** \ingroup libusb_dev
969 * Get the the parent from the specified device.
970 * \param dev a device
971 * \returns the device parent or NULL if not available
972 * You should issue a \ref libusb_get_device_list() before calling this
973 * function and make sure that you only access the parent before issuing
974 * \ref libusb_free_device_list(). The reason is that libusb currently does
975 * not maintain a permanent list of device instances, and therefore can
976 * only guarantee that parents are fully instantiated within a
977 * libusb_get_device_list() - libusb_free_device_list() block.
980 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
982 return dev->parent_dev;
985 /** \ingroup libusb_dev
986 * Get the address of the device on the bus it is connected to.
987 * \param dev a device
988 * \returns the device address
990 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
992 return dev->device_address;
995 /** \ingroup libusb_dev
996 * Get the negotiated connection speed for a device.
997 * \param dev a device
998 * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
999 * the OS doesn't know or doesn't support returning the negotiated speed.
1001 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
1006 static const struct libusb_endpoint_descriptor *find_endpoint(
1007 struct libusb_config_descriptor *config, unsigned char endpoint)
1010 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
1011 const struct libusb_interface *iface = &config->interface[iface_idx];
1014 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
1016 const struct libusb_interface_descriptor *altsetting
1017 = &iface->altsetting[altsetting_idx];
1020 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
1021 const struct libusb_endpoint_descriptor *ep =
1022 &altsetting->endpoint[ep_idx];
1023 if (ep->bEndpointAddress == endpoint)
1031 /** \ingroup libusb_dev
1032 * Convenience function to retrieve the wMaxPacketSize value for a particular
1033 * endpoint in the active device configuration.
1035 * This function was originally intended to be of assistance when setting up
1036 * isochronous transfers, but a design mistake resulted in this function
1037 * instead. It simply returns the wMaxPacketSize value without considering
1038 * its contents. If you're dealing with isochronous transfers, you probably
1039 * want libusb_get_max_iso_packet_size() instead.
1041 * \param dev a device
1042 * \param endpoint address of the endpoint in question
1043 * \returns the wMaxPacketSize value
1044 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1045 * \returns LIBUSB_ERROR_OTHER on other failure
1047 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
1048 unsigned char endpoint)
1050 struct libusb_config_descriptor *config;
1051 const struct libusb_endpoint_descriptor *ep;
1054 r = libusb_get_active_config_descriptor(dev, &config);
1056 usbi_err(DEVICE_CTX(dev),
1057 "could not retrieve active config descriptor");
1058 return LIBUSB_ERROR_OTHER;
1061 ep = find_endpoint(config, endpoint);
1063 r = LIBUSB_ERROR_NOT_FOUND;
1067 r = ep->wMaxPacketSize;
1070 libusb_free_config_descriptor(config);
1074 /** \ingroup libusb_dev
1075 * Calculate the maximum packet size which a specific endpoint is capable is
1076 * sending or receiving in the duration of 1 microframe
1078 * Only the active configuration is examined. The calculation is based on the
1079 * wMaxPacketSize field in the endpoint descriptor as described in section
1080 * 9.6.6 in the USB 2.0 specifications.
1082 * If acting on an isochronous or interrupt endpoint, this function will
1083 * multiply the value found in bits 0:10 by the number of transactions per
1084 * microframe (determined by bits 11:12). Otherwise, this function just
1085 * returns the numeric value found in bits 0:10.
1087 * This function is useful for setting up isochronous transfers, for example
1088 * you might pass the return value from this function to
1089 * libusb_set_iso_packet_lengths() in order to set the length field of every
1090 * isochronous packet in a transfer.
1094 * \param dev a device
1095 * \param endpoint address of the endpoint in question
1096 * \returns the maximum packet size which can be sent/received on this endpoint
1097 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1098 * \returns LIBUSB_ERROR_OTHER on other failure
1100 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
1101 unsigned char endpoint)
1103 struct libusb_config_descriptor *config;
1104 const struct libusb_endpoint_descriptor *ep;
1105 enum libusb_transfer_type ep_type;
1109 r = libusb_get_active_config_descriptor(dev, &config);
1111 usbi_err(DEVICE_CTX(dev),
1112 "could not retrieve active config descriptor");
1113 return LIBUSB_ERROR_OTHER;
1116 ep = find_endpoint(config, endpoint);
1118 r = LIBUSB_ERROR_NOT_FOUND;
1122 val = ep->wMaxPacketSize;
1123 ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
1126 if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
1127 || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1128 r *= (1 + ((val >> 11) & 3));
1131 libusb_free_config_descriptor(config);
1135 /** \ingroup libusb_dev
1136 * Increment the reference count of a device.
1137 * \param dev the device to reference
1138 * \returns the same device
1141 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
1143 usbi_mutex_lock(&dev->lock);
1145 usbi_mutex_unlock(&dev->lock);
1149 /** \ingroup libusb_dev
1150 * Decrement the reference count of a device. If the decrement operation
1151 * causes the reference count to reach zero, the device shall be destroyed.
1152 * \param dev the device to unreference
1154 void API_EXPORTED libusb_unref_device(libusb_device *dev)
1161 usbi_mutex_lock(&dev->lock);
1162 refcnt = --dev->refcnt;
1163 usbi_mutex_unlock(&dev->lock);
1166 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
1168 libusb_unref_device(dev->parent_dev);
1170 if (usbi_backend->destroy_device)
1171 usbi_backend->destroy_device(dev);
1173 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1174 /* backend does not support hotplug */
1175 usbi_disconnect_device(dev);
1178 usbi_mutex_destroy(&dev->lock);
1184 * Signal the event pipe so that the event handling thread will be
1185 * interrupted to process an internal event.
1187 int usbi_signal_event(struct libusb_context *ctx)
1189 unsigned char dummy = 1;
1192 /* write some data on event pipe to interrupt event handlers */
1193 r = usbi_write(ctx->event_pipe[1], &dummy, sizeof(dummy));
1194 if (r != sizeof(dummy)) {
1195 usbi_warn(ctx, "internal signalling write failed");
1196 return LIBUSB_ERROR_IO;
1203 * Clear the event pipe so that the event handling will no longer be
1206 int usbi_clear_event(struct libusb_context *ctx)
1208 unsigned char dummy;
1211 /* read some data on event pipe to clear it */
1212 r = usbi_read(ctx->event_pipe[0], &dummy, sizeof(dummy));
1213 if (r != sizeof(dummy)) {
1214 usbi_warn(ctx, "internal signalling read failed");
1215 return LIBUSB_ERROR_IO;
1221 /** \ingroup libusb_dev
1222 * Open a device and obtain a device handle. A handle allows you to perform
1223 * I/O on the device in question.
1225 * Internally, this function adds a reference to the device and makes it
1226 * available to you through libusb_get_device(). This reference is removed
1227 * during libusb_close().
1229 * This is a non-blocking function; no requests are sent over the bus.
1231 * \param dev the device to open
1232 * \param dev_handle output location for the returned device handle pointer. Only
1233 * populated when the return code is 0.
1234 * \returns 0 on success
1235 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
1236 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
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_open(libusb_device *dev,
1241 libusb_device_handle **dev_handle)
1243 struct libusb_context *ctx = DEVICE_CTX(dev);
1244 struct libusb_device_handle *_dev_handle;
1245 size_t priv_size = usbi_backend->device_handle_priv_size;
1247 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
1249 if (!dev->attached) {
1250 return LIBUSB_ERROR_NO_DEVICE;
1253 _dev_handle = malloc(sizeof(*_dev_handle) + priv_size);
1255 return LIBUSB_ERROR_NO_MEM;
1257 r = usbi_mutex_init(&_dev_handle->lock);
1260 return LIBUSB_ERROR_OTHER;
1263 _dev_handle->dev = libusb_ref_device(dev);
1264 _dev_handle->auto_detach_kernel_driver = 0;
1265 _dev_handle->claimed_interfaces = 0;
1266 memset(&_dev_handle->os_priv, 0, priv_size);
1268 r = usbi_backend->open(_dev_handle);
1270 usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
1271 libusb_unref_device(dev);
1272 usbi_mutex_destroy(&_dev_handle->lock);
1277 usbi_mutex_lock(&ctx->open_devs_lock);
1278 list_add(&_dev_handle->list, &ctx->open_devs);
1279 usbi_mutex_unlock(&ctx->open_devs_lock);
1280 *dev_handle = _dev_handle;
1285 /** \ingroup libusb_dev
1286 * Convenience function for finding a device with a particular
1287 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1288 * for those scenarios where you are using libusb to knock up a quick test
1289 * application - it allows you to avoid calling libusb_get_device_list() and
1290 * worrying about traversing/freeing the list.
1292 * This function has limitations and is hence not intended for use in real
1293 * applications: if multiple devices have the same IDs it will only
1294 * give you the first one, etc.
1296 * \param ctx the context to operate on, or NULL for the default context
1297 * \param vendor_id the idVendor value to search for
1298 * \param product_id the idProduct value to search for
1299 * \returns a device handle for the first found device, or NULL on error
1300 * or if the device could not be found. */
1302 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1303 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1305 struct libusb_device **devs;
1306 struct libusb_device *found = NULL;
1307 struct libusb_device *dev;
1308 struct libusb_device_handle *dev_handle = NULL;
1312 if (libusb_get_device_list(ctx, &devs) < 0)
1315 while ((dev = devs[i++]) != NULL) {
1316 struct libusb_device_descriptor desc;
1317 r = libusb_get_device_descriptor(dev, &desc);
1320 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1327 r = libusb_open(found, &dev_handle);
1333 libusb_free_device_list(devs, 1);
1337 static void do_close(struct libusb_context *ctx,
1338 struct libusb_device_handle *dev_handle)
1340 struct usbi_transfer *itransfer;
1341 struct usbi_transfer *tmp;
1343 /* remove any transfers in flight that are for this device */
1344 usbi_mutex_lock(&ctx->flying_transfers_lock);
1346 /* safe iteration because transfers may be being deleted */
1347 list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
1348 struct libusb_transfer *transfer =
1349 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1351 if (transfer->dev_handle != dev_handle)
1354 usbi_mutex_lock(&itransfer->lock);
1355 if (!(itransfer->state_flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1356 usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1358 if (itransfer->state_flags & USBI_TRANSFER_CANCELLING)
1359 usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1361 usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1363 usbi_mutex_unlock(&itransfer->lock);
1365 /* remove from the list of in-flight transfers and make sure
1366 * we don't accidentally use the device handle in the future
1367 * (or that such accesses will be easily caught and identified as a crash)
1369 list_del(&itransfer->list);
1370 transfer->dev_handle = NULL;
1372 /* it is up to the user to free up the actual transfer struct. this is
1373 * just making sure that we don't attempt to process the transfer after
1374 * the device handle is invalid
1376 usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
1377 transfer, dev_handle);
1379 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1381 usbi_mutex_lock(&ctx->open_devs_lock);
1382 list_del(&dev_handle->list);
1383 usbi_mutex_unlock(&ctx->open_devs_lock);
1385 usbi_backend->close(dev_handle);
1386 libusb_unref_device(dev_handle->dev);
1387 usbi_mutex_destroy(&dev_handle->lock);
1391 /** \ingroup libusb_dev
1392 * Close a device handle. Should be called on all open handles before your
1393 * application exits.
1395 * Internally, this function destroys the reference that was added by
1396 * libusb_open() on the given device.
1398 * This is a non-blocking function; no requests are sent over the bus.
1400 * \param dev_handle the device handle to close
1402 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1404 struct libusb_context *ctx;
1405 int handling_events;
1412 ctx = HANDLE_CTX(dev_handle);
1413 handling_events = usbi_handling_events(ctx);
1415 /* Similarly to libusb_open(), we want to interrupt all event handlers
1416 * at this point. More importantly, we want to perform the actual close of
1417 * the device while holding the event handling lock (preventing any other
1418 * thread from doing event handling) because we will be removing a file
1419 * descriptor from the polling loop. If this is being called by the current
1420 * event handler, we can bypass the interruption code because we already
1421 * hold the event handling lock. */
1423 if (!handling_events) {
1424 /* Record that we are closing a device.
1425 * Only signal an event if there are no prior pending events. */
1426 usbi_mutex_lock(&ctx->event_data_lock);
1427 pending_events = usbi_pending_events(ctx);
1428 ctx->device_close++;
1429 if (!pending_events)
1430 usbi_signal_event(ctx);
1431 usbi_mutex_unlock(&ctx->event_data_lock);
1433 /* take event handling lock */
1434 libusb_lock_events(ctx);
1437 /* Close the device */
1438 do_close(ctx, dev_handle);
1440 if (!handling_events) {
1441 /* We're done with closing this device.
1442 * Clear the event pipe if there are no further pending events. */
1443 usbi_mutex_lock(&ctx->event_data_lock);
1444 ctx->device_close--;
1445 pending_events = usbi_pending_events(ctx);
1446 if (!pending_events)
1447 usbi_clear_event(ctx);
1448 usbi_mutex_unlock(&ctx->event_data_lock);
1450 /* Release event handling lock and wake up event waiters */
1451 libusb_unlock_events(ctx);
1455 /** \ingroup libusb_dev
1456 * Get the underlying device for a device handle. This function does not modify
1457 * the reference count of the returned device, so do not feel compelled to
1458 * unreference it when you are done.
1459 * \param dev_handle a device handle
1460 * \returns the underlying device
1463 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1465 return dev_handle->dev;
1468 /** \ingroup libusb_dev
1469 * Determine the bConfigurationValue of the currently active configuration.
1471 * You could formulate your own control request to obtain this information,
1472 * but this function has the advantage that it may be able to retrieve the
1473 * information from operating system caches (no I/O involved).
1475 * If the OS does not cache this information, then this function will block
1476 * while a control transfer is submitted to retrieve the information.
1478 * This function will return a value of 0 in the <tt>config</tt> output
1479 * parameter if the device is in unconfigured state.
1481 * \param dev_handle a device handle
1482 * \param config output location for the bConfigurationValue of the active
1483 * configuration (only valid for return code 0)
1484 * \returns 0 on success
1485 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1486 * \returns another LIBUSB_ERROR code on other failure
1488 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev_handle,
1491 int r = LIBUSB_ERROR_NOT_SUPPORTED;
1494 if (usbi_backend->get_configuration)
1495 r = usbi_backend->get_configuration(dev_handle, config);
1497 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1499 usbi_dbg("falling back to control message");
1500 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
1501 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1503 usbi_err(HANDLE_CTX(dev_handle), "zero bytes returned in ctrl transfer?");
1504 r = LIBUSB_ERROR_IO;
1505 } else if (r == 1) {
1509 usbi_dbg("control failed, error %d", r);
1514 usbi_dbg("active config %d", *config);
1519 /** \ingroup libusb_dev
1520 * Set the active configuration for a device.
1522 * The operating system may or may not have already set an active
1523 * configuration on the device. It is up to your application to ensure the
1524 * correct configuration is selected before you attempt to claim interfaces
1525 * and perform other operations.
1527 * If you call this function on a device already configured with the selected
1528 * configuration, then this function will act as a lightweight device reset:
1529 * it will issue a SET_CONFIGURATION request using the current configuration,
1530 * causing most USB-related device state to be reset (altsetting reset to zero,
1531 * endpoint halts cleared, toggles reset).
1533 * You cannot change/reset configuration if your application has claimed
1534 * interfaces. It is advised to set the desired configuration before claiming
1537 * Alternatively you can call libusb_release_interface() first. Note if you
1538 * do things this way you must ensure that auto_detach_kernel_driver for
1539 * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
1540 * release the interface(s).
1542 * You cannot change/reset configuration if other applications or drivers have
1543 * claimed interfaces.
1545 * A configuration value of -1 will put the device in unconfigured state.
1546 * The USB specifications state that a configuration value of 0 does this,
1547 * however buggy devices exist which actually have a configuration 0.
1549 * You should always use this function rather than formulating your own
1550 * SET_CONFIGURATION control request. This is because the underlying operating
1551 * system needs to know when such changes happen.
1553 * This is a blocking function.
1555 * \param dev_handle a device handle
1556 * \param configuration the bConfigurationValue of the configuration you
1557 * wish to activate, or -1 if you wish to put the device in an unconfigured
1559 * \returns 0 on success
1560 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1561 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1562 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1563 * \returns another LIBUSB_ERROR code on other failure
1564 * \see libusb_set_auto_detach_kernel_driver()
1566 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev_handle,
1569 usbi_dbg("configuration %d", configuration);
1570 return usbi_backend->set_configuration(dev_handle, configuration);
1573 /** \ingroup libusb_dev
1574 * Claim an interface on a given device handle. You must claim the interface
1575 * you wish to use before you can perform I/O on any of its endpoints.
1577 * It is legal to attempt to claim an already-claimed interface, in which
1578 * case libusb just returns 0 without doing anything.
1580 * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
1581 * will be detached if necessary, on failure the detach error is returned.
1583 * Claiming of interfaces is a purely logical operation; it does not cause
1584 * any requests to be sent over the bus. Interface claiming is used to
1585 * instruct the underlying operating system that your application wishes
1586 * to take ownership of the interface.
1588 * This is a non-blocking function.
1590 * \param dev_handle a device handle
1591 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1593 * \returns 0 on success
1594 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1595 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1597 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1598 * \returns a LIBUSB_ERROR code on other failure
1599 * \see libusb_set_auto_detach_kernel_driver()
1601 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev_handle,
1602 int interface_number)
1606 usbi_dbg("interface %d", interface_number);
1607 if (interface_number >= USB_MAXINTERFACES)
1608 return LIBUSB_ERROR_INVALID_PARAM;
1610 if (!dev_handle->dev->attached)
1611 return LIBUSB_ERROR_NO_DEVICE;
1613 usbi_mutex_lock(&dev_handle->lock);
1614 if (dev_handle->claimed_interfaces & (1 << interface_number))
1617 r = usbi_backend->claim_interface(dev_handle, interface_number);
1619 dev_handle->claimed_interfaces |= 1 << interface_number;
1622 usbi_mutex_unlock(&dev_handle->lock);
1626 /** \ingroup libusb_dev
1627 * Release an interface previously claimed with libusb_claim_interface(). You
1628 * should release all claimed interfaces before closing a device handle.
1630 * This is a blocking function. A SET_INTERFACE control request will be sent
1631 * to the device, resetting interface state to the first alternate setting.
1633 * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
1634 * driver will be re-attached after releasing the interface.
1636 * \param dev_handle a device handle
1637 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1638 * previously-claimed interface
1639 * \returns 0 on success
1640 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1641 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1642 * \returns another LIBUSB_ERROR code on other failure
1643 * \see libusb_set_auto_detach_kernel_driver()
1645 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev_handle,
1646 int interface_number)
1650 usbi_dbg("interface %d", interface_number);
1651 if (interface_number >= USB_MAXINTERFACES)
1652 return LIBUSB_ERROR_INVALID_PARAM;
1654 usbi_mutex_lock(&dev_handle->lock);
1655 if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
1656 r = LIBUSB_ERROR_NOT_FOUND;
1660 r = usbi_backend->release_interface(dev_handle, interface_number);
1662 dev_handle->claimed_interfaces &= ~(1 << interface_number);
1665 usbi_mutex_unlock(&dev_handle->lock);
1669 /** \ingroup libusb_dev
1670 * Activate an alternate setting for an interface. The interface must have
1671 * been previously claimed with libusb_claim_interface().
1673 * You should always use this function rather than formulating your own
1674 * SET_INTERFACE control request. This is because the underlying operating
1675 * system needs to know when such changes happen.
1677 * This is a blocking function.
1679 * \param dev_handle a device handle
1680 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1681 * previously-claimed interface
1682 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1683 * setting to activate
1684 * \returns 0 on success
1685 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1686 * requested alternate setting does not exist
1687 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1688 * \returns another LIBUSB_ERROR code on other failure
1690 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
1691 int interface_number, int alternate_setting)
1693 usbi_dbg("interface %d altsetting %d",
1694 interface_number, alternate_setting);
1695 if (interface_number >= USB_MAXINTERFACES)
1696 return LIBUSB_ERROR_INVALID_PARAM;
1698 usbi_mutex_lock(&dev_handle->lock);
1699 if (!dev_handle->dev->attached) {
1700 usbi_mutex_unlock(&dev_handle->lock);
1701 return LIBUSB_ERROR_NO_DEVICE;
1704 if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
1705 usbi_mutex_unlock(&dev_handle->lock);
1706 return LIBUSB_ERROR_NOT_FOUND;
1708 usbi_mutex_unlock(&dev_handle->lock);
1710 return usbi_backend->set_interface_altsetting(dev_handle, interface_number,
1714 /** \ingroup libusb_dev
1715 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1716 * are unable to receive or transmit data until the halt condition is stalled.
1718 * You should cancel all pending transfers before attempting to clear the halt
1721 * This is a blocking function.
1723 * \param dev_handle a device handle
1724 * \param endpoint the endpoint to clear halt status
1725 * \returns 0 on success
1726 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1727 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1728 * \returns another LIBUSB_ERROR code on other failure
1730 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev_handle,
1731 unsigned char endpoint)
1733 usbi_dbg("endpoint %x", endpoint);
1734 if (!dev_handle->dev->attached)
1735 return LIBUSB_ERROR_NO_DEVICE;
1737 return usbi_backend->clear_halt(dev_handle, endpoint);
1740 /** \ingroup libusb_dev
1741 * Perform a USB port reset to reinitialize a device. The system will attempt
1742 * to restore the previous configuration and alternate settings after the
1743 * reset has completed.
1745 * If the reset fails, the descriptors change, or the previous state cannot be
1746 * restored, the device will appear to be disconnected and reconnected. This
1747 * means that the device handle is no longer valid (you should close it) and
1748 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1749 * when this is the case.
1751 * This is a blocking function which usually incurs a noticeable delay.
1753 * \param dev_handle a handle of the device to reset
1754 * \returns 0 on success
1755 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1756 * device has been disconnected
1757 * \returns another LIBUSB_ERROR code on other failure
1759 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev_handle)
1762 if (!dev_handle->dev->attached)
1763 return LIBUSB_ERROR_NO_DEVICE;
1765 return usbi_backend->reset_device(dev_handle);
1768 /** \ingroup libusb_asyncio
1769 * Allocate up to num_streams usb bulk streams on the specified endpoints. This
1770 * function takes an array of endpoints rather then a single endpoint because
1771 * some protocols require that endpoints are setup with similar stream ids.
1772 * All endpoints passed in must belong to the same interface.
1774 * Note this function may return less streams then requested. Also note that the
1775 * same number of streams are allocated for each endpoint in the endpoint array.
1777 * Stream id 0 is reserved, and should not be used to communicate with devices.
1778 * If libusb_alloc_streams() returns with a value of N, you may use stream ids
1781 * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1783 * \param dev_handle a device handle
1784 * \param num_streams number of streams to try to allocate
1785 * \param endpoints array of endpoints to allocate streams on
1786 * \param num_endpoints length of the endpoints array
1787 * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
1789 int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev_handle,
1790 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1792 usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints);
1794 if (!dev_handle->dev->attached)
1795 return LIBUSB_ERROR_NO_DEVICE;
1797 if (usbi_backend->alloc_streams)
1798 return usbi_backend->alloc_streams(dev_handle, num_streams, endpoints,
1801 return LIBUSB_ERROR_NOT_SUPPORTED;
1804 /** \ingroup libusb_asyncio
1805 * Free usb bulk streams allocated with libusb_alloc_streams().
1807 * Note streams are automatically free-ed when releasing an interface.
1809 * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1811 * \param dev_handle a device handle
1812 * \param endpoints array of endpoints to free streams on
1813 * \param num_endpoints length of the endpoints array
1814 * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1816 int API_EXPORTED libusb_free_streams(libusb_device_handle *dev_handle,
1817 unsigned char *endpoints, int num_endpoints)
1819 usbi_dbg("eps %d", num_endpoints);
1821 if (!dev_handle->dev->attached)
1822 return LIBUSB_ERROR_NO_DEVICE;
1824 if (usbi_backend->free_streams)
1825 return usbi_backend->free_streams(dev_handle, endpoints,
1828 return LIBUSB_ERROR_NOT_SUPPORTED;
1831 /** \ingroup libusb_asyncio
1832 * Attempts to allocate a block of persistent DMA memory suitable for transfers
1833 * against the given device. If successful, will return a block of memory
1834 * that is suitable for use as "buffer" in \ref libusb_transfer against this
1835 * device. Using this memory instead of regular memory means that the host
1836 * controller can use DMA directly into the buffer to increase performance, and
1837 * also that transfers can no longer fail due to kernel memory fragmentation.
1839 * Note that this means you should not modify this memory (or even data on
1840 * the same cache lines) when a transfer is in progress, although it is legal
1841 * to have several transfers going on within the same memory block.
1843 * Will return NULL on failure. Many systems do not support such zerocopy
1844 * and will always return NULL. Memory allocated with this function must be
1845 * freed with \ref libusb_dev_mem_free. Specifically, this means that the
1846 * flag \ref LIBUSB_TRANSFER_FREE_BUFFER cannot be used to free memory allocated
1847 * with this function.
1849 * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
1851 * \param dev_handle a device handle
1852 * \param length size of desired data buffer
1853 * \returns a pointer to the newly allocated memory, or NULL on failure
1856 unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle,
1859 if (!dev_handle->dev->attached)
1862 if (usbi_backend->dev_mem_alloc)
1863 return usbi_backend->dev_mem_alloc(dev_handle, length);
1868 /** \ingroup libusb_asyncio
1869 * Free device memory allocated with libusb_dev_mem_alloc().
1871 * \param dev_handle a device handle
1872 * \param buffer pointer to the previously allocated memory
1873 * \param length size of previously allocated memory
1874 * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1876 int API_EXPORTED libusb_dev_mem_free(libusb_device_handle *dev_handle,
1877 unsigned char *buffer, size_t length)
1879 if (usbi_backend->dev_mem_free)
1880 return usbi_backend->dev_mem_free(dev_handle, buffer, length);
1882 return LIBUSB_ERROR_NOT_SUPPORTED;
1885 /** \ingroup libusb_dev
1886 * Determine if a kernel driver is active on an interface. If a kernel driver
1887 * is active, you cannot claim the interface, and libusb will be unable to
1890 * This functionality is not available on Windows.
1892 * \param dev_handle a device handle
1893 * \param interface_number the interface to check
1894 * \returns 0 if no kernel driver is active
1895 * \returns 1 if a kernel driver is active
1896 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1897 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1899 * \returns another LIBUSB_ERROR code on other failure
1900 * \see libusb_detach_kernel_driver()
1902 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev_handle,
1903 int interface_number)
1905 usbi_dbg("interface %d", interface_number);
1907 if (!dev_handle->dev->attached)
1908 return LIBUSB_ERROR_NO_DEVICE;
1910 if (usbi_backend->kernel_driver_active)
1911 return usbi_backend->kernel_driver_active(dev_handle, interface_number);
1913 return LIBUSB_ERROR_NOT_SUPPORTED;
1916 /** \ingroup libusb_dev
1917 * Detach a kernel driver from an interface. If successful, you will then be
1918 * able to claim the interface and perform I/O.
1920 * This functionality is not available on Darwin or Windows.
1922 * Note that libusb itself also talks to the device through a special kernel
1923 * driver, if this driver is already attached to the device, this call will
1924 * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1926 * \param dev_handle a device handle
1927 * \param interface_number the interface to detach the driver from
1928 * \returns 0 on success
1929 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1930 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1931 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1932 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1934 * \returns another LIBUSB_ERROR code on other failure
1935 * \see libusb_kernel_driver_active()
1937 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
1938 int interface_number)
1940 usbi_dbg("interface %d", interface_number);
1942 if (!dev_handle->dev->attached)
1943 return LIBUSB_ERROR_NO_DEVICE;
1945 if (usbi_backend->detach_kernel_driver)
1946 return usbi_backend->detach_kernel_driver(dev_handle, interface_number);
1948 return LIBUSB_ERROR_NOT_SUPPORTED;
1951 /** \ingroup libusb_dev
1952 * Re-attach an interface's kernel driver, which was previously detached
1953 * using libusb_detach_kernel_driver(). This call is only effective on
1954 * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1956 * This functionality is not available on Darwin or Windows.
1958 * \param dev_handle a device handle
1959 * \param interface_number the interface to attach the driver from
1960 * \returns 0 on success
1961 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1962 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1963 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1964 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1966 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1967 * interface is claimed by a program or driver
1968 * \returns another LIBUSB_ERROR code on other failure
1969 * \see libusb_kernel_driver_active()
1971 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
1972 int interface_number)
1974 usbi_dbg("interface %d", interface_number);
1976 if (!dev_handle->dev->attached)
1977 return LIBUSB_ERROR_NO_DEVICE;
1979 if (usbi_backend->attach_kernel_driver)
1980 return usbi_backend->attach_kernel_driver(dev_handle, interface_number);
1982 return LIBUSB_ERROR_NOT_SUPPORTED;
1985 /** \ingroup libusb_dev
1986 * Enable/disable libusb's automatic kernel driver detachment. When this is
1987 * enabled libusb will automatically detach the kernel driver on an interface
1988 * when claiming the interface, and attach it when releasing the interface.
1990 * Automatic kernel driver detachment is disabled on newly opened device
1991 * handles by default.
1993 * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
1994 * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
1995 * continue as if this function was never called.
1997 * \param dev_handle a device handle
1998 * \param enable whether to enable or disable auto kernel driver detachment
2000 * \returns LIBUSB_SUCCESS on success
2001 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
2003 * \see libusb_claim_interface()
2004 * \see libusb_release_interface()
2005 * \see libusb_set_configuration()
2007 int API_EXPORTED libusb_set_auto_detach_kernel_driver(
2008 libusb_device_handle *dev_handle, int enable)
2010 if (!(usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
2011 return LIBUSB_ERROR_NOT_SUPPORTED;
2013 dev_handle->auto_detach_kernel_driver = enable;
2014 return LIBUSB_SUCCESS;
2017 /** \ingroup libusb_lib
2018 * Set log message verbosity.
2020 * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
2021 * printed. If you choose to increase the message verbosity level, ensure
2022 * that your application does not close the stdout/stderr file descriptors.
2024 * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusb is conservative
2025 * with its message logging and most of the time, will only log messages that
2026 * explain error conditions and other oddities. This will help you debug
2029 * If the LIBUSB_DEBUG environment variable was set when libusb was
2030 * initialized, this function does nothing: the message verbosity is fixed
2031 * to the value in the environment variable.
2033 * If libusb was compiled without any message logging, this function does
2034 * nothing: you'll never get any messages.
2036 * If libusb was compiled with verbose debug message logging, this function
2037 * does nothing: you'll always get messages from all levels.
2039 * \param ctx the context to operate on, or NULL for the default context
2040 * \param level debug level to set
2042 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
2044 USBI_GET_CONTEXT(ctx);
2045 if (!ctx->debug_fixed)
2049 /** \ingroup libusb_lib
2050 * Initialize libusb. This function must be called before calling any other
2053 * If you do not provide an output location for a context pointer, a default
2054 * context will be created. If there was already a default context, it will
2055 * be reused (and nothing will be initialized/reinitialized).
2057 * \param context Optional output location for context pointer.
2058 * Only valid on return code 0.
2059 * \returns 0 on success, or a LIBUSB_ERROR code on failure
2060 * \see libusb_contexts
2062 int API_EXPORTED libusb_init(libusb_context **context)
2064 struct libusb_device *dev, *next;
2065 char *dbg = getenv("LIBUSB_DEBUG");
2066 struct libusb_context *ctx;
2067 static int first_init = 1;
2070 usbi_mutex_static_lock(&default_context_lock);
2072 if (!timestamp_origin.tv_sec) {
2073 usbi_backend->clock_gettime(USBI_CLOCK_REALTIME, ×tamp_origin);
2076 if (!context && usbi_default_context) {
2077 usbi_dbg("reusing default context");
2078 default_context_refcnt++;
2079 usbi_mutex_static_unlock(&default_context_lock);
2083 ctx = calloc(1, sizeof(*ctx));
2085 r = LIBUSB_ERROR_NO_MEM;
2089 #ifdef ENABLE_DEBUG_LOGGING
2090 ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
2094 ctx->debug = atoi(dbg);
2096 ctx->debug_fixed = 1;
2099 /* default context should be initialized before calling usbi_dbg */
2100 if (!usbi_default_context) {
2101 usbi_default_context = ctx;
2102 default_context_refcnt++;
2103 usbi_dbg("created default context");
2106 usbi_dbg("libusb v%u.%u.%u.%u%s", libusb_version_internal.major, libusb_version_internal.minor,
2107 libusb_version_internal.micro, libusb_version_internal.nano, libusb_version_internal.rc);
2109 usbi_mutex_init(&ctx->usb_devs_lock);
2110 usbi_mutex_init(&ctx->open_devs_lock);
2111 usbi_mutex_init(&ctx->hotplug_cbs_lock);
2112 list_init(&ctx->usb_devs);
2113 list_init(&ctx->open_devs);
2114 list_init(&ctx->hotplug_cbs);
2116 usbi_mutex_static_lock(&active_contexts_lock);
2119 list_init (&active_contexts_list);
2121 list_add (&ctx->list, &active_contexts_list);
2122 usbi_mutex_static_unlock(&active_contexts_lock);
2124 if (usbi_backend->init) {
2125 r = usbi_backend->init(ctx);
2130 r = usbi_io_init(ctx);
2132 goto err_backend_exit;
2134 usbi_mutex_static_unlock(&default_context_lock);
2142 if (usbi_backend->exit)
2143 usbi_backend->exit();
2145 if (ctx == usbi_default_context) {
2146 usbi_default_context = NULL;
2147 default_context_refcnt--;
2150 usbi_mutex_static_lock(&active_contexts_lock);
2151 list_del (&ctx->list);
2152 usbi_mutex_static_unlock(&active_contexts_lock);
2154 usbi_mutex_lock(&ctx->usb_devs_lock);
2155 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
2156 list_del(&dev->list);
2157 libusb_unref_device(dev);
2159 usbi_mutex_unlock(&ctx->usb_devs_lock);
2161 usbi_mutex_destroy(&ctx->open_devs_lock);
2162 usbi_mutex_destroy(&ctx->usb_devs_lock);
2163 usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2167 usbi_mutex_static_unlock(&default_context_lock);
2171 /** \ingroup libusb_lib
2172 * Deinitialize libusb. Should be called after closing all open devices and
2173 * before your application terminates.
2174 * \param ctx the context to deinitialize, or NULL for the default context
2176 void API_EXPORTED libusb_exit(struct libusb_context *ctx)
2178 struct libusb_device *dev, *next;
2179 struct timeval tv = { 0, 0 };
2182 USBI_GET_CONTEXT(ctx);
2184 /* if working with default context, only actually do the deinitialization
2185 * if we're the last user */
2186 usbi_mutex_static_lock(&default_context_lock);
2187 if (ctx == usbi_default_context) {
2188 if (--default_context_refcnt > 0) {
2189 usbi_dbg("not destroying default context");
2190 usbi_mutex_static_unlock(&default_context_lock);
2193 usbi_dbg("destroying default context");
2194 usbi_default_context = NULL;
2196 usbi_mutex_static_unlock(&default_context_lock);
2198 usbi_mutex_static_lock(&active_contexts_lock);
2199 list_del (&ctx->list);
2200 usbi_mutex_static_unlock(&active_contexts_lock);
2202 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
2203 usbi_hotplug_deregister_all(ctx);
2206 * Ensure any pending unplug events are read from the hotplug
2207 * pipe. The usb_device-s hold in the events are no longer part
2208 * of usb_devs, but the events still hold a reference!
2210 * Note we don't do this if the application has left devices
2211 * open (which implies a buggy app) to avoid packet completion
2212 * handlers running when the app does not expect them to run.
2214 if (list_empty(&ctx->open_devs))
2215 libusb_handle_events_timeout(ctx, &tv);
2217 usbi_mutex_lock(&ctx->usb_devs_lock);
2218 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
2219 list_del(&dev->list);
2220 libusb_unref_device(dev);
2222 usbi_mutex_unlock(&ctx->usb_devs_lock);
2225 /* a few sanity checks. don't bother with locking because unless
2226 * there is an application bug, nobody will be accessing these. */
2227 if (!list_empty(&ctx->usb_devs))
2228 usbi_warn(ctx, "some libusb_devices were leaked");
2229 if (!list_empty(&ctx->open_devs))
2230 usbi_warn(ctx, "application left some devices open");
2233 if (usbi_backend->exit)
2234 usbi_backend->exit();
2236 usbi_mutex_destroy(&ctx->open_devs_lock);
2237 usbi_mutex_destroy(&ctx->usb_devs_lock);
2238 usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2242 /** \ingroup libusb_misc
2243 * Check at runtime if the loaded library has a given capability.
2244 * This call should be performed after \ref libusb_init(), to ensure the
2245 * backend has updated its capability set.
2247 * \param capability the \ref libusb_capability to check for
2248 * \returns nonzero if the running library has the capability, 0 otherwise
2250 int API_EXPORTED libusb_has_capability(uint32_t capability)
2252 switch (capability) {
2253 case LIBUSB_CAP_HAS_CAPABILITY:
2255 case LIBUSB_CAP_HAS_HOTPLUG:
2256 return !(usbi_backend->get_device_list);
2257 case LIBUSB_CAP_HAS_HID_ACCESS:
2258 return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS);
2259 case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
2260 return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
2265 /* this is defined in libusbi.h if needed */
2266 #ifdef LIBUSB_PRINTF_WIN32
2268 * Prior to VS2015, Microsoft did not provide the snprintf() function and
2269 * provided a vsnprintf() that did not guarantee NULL-terminated output.
2270 * Microsoft did provide a _snprintf() function, but again it did not
2271 * guarantee NULL-terminated output.
2273 * The below implementations guarantee NULL-terminated output and are
2277 int usbi_snprintf(char *str, size_t size, const char *format, ...)
2282 va_start(ap, format);
2283 ret = usbi_vsnprintf(str, size, format, ap);
2289 int usbi_vsnprintf(char *str, size_t size, const char *format, va_list ap)
2293 ret = _vsnprintf(str, size, format, ap);
2294 if (ret < 0 || ret == (int)size) {
2295 /* Output is truncated, ensure buffer is NULL-terminated and
2296 * determine how many characters would have been written. */
2297 str[size - 1] = '\0';
2299 ret = _vsnprintf(NULL, 0, format, ap);
2306 static void usbi_log_str(struct libusb_context *ctx,
2307 enum libusb_log_level level, const char * str)
2309 #if defined(USE_SYSTEM_LOGGING_FACILITY)
2310 #if defined(OS_WINDOWS)
2311 OutputDebugString(str);
2312 #elif defined(OS_WINCE)
2313 /* Windows CE only supports the Unicode version of OutputDebugString. */
2314 WCHAR wbuf[USBI_MAX_LOG_LEN];
2315 MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
2316 OutputDebugStringW(wbuf);
2317 #elif defined(__ANDROID__)
2318 int priority = ANDROID_LOG_UNKNOWN;
2320 case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
2321 case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
2322 case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
2323 case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
2325 __android_log_write(priority, "libusb", str);
2326 #elif defined(HAVE_SYSLOG_FUNC)
2327 int syslog_level = LOG_INFO;
2329 case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
2330 case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
2331 case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
2332 case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
2334 syslog(syslog_level, "%s", str);
2335 #else /* All of gcc, Clang, XCode seem to use #warning */
2336 #warning System logging is not supported on this platform. Logging to stderr will be used instead.
2341 #endif /* USE_SYSTEM_LOGGING_FACILITY */
2346 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
2347 const char *function, const char *format, va_list args)
2349 const char *prefix = "";
2350 char buf[USBI_MAX_LOG_LEN];
2351 struct timespec now;
2352 int global_debug, header_len, text_len;
2353 static int has_debug_header_been_displayed = 0;
2355 #ifdef ENABLE_DEBUG_LOGGING
2361 USBI_GET_CONTEXT(ctx);
2363 ctx_level = ctx->debug;
2365 char *dbg = getenv("LIBUSB_DEBUG");
2367 ctx_level = atoi(dbg);
2369 global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
2372 if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING)
2374 if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO)
2376 if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG)
2380 usbi_backend->clock_gettime(USBI_CLOCK_REALTIME, &now);
2381 if ((global_debug) && (!has_debug_header_been_displayed)) {
2382 has_debug_header_been_displayed = 1;
2383 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>" USBI_LOG_LINE_END);
2384 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END);
2386 if (now.tv_nsec < timestamp_origin.tv_nsec) {
2388 now.tv_nsec += 1000000000L;
2390 now.tv_sec -= timestamp_origin.tv_sec;
2391 now.tv_nsec -= timestamp_origin.tv_nsec;
2394 case LIBUSB_LOG_LEVEL_INFO:
2397 case LIBUSB_LOG_LEVEL_WARNING:
2400 case LIBUSB_LOG_LEVEL_ERROR:
2403 case LIBUSB_LOG_LEVEL_DEBUG:
2406 case LIBUSB_LOG_LEVEL_NONE:
2414 header_len = snprintf(buf, sizeof(buf),
2415 "[%2d.%06d] [%08x] libusb: %s [%s] ",
2416 (int)now.tv_sec, (int)(now.tv_nsec / 1000L), usbi_get_tid(), prefix, function);
2418 header_len = snprintf(buf, sizeof(buf),
2419 "libusb: %s [%s] ", prefix, function);
2422 if (header_len < 0 || header_len >= (int)sizeof(buf)) {
2423 /* Somehow snprintf failed to write to the buffer,
2424 * remove the header so something useful is output. */
2427 /* Make sure buffer is NUL terminated */
2428 buf[header_len] = '\0';
2429 text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
2431 if (text_len < 0 || text_len + header_len >= (int)sizeof(buf)) {
2432 /* Truncated log output. On some platforms a -1 return value means
2433 * that the output was truncated. */
2434 text_len = sizeof(buf) - header_len;
2436 if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
2437 /* Need to truncate the text slightly to fit on the terminator. */
2438 text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
2440 strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
2442 usbi_log_str(ctx, level, buf);
2445 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
2446 const char *function, const char *format, ...)
2450 va_start (args, format);
2451 usbi_log_v(ctx, level, function, format, args);
2455 /** \ingroup libusb_misc
2456 * Returns a constant NULL-terminated string with the ASCII name of a libusb
2457 * error or transfer status code. The caller must not free() the returned
2460 * \param error_code The \ref libusb_error or libusb_transfer_status code to
2461 * return the name of.
2462 * \returns The error name, or the string **UNKNOWN** if the value of
2463 * error_code is not a known error / status code.
2465 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
2467 switch (error_code) {
2468 case LIBUSB_ERROR_IO:
2469 return "LIBUSB_ERROR_IO";
2470 case LIBUSB_ERROR_INVALID_PARAM:
2471 return "LIBUSB_ERROR_INVALID_PARAM";
2472 case LIBUSB_ERROR_ACCESS:
2473 return "LIBUSB_ERROR_ACCESS";
2474 case LIBUSB_ERROR_NO_DEVICE:
2475 return "LIBUSB_ERROR_NO_DEVICE";
2476 case LIBUSB_ERROR_NOT_FOUND:
2477 return "LIBUSB_ERROR_NOT_FOUND";
2478 case LIBUSB_ERROR_BUSY:
2479 return "LIBUSB_ERROR_BUSY";
2480 case LIBUSB_ERROR_TIMEOUT:
2481 return "LIBUSB_ERROR_TIMEOUT";
2482 case LIBUSB_ERROR_OVERFLOW:
2483 return "LIBUSB_ERROR_OVERFLOW";
2484 case LIBUSB_ERROR_PIPE:
2485 return "LIBUSB_ERROR_PIPE";
2486 case LIBUSB_ERROR_INTERRUPTED:
2487 return "LIBUSB_ERROR_INTERRUPTED";
2488 case LIBUSB_ERROR_NO_MEM:
2489 return "LIBUSB_ERROR_NO_MEM";
2490 case LIBUSB_ERROR_NOT_SUPPORTED:
2491 return "LIBUSB_ERROR_NOT_SUPPORTED";
2492 case LIBUSB_ERROR_OTHER:
2493 return "LIBUSB_ERROR_OTHER";
2495 case LIBUSB_TRANSFER_ERROR:
2496 return "LIBUSB_TRANSFER_ERROR";
2497 case LIBUSB_TRANSFER_TIMED_OUT:
2498 return "LIBUSB_TRANSFER_TIMED_OUT";
2499 case LIBUSB_TRANSFER_CANCELLED:
2500 return "LIBUSB_TRANSFER_CANCELLED";
2501 case LIBUSB_TRANSFER_STALL:
2502 return "LIBUSB_TRANSFER_STALL";
2503 case LIBUSB_TRANSFER_NO_DEVICE:
2504 return "LIBUSB_TRANSFER_NO_DEVICE";
2505 case LIBUSB_TRANSFER_OVERFLOW:
2506 return "LIBUSB_TRANSFER_OVERFLOW";
2509 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
2511 return "**UNKNOWN**";
2515 /** \ingroup libusb_misc
2516 * Returns a pointer to const struct libusb_version with the version
2517 * (major, minor, micro, nano and rc) of the running library.
2520 const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
2522 return &libusb_version_internal;