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
27 #include <android/log.h>
35 static const struct libusb_version libusb_version_internal =
36 { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
37 LIBUSB_RC, "http://libusb.info" };
38 static struct timespec timestamp_origin;
39 #if defined(ENABLE_LOGGING) && !defined(USE_SYSTEM_LOGGING_FACILITY)
40 static libusb_log_cb log_handler;
43 struct libusb_context *usbi_default_context;
44 static int default_context_refcnt;
45 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
46 static struct usbi_option default_context_options[LIBUSB_OPTION_MAX];
49 usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
50 struct list_head active_contexts_list;
53 * \mainpage libusb-1.0 API Reference
55 * \section intro Introduction
57 * libusb is an open source library that allows you to communicate with USB
58 * devices from user space. For more info, see the
59 * <a href="http://libusb.info">libusb homepage</a>.
61 * This documentation is aimed at application developers wishing to
62 * communicate with USB peripherals from their own software. After reviewing
63 * this documentation, feedback and questions can be sent to the
64 * <a href="http://mailing-list.libusb.info">libusb-devel mailing list</a>.
66 * This documentation assumes knowledge of how to operate USB devices from
67 * a software standpoint (descriptors, configurations, interfaces, endpoints,
68 * control/bulk/interrupt/isochronous transfers, etc). Full information
69 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
70 * Specification</a> which is available for free download. You can probably
71 * find less verbose introductions by searching the web.
73 * \section API Application Programming Interface (API)
75 * See the \ref libusb_api page for a complete list of the libusb functions.
77 * \section features Library features
79 * - All transfer types supported (control/bulk/interrupt/isochronous)
80 * - 2 transfer interfaces:
81 * -# Synchronous (simple)
82 * -# Asynchronous (more complicated, but more powerful)
83 * - Thread safe (although the asynchronous interface means that you
84 * usually won't need to thread)
85 * - Lightweight with lean API
86 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
87 * - Hotplug support (on some platforms). See \ref libusb_hotplug.
89 * \section gettingstarted Getting Started
91 * To begin reading the API documentation, start with the Modules page which
92 * links to the different categories of libusb's functionality.
94 * One decision you will have to make is whether to use the synchronous
95 * or the asynchronous data transfer interface. The \ref libusb_io documentation
96 * provides some insight into this topic.
98 * Some example programs can be found in the libusb source distribution under
99 * the "examples" subdirectory. The libusb homepage includes a list of
100 * real-life project examples which use libusb.
102 * \section errorhandling Error handling
104 * libusb functions typically return 0 on success or a negative error code
105 * on failure. These negative error codes relate to LIBUSB_ERROR constants
106 * which are listed on the \ref libusb_misc "miscellaneous" documentation page.
108 * \section msglog Debug message logging
110 * libusb uses stderr for all logging. By default, logging is set to NONE,
111 * which means that no output will be produced. However, unless the library
112 * has been compiled with logging disabled, then any application calls to
113 * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level), or the setting of the
114 * environmental variable LIBUSB_DEBUG outside of the application, can result
115 * in logging being produced. Your application should therefore not close
116 * stderr, but instead direct it to the null device if its output is
119 * The libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) function can be
120 * used to enable logging of certain messages. Under standard configuration,
121 * libusb doesn't really log much so you are advised to use this function
122 * to enable all error/warning/ informational messages. It will help debug
123 * problems with your software.
125 * The logged messages are unstructured. There is no one-to-one correspondence
126 * between messages being logged and success or failure return codes from
127 * libusb functions. There is no format to the messages, so you should not
128 * try to capture or parse them. They are not and will not be localized.
129 * These messages are not intended to being passed to your application user;
130 * instead, you should interpret the error codes returned from libusb functions
131 * and provide appropriate notification to the user. The messages are simply
132 * there to aid you as a programmer, and if you're confused because you're
133 * getting a strange error code from a libusb function, enabling message
134 * logging may give you a suitable explanation.
136 * The LIBUSB_DEBUG environment variable can be used to enable message logging
137 * at run-time. This environment variable should be set to a log level number,
138 * which is interpreted the same as the
139 * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) parameter. When this
140 * environment variable is set, the message logging verbosity level is fixed
141 * and libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) effectively does
144 * libusb can be compiled without any logging functions, useful for embedded
145 * systems. In this case, libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level)
146 * and the LIBUSB_DEBUG environment variable have no effects.
148 * libusb can also be compiled with verbose debugging messages always. When
149 * the library is compiled in this way, all messages of all verbosities are
150 * always logged. libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) and
151 * the LIBUSB_DEBUG environment variable have no effects.
153 * \section remarks Other remarks
155 * libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts
160 * \page libusb_caveats Caveats
162 * \section threadsafety Thread safety
164 * libusb is designed to be completely thread-safe, but as with any API it
165 * cannot prevent a user from sabotaging themselves, either intentionally or
168 * Observe the following general guidelines:
170 * - Calls to functions that release a resource (e.g. libusb_close(),
171 * libusb_free_config_descriptor()) should not be called concurrently on
172 * the same resource. This is no different than concurrently calling free()
173 * on the same allocated pointer.
174 * - Each individual \ref libusb_transfer should be prepared by a single
175 * thread. In other words, no two threads should ever be concurrently
176 * filling out the fields of a \ref libusb_transfer. You can liken this to
177 * calling sprintf() with the same destination buffer from multiple threads.
178 * The results will likely not be what you want unless the input parameters
179 * are all the same, but its best to avoid this situation entirely.
180 * - Both the \ref libusb_transfer structure and its associated data buffer
181 * should not be accessed between the time the transfer is submitted and the
182 * time the completion callback is invoked. You can think of "ownership" of
183 * these things as being transferred to libusb while the transfer is active.
184 * - The various "setter" functions (e.g. libusb_set_log_cb(),
185 * libusb_set_pollfd_notifiers()) should not be called concurrently on the
186 * resource. Though doing so will not lead to any undefined behavior, it
187 * will likely produce results that the application does not expect.
189 * Rules for multiple threads and asynchronous I/O are detailed
190 * \ref libusb_mtasync "here".
192 * \section fork Fork considerations
194 * libusb is <em>not</em> designed to work across fork() calls. Depending on
195 * the platform, there may be resources in the parent process that are not
196 * available to the child (e.g. the hotplug monitor thread on Linux). In
197 * addition, since the parent and child will share libusb's internal file
198 * descriptors, using libusb in any way from the child could cause the parent
199 * process's \ref libusb_context to get into an inconsistent state.
201 * On Linux, libusb's file descriptors will be marked as CLOEXEC, which means
202 * that it is safe to fork() and exec() without worrying about the child
203 * process needing to clean up state or having access to these file descriptors.
204 * Other platforms may not be so forgiving, so consider yourself warned!
206 * \section devresets Device resets
208 * The libusb_reset_device() function allows you to reset a device. If your
209 * program has to call such a function, it should obviously be aware that
210 * the reset will cause device state to change (e.g. register values may be
213 * The problem is that any other program could reset the device your program
214 * is working with, at any time. libusb does not offer a mechanism to inform
215 * you when this has happened, so if someone else resets your device it will
216 * not be clear to your own program why the device state has changed.
218 * Ultimately, this is a limitation of writing drivers in user space.
219 * Separation from the USB stack in the underlying kernel makes it difficult
220 * for the operating system to deliver such notifications to your program.
221 * The Linux kernel USB stack allows such reset notifications to be delivered
222 * to in-kernel USB drivers, but it is not clear how such notifications could
223 * be delivered to second-class drivers that live in user space.
225 * \section blockonly Blocking-only functionality
227 * The functionality listed below is only available through synchronous,
228 * blocking functions. There are no asynchronous/non-blocking alternatives,
229 * and no clear ways of implementing these.
231 * - Configuration activation (libusb_set_configuration())
232 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
233 * - Releasing of interfaces (libusb_release_interface())
234 * - Clearing of halt/stall condition (libusb_clear_halt())
235 * - Device resets (libusb_reset_device())
237 * \section configsel Configuration selection and handling
239 * When libusb presents a device handle to an application, there is a chance
240 * that the corresponding device may be in unconfigured state. For devices
241 * with multiple configurations, there is also a chance that the configuration
242 * currently selected is not the one that the application wants to use.
244 * The obvious solution is to add a call to libusb_set_configuration() early
245 * on during your device initialization routines, but there are caveats to
247 * -# If the device is already in the desired configuration, calling
248 * libusb_set_configuration() using the same configuration value will cause
249 * a lightweight device reset. This may not be desirable behaviour.
250 * -# In the case where the desired configuration is already active, libusb
251 * may not even be able to perform a lightweight device reset. For example,
252 * take my USB keyboard with fingerprint reader: I'm interested in driving
253 * the fingerprint reader interface through libusb, but the kernel's
254 * USB-HID driver will almost always have claimed the keyboard interface.
255 * Because the kernel has claimed an interface, it is not even possible to
256 * perform the lightweight device reset, so libusb_set_configuration() will
257 * fail. (Luckily the device in question only has a single configuration.)
258 * -# libusb will be unable to set a configuration if other programs or
259 * drivers have claimed interfaces. In particular, this means that kernel
260 * drivers must be detached from all the interfaces before
261 * libusb_set_configuration() may succeed.
263 * One solution to some of the above problems is to consider the currently
264 * active configuration. If the configuration we want is already active, then
265 * we don't have to select any configuration:
268 libusb_get_configuration(dev, &cfg);
270 libusb_set_configuration(dev, desired);
273 * This is probably suitable for most scenarios, but is inherently racy:
274 * another application or driver may change the selected configuration
275 * <em>after</em> the libusb_get_configuration() call.
277 * Even in cases where libusb_set_configuration() succeeds, consider that other
278 * applications or drivers may change configuration after your application
279 * calls libusb_set_configuration().
281 * One possible way to lock your device into a specific configuration is as
283 * -# Set the desired configuration (or use the logic above to realise that
284 * it is already in the desired configuration)
285 * -# Claim the interface that you wish to use
286 * -# Check that the currently active configuration is the one that you want
289 * The above method works because once an interface is claimed, no application
290 * or driver is able to select another configuration.
292 * \section earlycomp Early transfer completion
294 * NOTE: This section is currently Linux-centric. I am not sure if any of these
295 * considerations apply to Darwin or other platforms.
297 * When a transfer completes early (i.e. when less data is received/sent in
298 * any one packet than the transfer buffer allows for) then libusb is designed
299 * to terminate the transfer immediately, not transferring or receiving any
300 * more data unless other transfers have been queued by the user.
302 * On legacy platforms, libusb is unable to do this in all situations. After
303 * the incomplete packet occurs, "surplus" data may be transferred. For recent
304 * versions of libusb, this information is kept (the data length of the
305 * transfer is updated) and, for device-to-host transfers, any surplus data was
306 * added to the buffer. Still, this is not a nice solution because it loses the
307 * information about the end of the short packet, and the user probably wanted
308 * that surplus data to arrive in the next logical transfer.
310 * \section zlp Zero length packets
312 * - libusb is able to send a packet of zero length to an endpoint simply by
313 * submitting a transfer of zero length.
314 * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
315 * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently supported on Linux,
316 * Darwin and Windows (WinUSB).
320 * \page libusb_contexts Contexts
322 * It is possible that libusb may be used simultaneously from two independent
323 * libraries linked into the same executable. For example, if your application
324 * has a plugin-like system which allows the user to dynamically load a range
325 * of modules into your program, it is feasible that two independently
326 * developed modules may both use libusb.
328 * libusb is written to allow for these multiple user scenarios. The two
329 * "instances" of libusb will not interfere: libusb_set_option() calls
330 * from one user will not affect the same settings for other users, other
331 * users can continue using libusb after one of them calls libusb_exit(), etc.
333 * This is made possible through libusb's <em>context</em> concept. When you
334 * call libusb_init(), you are (optionally) given a context. You can then pass
335 * this context pointer back into future libusb functions.
337 * In order to keep things simple for more simplistic applications, it is
338 * legal to pass NULL to all functions requiring a context pointer (as long as
339 * you're sure no other code will attempt to use libusb from the same process).
340 * When you pass NULL, the default context will be used. The default context
341 * is created the first time a process calls libusb_init() when no other
342 * context is alive. Contexts are destroyed during libusb_exit().
344 * The default context is reference-counted and can be shared. That means that
345 * if libusb_init(NULL) is called twice within the same process, the two
346 * users end up sharing the same context. The deinitialization and freeing of
347 * the default context will only happen when the last user calls libusb_exit().
348 * In other words, the default context is created and initialized when its
349 * reference count goes from 0 to 1, and is deinitialized and destroyed when
350 * its reference count goes from 1 to 0.
352 * You may be wondering why only a subset of libusb functions require a
353 * context pointer in their function definition. Internally, libusb stores
354 * context pointers in other objects (e.g. libusb_device instances) and hence
355 * can infer the context from those objects.
359 * \page libusb_api Application Programming Interface
361 * This is the complete list of libusb functions, structures and
362 * enumerations in alphabetical order.
365 * - libusb_alloc_streams()
366 * - libusb_alloc_transfer()
367 * - libusb_attach_kernel_driver()
368 * - libusb_bulk_transfer()
369 * - libusb_cancel_transfer()
370 * - libusb_claim_interface()
371 * - libusb_clear_halt()
373 * - libusb_control_transfer()
374 * - libusb_control_transfer_get_data()
375 * - libusb_control_transfer_get_setup()
376 * - libusb_cpu_to_le16()
377 * - libusb_detach_kernel_driver()
378 * - libusb_dev_mem_alloc()
379 * - libusb_dev_mem_free()
380 * - libusb_error_name()
381 * - libusb_event_handler_active()
382 * - libusb_event_handling_ok()
384 * - libusb_fill_bulk_stream_transfer()
385 * - libusb_fill_bulk_transfer()
386 * - libusb_fill_control_setup()
387 * - libusb_fill_control_transfer()
388 * - libusb_fill_interrupt_transfer()
389 * - libusb_fill_iso_transfer()
390 * - libusb_free_bos_descriptor()
391 * - libusb_free_config_descriptor()
392 * - libusb_free_container_id_descriptor()
393 * - libusb_free_device_list()
394 * - libusb_free_pollfds()
395 * - libusb_free_ss_endpoint_companion_descriptor()
396 * - libusb_free_ss_usb_device_capability_descriptor()
397 * - libusb_free_streams()
398 * - libusb_free_transfer()
399 * - libusb_free_usb_2_0_extension_descriptor()
400 * - libusb_get_active_config_descriptor()
401 * - libusb_get_bos_descriptor()
402 * - libusb_get_bus_number()
403 * - libusb_get_config_descriptor()
404 * - libusb_get_config_descriptor_by_value()
405 * - libusb_get_configuration()
406 * - libusb_get_container_id_descriptor()
407 * - libusb_get_descriptor()
408 * - libusb_get_device()
409 * - libusb_get_device_address()
410 * - libusb_get_device_descriptor()
411 * - libusb_get_device_list()
412 * - libusb_get_device_speed()
413 * - libusb_get_iso_packet_buffer()
414 * - libusb_get_iso_packet_buffer_simple()
415 * - libusb_get_max_iso_packet_size()
416 * - libusb_get_max_packet_size()
417 * - libusb_get_next_timeout()
418 * - libusb_get_parent()
419 * - libusb_get_pollfds()
420 * - libusb_get_port_number()
421 * - libusb_get_port_numbers()
422 * - libusb_get_port_path()
423 * - libusb_get_ss_endpoint_companion_descriptor()
424 * - libusb_get_ss_usb_device_capability_descriptor()
425 * - libusb_get_string_descriptor()
426 * - libusb_get_string_descriptor_ascii()
427 * - libusb_get_usb_2_0_extension_descriptor()
428 * - libusb_get_version()
429 * - libusb_handle_events()
430 * - libusb_handle_events_completed()
431 * - libusb_handle_events_locked()
432 * - libusb_handle_events_timeout()
433 * - libusb_handle_events_timeout_completed()
434 * - libusb_has_capability()
435 * - libusb_hotplug_deregister_callback()
436 * - libusb_hotplug_register_callback()
438 * - libusb_interrupt_event_handler()
439 * - libusb_interrupt_transfer()
440 * - libusb_kernel_driver_active()
441 * - libusb_lock_events()
442 * - libusb_lock_event_waiters()
444 * - libusb_open_device_with_vid_pid()
445 * - libusb_pollfds_handle_timeouts()
446 * - libusb_ref_device()
447 * - libusb_release_interface()
448 * - libusb_reset_device()
449 * - libusb_set_auto_detach_kernel_driver()
450 * - libusb_set_configuration()
451 * - libusb_set_debug()
452 * - libusb_set_log_cb()
453 * - libusb_set_interface_alt_setting()
454 * - libusb_set_iso_packet_lengths()
455 * - libusb_set_option()
456 * - libusb_setlocale()
457 * - libusb_set_pollfd_notifiers()
458 * - libusb_strerror()
459 * - libusb_submit_transfer()
460 * - libusb_transfer_get_stream_id()
461 * - libusb_transfer_set_stream_id()
462 * - libusb_try_lock_events()
463 * - libusb_unlock_events()
464 * - libusb_unlock_event_waiters()
465 * - libusb_unref_device()
466 * - libusb_wait_for_event()
467 * - libusb_wrap_sys_device()
469 * \section Structures
470 * - libusb_bos_descriptor
471 * - libusb_bos_dev_capability_descriptor
472 * - libusb_config_descriptor
473 * - libusb_container_id_descriptor
474 * - \ref libusb_context
475 * - libusb_control_setup
476 * - \ref libusb_device
477 * - libusb_device_descriptor
478 * - \ref libusb_device_handle
479 * - libusb_endpoint_descriptor
481 * - libusb_interface_descriptor
482 * - libusb_iso_packet_descriptor
484 * - libusb_ss_endpoint_companion_descriptor
485 * - libusb_ss_usb_device_capability_descriptor
487 * - libusb_usb_2_0_extension_descriptor
491 * - \ref libusb_bos_type
492 * - \ref libusb_capability
493 * - \ref libusb_class_code
494 * - \ref libusb_descriptor_type
495 * - \ref libusb_endpoint_direction
496 * - \ref libusb_endpoint_transfer_type
497 * - \ref libusb_error
498 * - \ref libusb_iso_sync_type
499 * - \ref libusb_iso_usage_type
500 * - \ref libusb_log_level
501 * - \ref libusb_option
502 * - \ref libusb_request_recipient
503 * - \ref libusb_request_type
504 * - \ref libusb_speed
505 * - \ref libusb_ss_usb_device_capability_attributes
506 * - \ref libusb_standard_request
507 * - \ref libusb_supported_speed
508 * - \ref libusb_transfer_flags
509 * - \ref libusb_transfer_status
510 * - \ref libusb_transfer_type
511 * - \ref libusb_usb_2_0_extension_attributes
515 * @defgroup libusb_lib Library initialization/deinitialization
516 * This page details how to initialize and deinitialize libusb. Initialization
517 * must be performed before using any libusb functionality, and similarly you
518 * must not call any libusb functions after deinitialization.
522 * @defgroup libusb_dev Device handling and enumeration
523 * The functionality documented below is designed to help with the following
525 * - Enumerating the USB devices currently attached to the system
526 * - Choosing a device to operate from your software
527 * - Opening and closing the chosen device
529 * \section nutshell In a nutshell...
531 * The description below really makes things sound more complicated than they
532 * actually are. The following sequence of function calls will be suitable
533 * for almost all scenarios and does not require you to have such a deep
534 * understanding of the resource management issues:
537 libusb_device **list;
538 libusb_device *found = NULL;
539 ssize_t cnt = libusb_get_device_list(NULL, &list);
545 for (i = 0; i < cnt; i++) {
546 libusb_device *device = list[i];
547 if (is_interesting(device)) {
554 libusb_device_handle *handle;
556 err = libusb_open(found, &handle);
562 libusb_free_device_list(list, 1);
565 * The two important points:
566 * - You asked libusb_free_device_list() to unreference the devices (2nd
568 * - You opened the device before freeing the list and unreferencing the
571 * If you ended up with a handle, you can now proceed to perform I/O on the
574 * \section devshandles Devices and device handles
575 * libusb has a concept of a USB device, represented by the
576 * \ref libusb_device opaque type. A device represents a USB device that
577 * is currently or was previously connected to the system. Using a reference
578 * to a device, you can determine certain information about the device (e.g.
579 * you can read the descriptor data).
581 * The libusb_get_device_list() function can be used to obtain a list of
582 * devices currently connected to the system. This is known as device
583 * discovery. Devices can also be discovered with the hotplug mechanism,
584 * whereby a callback function registered with libusb_hotplug_register_callback()
585 * will be called when a device of interest is connected or disconnected.
587 * Just because you have a reference to a device does not mean it is
588 * necessarily usable. The device may have been unplugged, you may not have
589 * permission to operate such device, or another program or driver may be
592 * When you've found a device that you'd like to operate, you must ask
593 * libusb to open the device using the libusb_open() function. Assuming
594 * success, libusb then returns you a <em>device handle</em>
595 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
596 * operate on the handle rather than the original device pointer.
598 * \section devref Device discovery and reference counting
600 * Device discovery (i.e. calling libusb_get_device_list()) returns a
601 * freshly-allocated list of devices. The list itself must be freed when
602 * you are done with it. libusb also needs to know when it is OK to free
603 * the contents of the list - the devices themselves.
605 * To handle these issues, libusb provides you with two separate items:
606 * - A function to free the list itself
607 * - A reference counting system for the devices inside
609 * New devices presented by the libusb_get_device_list() function all have a
610 * reference count of 1. You can increase and decrease reference count using
611 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
612 * its reference count reaches 0.
614 * With the above information in mind, the process of opening a device can
615 * be viewed as follows:
616 * -# Discover devices using libusb_get_device_list() or libusb_hotplug_register_callback().
617 * -# Choose the device that you want to operate, and call libusb_open().
618 * -# Unref all devices in the discovered device list.
619 * -# Free the discovered device list.
621 * The order is important - you must not unreference the device before
622 * attempting to open it, because unreferencing it may destroy the device.
624 * For convenience, the libusb_free_device_list() function includes a
625 * parameter to optionally unreference all the devices in the list before
626 * freeing the list itself. This combines steps 3 and 4 above.
628 * As an implementation detail, libusb_open() actually adds a reference to
629 * the device in question. This is because the device remains available
630 * through the handle via libusb_get_device(). The reference is deleted during
634 /** @defgroup libusb_misc Miscellaneous */
636 /* we traverse usbfs without knowing how many devices we are going to find.
637 * so we create this discovered_devs model which is similar to a linked-list
638 * which grows when required. it can be freed once discovery has completed,
639 * eliminating the need for a list node in the libusb_device structure
641 #define DISCOVERED_DEVICES_SIZE_STEP 16
643 static struct discovered_devs *discovered_devs_alloc(void)
645 struct discovered_devs *ret =
646 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
650 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
655 static void discovered_devs_free(struct discovered_devs *discdevs)
659 for (i = 0; i < discdevs->len; i++)
660 libusb_unref_device(discdevs->devices[i]);
665 /* append a device to the discovered devices collection. may realloc itself,
666 * returning new discdevs. returns NULL on realloc failure. */
667 struct discovered_devs *discovered_devs_append(
668 struct discovered_devs *discdevs, struct libusb_device *dev)
670 size_t len = discdevs->len;
672 struct discovered_devs *new_discdevs;
674 /* if there is space, just append the device */
675 if (len < discdevs->capacity) {
676 discdevs->devices[len] = libusb_ref_device(dev);
681 /* exceeded capacity, need to grow */
682 usbi_dbg(DEVICE_CTX(dev), "need to increase capacity");
683 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
684 /* can't use usbi_reallocf here because in failure cases it would
685 * free the existing discdevs without unreferencing its devices. */
686 new_discdevs = realloc(discdevs,
687 sizeof(*discdevs) + (sizeof(void *) * capacity));
689 discovered_devs_free(discdevs);
693 discdevs = new_discdevs;
694 discdevs->capacity = capacity;
695 discdevs->devices[len] = libusb_ref_device(dev);
701 /* Allocate a new device with a specific session ID. The returned device has
702 * a reference count of 1. */
703 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
704 unsigned long session_id)
706 size_t priv_size = usbi_backend.device_priv_size;
707 struct libusb_device *dev = calloc(1, PTR_ALIGN(sizeof(*dev)) + priv_size);
712 usbi_atomic_store(&dev->refcnt, 1);
715 dev->session_data = session_id;
716 dev->speed = LIBUSB_SPEED_UNKNOWN;
718 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
719 usbi_connect_device(dev);
724 void usbi_connect_device(struct libusb_device *dev)
726 struct libusb_context *ctx = DEVICE_CTX(dev);
728 usbi_atomic_store(&dev->attached, 1);
730 usbi_mutex_lock(&dev->ctx->usb_devs_lock);
731 list_add(&dev->list, &dev->ctx->usb_devs);
732 usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
734 usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED);
737 void usbi_disconnect_device(struct libusb_device *dev)
739 struct libusb_context *ctx = DEVICE_CTX(dev);
741 usbi_atomic_store(&dev->attached, 0);
743 usbi_mutex_lock(&ctx->usb_devs_lock);
744 list_del(&dev->list);
745 usbi_mutex_unlock(&ctx->usb_devs_lock);
747 usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);
750 /* Perform some final sanity checks on a newly discovered device. If this
751 * function fails (negative return code), the device should not be added
752 * to the discovered device list. */
753 int usbi_sanitize_device(struct libusb_device *dev)
755 uint8_t num_configurations;
757 if (dev->device_descriptor.bLength != LIBUSB_DT_DEVICE_SIZE ||
758 dev->device_descriptor.bDescriptorType != LIBUSB_DT_DEVICE) {
759 usbi_err(DEVICE_CTX(dev), "invalid device descriptor");
760 return LIBUSB_ERROR_IO;
763 num_configurations = dev->device_descriptor.bNumConfigurations;
764 if (num_configurations > USB_MAXCONFIG) {
765 usbi_err(DEVICE_CTX(dev), "too many configurations");
766 return LIBUSB_ERROR_IO;
767 } else if (0 == num_configurations) {
768 usbi_dbg(DEVICE_CTX(dev), "zero configurations, maybe an unauthorized device");
774 /* Examine libusb's internal list of known devices, looking for one with
775 * a specific session ID. Returns the matching device if it was found, and
777 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
778 unsigned long session_id)
780 struct libusb_device *dev;
781 struct libusb_device *ret = NULL;
783 usbi_mutex_lock(&ctx->usb_devs_lock);
784 for_each_device(ctx, dev) {
785 if (dev->session_data == session_id) {
786 ret = libusb_ref_device(dev);
790 usbi_mutex_unlock(&ctx->usb_devs_lock);
795 /** @ingroup libusb_dev
796 * Returns a list of USB devices currently attached to the system. This is
797 * your entry point into finding a USB device to operate.
799 * You are expected to unreference all the devices when you are done with
800 * them, and then free the list with libusb_free_device_list(). Note that
801 * libusb_free_device_list() can unref all the devices for you. Be careful
802 * not to unreference a device you are about to open until after you have
805 * This return value of this function indicates the number of devices in
806 * the resultant list. The list is actually one element larger, as it is
809 * \param ctx the context to operate on, or NULL for the default context
810 * \param list output location for a list of devices. Must be later freed with
811 * libusb_free_device_list().
812 * \returns the number of devices in the outputted list, or any
813 * \ref libusb_error according to errors encountered by the backend.
815 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
816 libusb_device ***list)
818 struct discovered_devs *discdevs = discovered_devs_alloc();
819 struct libusb_device **ret;
826 return LIBUSB_ERROR_NO_MEM;
828 ctx = usbi_get_context(ctx);
830 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
831 /* backend provides hotplug support */
832 struct libusb_device *dev;
834 if (usbi_backend.hotplug_poll)
835 usbi_backend.hotplug_poll();
837 usbi_mutex_lock(&ctx->usb_devs_lock);
838 for_each_device(ctx, dev) {
839 discdevs = discovered_devs_append(discdevs, dev);
842 r = LIBUSB_ERROR_NO_MEM;
846 usbi_mutex_unlock(&ctx->usb_devs_lock);
848 /* backend does not provide hotplug support */
849 r = usbi_backend.get_device_list(ctx, &discdevs);
857 /* convert discovered_devs into a list */
858 len = (ssize_t)discdevs->len;
859 ret = calloc((size_t)len + 1, sizeof(struct libusb_device *));
861 len = LIBUSB_ERROR_NO_MEM;
866 for (i = 0; i < len; i++) {
867 struct libusb_device *dev = discdevs->devices[i];
868 ret[i] = libusb_ref_device(dev);
874 discovered_devs_free(discdevs);
878 /** \ingroup libusb_dev
879 * Frees a list of devices previously discovered using
880 * libusb_get_device_list(). If the unref_devices parameter is set, the
881 * reference count of each device in the list is decremented by 1.
882 * \param list the list to free
883 * \param unref_devices whether to unref the devices in the list
885 void API_EXPORTED libusb_free_device_list(libusb_device **list,
893 struct libusb_device *dev;
895 while ((dev = list[i++]) != NULL)
896 libusb_unref_device(dev);
901 /** \ingroup libusb_dev
902 * Get the number of the bus that a device is connected to.
903 * \param dev a device
904 * \returns the bus number
906 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
908 return dev->bus_number;
911 /** \ingroup libusb_dev
912 * Get the number of the port that a device is connected to.
913 * Unless the OS does something funky, or you are hot-plugging USB extension cards,
914 * the port number returned by this call is usually guaranteed to be uniquely tied
915 * to a physical port, meaning that different devices plugged on the same physical
916 * port should return the same port number.
918 * But outside of this, there is no guarantee that the port number returned by this
919 * call will remain the same, or even match the order in which ports have been
920 * numbered by the HUB/HCD manufacturer.
922 * \param dev a device
923 * \returns the port number (0 if not available)
925 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
927 return dev->port_number;
930 /** \ingroup libusb_dev
931 * Get the list of all port numbers from root for the specified device
933 * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
934 * \param dev a device
935 * \param port_numbers the array that should contain the port numbers
936 * \param port_numbers_len the maximum length of the array. As per the USB 3.0
937 * specs, the current maximum limit for the depth is 7.
938 * \returns the number of elements filled
939 * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
941 int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
942 uint8_t *port_numbers, int port_numbers_len)
944 int i = port_numbers_len;
945 struct libusb_context *ctx = DEVICE_CTX(dev);
947 if (port_numbers_len <= 0)
948 return LIBUSB_ERROR_INVALID_PARAM;
950 // HCDs can be listed as devices with port #0
951 while((dev) && (dev->port_number != 0)) {
953 usbi_warn(ctx, "port numbers array is too small");
954 return LIBUSB_ERROR_OVERFLOW;
956 port_numbers[i] = dev->port_number;
957 dev = dev->parent_dev;
959 if (i < port_numbers_len)
960 memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
961 return port_numbers_len - i;
964 /** \ingroup libusb_dev
965 * \deprecated Please use \ref libusb_get_port_numbers() instead.
967 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
968 uint8_t *port_numbers, uint8_t port_numbers_len)
972 return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
975 /** \ingroup libusb_dev
976 * Get the the parent from the specified device.
977 * \param dev a device
978 * \returns the device parent or NULL if not available
979 * You should issue a \ref libusb_get_device_list() before calling this
980 * function and make sure that you only access the parent before issuing
981 * \ref libusb_free_device_list(). The reason is that libusb currently does
982 * not maintain a permanent list of device instances, and therefore can
983 * only guarantee that parents are fully instantiated within a
984 * libusb_get_device_list() - libusb_free_device_list() block.
987 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
989 return dev->parent_dev;
992 /** \ingroup libusb_dev
993 * Get the address of the device on the bus it is connected to.
994 * \param dev a device
995 * \returns the device address
997 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
999 return dev->device_address;
1002 /** \ingroup libusb_dev
1003 * Get the negotiated connection speed for a device.
1004 * \param dev a device
1005 * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
1006 * the OS doesn't know or doesn't support returning the negotiated speed.
1008 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
1013 static const struct libusb_endpoint_descriptor *find_endpoint(
1014 struct libusb_config_descriptor *config, unsigned char endpoint)
1017 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
1018 const struct libusb_interface *iface = &config->interface[iface_idx];
1021 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
1023 const struct libusb_interface_descriptor *altsetting
1024 = &iface->altsetting[altsetting_idx];
1027 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
1028 const struct libusb_endpoint_descriptor *ep =
1029 &altsetting->endpoint[ep_idx];
1030 if (ep->bEndpointAddress == endpoint)
1038 /** \ingroup libusb_dev
1039 * Convenience function to retrieve the wMaxPacketSize value for a particular
1040 * endpoint in the active device configuration.
1042 * This function was originally intended to be of assistance when setting up
1043 * isochronous transfers, but a design mistake resulted in this function
1044 * instead. It simply returns the wMaxPacketSize value without considering
1045 * its contents. If you're dealing with isochronous transfers, you probably
1046 * want libusb_get_max_iso_packet_size() instead.
1048 * \param dev a device
1049 * \param endpoint address of the endpoint in question
1050 * \returns the wMaxPacketSize value
1051 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1052 * \returns LIBUSB_ERROR_OTHER on other failure
1054 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
1055 unsigned char endpoint)
1057 struct libusb_config_descriptor *config;
1058 const struct libusb_endpoint_descriptor *ep;
1061 r = libusb_get_active_config_descriptor(dev, &config);
1063 usbi_err(DEVICE_CTX(dev),
1064 "could not retrieve active config descriptor");
1065 return LIBUSB_ERROR_OTHER;
1068 ep = find_endpoint(config, endpoint);
1070 r = LIBUSB_ERROR_NOT_FOUND;
1074 r = ep->wMaxPacketSize;
1077 libusb_free_config_descriptor(config);
1081 /** \ingroup libusb_dev
1082 * Calculate the maximum packet size which a specific endpoint is capable is
1083 * sending or receiving in the duration of 1 microframe
1085 * Only the active configuration is examined. The calculation is based on the
1086 * wMaxPacketSize field in the endpoint descriptor as described in section
1087 * 9.6.6 in the USB 2.0 specifications.
1089 * If acting on an isochronous or interrupt endpoint, this function will
1090 * multiply the value found in bits 0:10 by the number of transactions per
1091 * microframe (determined by bits 11:12). Otherwise, this function just
1092 * returns the numeric value found in bits 0:10. For USB 3.0 device, it
1093 * will attempts to retrieve the Endpoint Companion Descriptor to return
1094 * wBytesPerInterval.
1096 * This function is useful for setting up isochronous transfers, for example
1097 * you might pass the return value from this function to
1098 * libusb_set_iso_packet_lengths() in order to set the length field of every
1099 * isochronous packet in a transfer.
1103 * \param dev a device
1104 * \param endpoint address of the endpoint in question
1105 * \returns the maximum packet size which can be sent/received on this endpoint
1106 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1107 * \returns LIBUSB_ERROR_OTHER on other failure
1109 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
1110 unsigned char endpoint)
1112 struct libusb_config_descriptor *config;
1113 const struct libusb_endpoint_descriptor *ep;
1114 struct libusb_ss_endpoint_companion_descriptor *ss_ep_cmp;
1115 enum libusb_endpoint_transfer_type ep_type;
1120 r = libusb_get_active_config_descriptor(dev, &config);
1122 usbi_err(DEVICE_CTX(dev),
1123 "could not retrieve active config descriptor");
1124 return LIBUSB_ERROR_OTHER;
1127 ep = find_endpoint(config, endpoint);
1129 r = LIBUSB_ERROR_NOT_FOUND;
1133 speed = libusb_get_device_speed(dev);
1134 if (speed >= LIBUSB_SPEED_SUPER) {
1135 r = libusb_get_ss_endpoint_companion_descriptor(dev->ctx, ep, &ss_ep_cmp);
1136 if (r == LIBUSB_SUCCESS) {
1137 r = ss_ep_cmp->wBytesPerInterval;
1138 libusb_free_ss_endpoint_companion_descriptor(ss_ep_cmp);
1142 /* If the device isn't a SuperSpeed device or retrieving the SS endpoint didn't worked. */
1143 if (speed < LIBUSB_SPEED_SUPER || r < 0) {
1144 val = ep->wMaxPacketSize;
1145 ep_type = (enum libusb_endpoint_transfer_type) (ep->bmAttributes & 0x3);
1148 if (ep_type == LIBUSB_ENDPOINT_TRANSFER_TYPE_ISOCHRONOUS
1149 || ep_type == LIBUSB_ENDPOINT_TRANSFER_TYPE_INTERRUPT)
1150 r *= (1 + ((val >> 11) & 3));
1154 libusb_free_config_descriptor(config);
1158 /** \ingroup libusb_dev
1159 * Increment the reference count of a device.
1160 * \param dev the device to reference
1161 * \returns the same device
1164 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
1168 refcnt = usbi_atomic_inc(&dev->refcnt);
1169 assert(refcnt >= 2);
1174 /** \ingroup libusb_dev
1175 * Decrement the reference count of a device. If the decrement operation
1176 * causes the reference count to reach zero, the device shall be destroyed.
1177 * \param dev the device to unreference
1179 void API_EXPORTED libusb_unref_device(libusb_device *dev)
1186 refcnt = usbi_atomic_dec(&dev->refcnt);
1187 assert(refcnt >= 0);
1190 usbi_dbg(DEVICE_CTX(dev), "destroy device %d.%d", dev->bus_number, dev->device_address);
1192 libusb_unref_device(dev->parent_dev);
1194 if (usbi_backend.destroy_device)
1195 usbi_backend.destroy_device(dev);
1197 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1198 /* backend does not support hotplug */
1199 usbi_disconnect_device(dev);
1206 /** \ingroup libusb_dev
1207 * Wrap a platform-specific system device handle and obtain a libusb device
1208 * handle for the underlying device. The handle allows you to use libusb to
1209 * perform I/O on the device in question.
1211 * Call libusb_set_option(NULL, LIBUSB_OPTION_NO_DEVICE_DISCOVERY) before
1212 * libusb_init() if you want to skip enumeration of USB devices. In particular,
1213 * this might be needed on Android if you don't have authority to access USB
1214 * devices in general.
1216 * On Linux, the system device handle must be a valid file descriptor opened
1217 * on the device node.
1219 * The system device handle must remain open until libusb_close() is called.
1220 * The system device handle will not be closed by libusb_close().
1222 * Internally, this function creates a temporary device and makes it
1223 * available to you through libusb_get_device(). This device is destroyed
1224 * during libusb_close(). The device shall not be opened through libusb_open().
1226 * This is a non-blocking function; no requests are sent over the bus.
1228 * Since version 1.0.23, \ref LIBUSB_API_VERSION >= 0x01000107
1230 * \param ctx the context to operate on, or NULL for the default context
1231 * \param sys_dev the platform-specific system device handle
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_NOT_SUPPORTED if the operation is not supported on this
1239 * \returns another LIBUSB_ERROR code on other failure
1241 int API_EXPORTED libusb_wrap_sys_device(libusb_context *ctx, intptr_t sys_dev,
1242 libusb_device_handle **dev_handle)
1244 struct libusb_device_handle *_dev_handle;
1245 size_t priv_size = usbi_backend.device_handle_priv_size;
1248 usbi_dbg(ctx, "wrap_sys_device 0x%" PRIxPTR, (uintptr_t)sys_dev);
1250 ctx = usbi_get_context(ctx);
1252 if (!usbi_backend.wrap_sys_device)
1253 return LIBUSB_ERROR_NOT_SUPPORTED;
1255 _dev_handle = calloc(1, PTR_ALIGN(sizeof(*_dev_handle)) + priv_size);
1257 return LIBUSB_ERROR_NO_MEM;
1259 usbi_mutex_init(&_dev_handle->lock);
1261 r = usbi_backend.wrap_sys_device(ctx, _dev_handle, sys_dev);
1263 usbi_dbg(ctx, "wrap_sys_device 0x%" PRIxPTR " returns %d", (uintptr_t)sys_dev, r);
1264 usbi_mutex_destroy(&_dev_handle->lock);
1269 usbi_mutex_lock(&ctx->open_devs_lock);
1270 list_add(&_dev_handle->list, &ctx->open_devs);
1271 usbi_mutex_unlock(&ctx->open_devs_lock);
1272 *dev_handle = _dev_handle;
1277 /** \ingroup libusb_dev
1278 * Open a device and obtain a device handle. A handle allows you to perform
1279 * I/O on the device in question.
1281 * Internally, this function adds a reference to the device and makes it
1282 * available to you through libusb_get_device(). This reference is removed
1283 * during libusb_close().
1285 * This is a non-blocking function; no requests are sent over the bus.
1287 * \param dev the device to open
1288 * \param dev_handle output location for the returned device handle pointer. Only
1289 * populated when the return code is 0.
1290 * \returns 0 on success
1291 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
1292 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1293 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1294 * \returns another LIBUSB_ERROR code on other failure
1296 int API_EXPORTED libusb_open(libusb_device *dev,
1297 libusb_device_handle **dev_handle)
1299 struct libusb_context *ctx = DEVICE_CTX(dev);
1300 struct libusb_device_handle *_dev_handle;
1301 size_t priv_size = usbi_backend.device_handle_priv_size;
1304 usbi_dbg(DEVICE_CTX(dev), "open %d.%d", dev->bus_number, dev->device_address);
1306 if (!usbi_atomic_load(&dev->attached))
1307 return LIBUSB_ERROR_NO_DEVICE;
1309 _dev_handle = calloc(1, PTR_ALIGN(sizeof(*_dev_handle)) + priv_size);
1311 return LIBUSB_ERROR_NO_MEM;
1313 usbi_mutex_init(&_dev_handle->lock);
1315 _dev_handle->dev = libusb_ref_device(dev);
1317 r = usbi_backend.open(_dev_handle);
1319 usbi_dbg(DEVICE_CTX(dev), "open %d.%d returns %d", dev->bus_number, dev->device_address, r);
1320 libusb_unref_device(dev);
1321 usbi_mutex_destroy(&_dev_handle->lock);
1326 usbi_mutex_lock(&ctx->open_devs_lock);
1327 list_add(&_dev_handle->list, &ctx->open_devs);
1328 usbi_mutex_unlock(&ctx->open_devs_lock);
1329 *dev_handle = _dev_handle;
1334 /** \ingroup libusb_dev
1335 * Convenience function for finding a device with a particular
1336 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1337 * for those scenarios where you are using libusb to knock up a quick test
1338 * application - it allows you to avoid calling libusb_get_device_list() and
1339 * worrying about traversing/freeing the list.
1341 * This function has limitations and is hence not intended for use in real
1342 * applications: if multiple devices have the same IDs it will only
1343 * give you the first one, etc.
1345 * \param ctx the context to operate on, or NULL for the default context
1346 * \param vendor_id the idVendor value to search for
1347 * \param product_id the idProduct value to search for
1348 * \returns a device handle for the first found device, or NULL on error
1349 * or if the device could not be found. */
1351 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1352 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1354 struct libusb_device **devs;
1355 struct libusb_device *found = NULL;
1356 struct libusb_device *dev;
1357 struct libusb_device_handle *dev_handle = NULL;
1361 if (libusb_get_device_list(ctx, &devs) < 0)
1364 while ((dev = devs[i++]) != NULL) {
1365 struct libusb_device_descriptor desc;
1366 r = libusb_get_device_descriptor(dev, &desc);
1369 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1376 r = libusb_open(found, &dev_handle);
1382 libusb_free_device_list(devs, 1);
1386 static void do_close(struct libusb_context *ctx,
1387 struct libusb_device_handle *dev_handle)
1389 struct usbi_transfer *itransfer;
1390 struct usbi_transfer *tmp;
1392 /* remove any transfers in flight that are for this device */
1393 usbi_mutex_lock(&ctx->flying_transfers_lock);
1395 /* safe iteration because transfers may be being deleted */
1396 for_each_transfer_safe(ctx, itransfer, tmp) {
1397 struct libusb_transfer *transfer =
1398 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1400 if (transfer->dev_handle != dev_handle)
1403 usbi_mutex_lock(&itransfer->lock);
1404 if (!(itransfer->state_flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1405 usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1407 if (itransfer->state_flags & USBI_TRANSFER_CANCELLING)
1408 usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1410 usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1412 usbi_mutex_unlock(&itransfer->lock);
1414 /* remove from the list of in-flight transfers and make sure
1415 * we don't accidentally use the device handle in the future
1416 * (or that such accesses will be easily caught and identified as a crash)
1418 list_del(&itransfer->list);
1419 transfer->dev_handle = NULL;
1421 /* it is up to the user to free up the actual transfer struct. this is
1422 * just making sure that we don't attempt to process the transfer after
1423 * the device handle is invalid
1425 usbi_dbg(ctx, "Removed transfer %p from the in-flight list because device handle %p closed",
1426 transfer, dev_handle);
1428 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1430 usbi_mutex_lock(&ctx->open_devs_lock);
1431 list_del(&dev_handle->list);
1432 usbi_mutex_unlock(&ctx->open_devs_lock);
1434 usbi_backend.close(dev_handle);
1435 libusb_unref_device(dev_handle->dev);
1436 usbi_mutex_destroy(&dev_handle->lock);
1440 /** \ingroup libusb_dev
1441 * Close a device handle. Should be called on all open handles before your
1442 * application exits.
1444 * Internally, this function destroys the reference that was added by
1445 * libusb_open() on the given device.
1447 * This is a non-blocking function; no requests are sent over the bus.
1449 * \param dev_handle the device handle to close
1451 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1453 struct libusb_context *ctx;
1454 unsigned int event_flags;
1455 int handling_events;
1459 ctx = HANDLE_CTX(dev_handle);
1462 handling_events = usbi_handling_events(ctx);
1464 /* Similarly to libusb_open(), we want to interrupt all event handlers
1465 * at this point. More importantly, we want to perform the actual close of
1466 * the device while holding the event handling lock (preventing any other
1467 * thread from doing event handling) because we will be removing a file
1468 * descriptor from the polling loop. If this is being called by the current
1469 * event handler, we can bypass the interruption code because we already
1470 * hold the event handling lock. */
1472 if (!handling_events) {
1473 /* Record that we are closing a device.
1474 * Only signal an event if there are no prior pending events. */
1475 usbi_mutex_lock(&ctx->event_data_lock);
1476 event_flags = ctx->event_flags;
1477 if (!ctx->device_close++)
1478 ctx->event_flags |= USBI_EVENT_DEVICE_CLOSE;
1480 usbi_signal_event(&ctx->event);
1481 usbi_mutex_unlock(&ctx->event_data_lock);
1483 /* take event handling lock */
1484 libusb_lock_events(ctx);
1487 /* Close the device */
1488 do_close(ctx, dev_handle);
1490 if (!handling_events) {
1491 /* We're done with closing this device.
1492 * Clear the event pipe if there are no further pending events. */
1493 usbi_mutex_lock(&ctx->event_data_lock);
1494 if (!--ctx->device_close)
1495 ctx->event_flags &= ~USBI_EVENT_DEVICE_CLOSE;
1496 if (!ctx->event_flags)
1497 usbi_clear_event(&ctx->event);
1498 usbi_mutex_unlock(&ctx->event_data_lock);
1500 /* Release event handling lock and wake up event waiters */
1501 libusb_unlock_events(ctx);
1505 /** \ingroup libusb_dev
1506 * Get the underlying device for a device handle. This function does not modify
1507 * the reference count of the returned device, so do not feel compelled to
1508 * unreference it when you are done.
1509 * \param dev_handle a device handle
1510 * \returns the underlying device
1513 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1515 return dev_handle->dev;
1518 /** \ingroup libusb_dev
1519 * Determine the bConfigurationValue of the currently active configuration.
1521 * You could formulate your own control request to obtain this information,
1522 * but this function has the advantage that it may be able to retrieve the
1523 * information from operating system caches (no I/O involved).
1525 * If the OS does not cache this information, then this function will block
1526 * while a control transfer is submitted to retrieve the information.
1528 * This function will return a value of 0 in the <tt>config</tt> output
1529 * parameter if the device is in unconfigured state.
1531 * \param dev_handle a device handle
1532 * \param config output location for the bConfigurationValue of the active
1533 * configuration (only valid for return code 0)
1534 * \returns 0 on success
1535 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1536 * \returns another LIBUSB_ERROR code on other failure
1538 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev_handle,
1541 int r = LIBUSB_ERROR_NOT_SUPPORTED;
1543 struct libusb_context *ctx = HANDLE_CTX(dev_handle);
1546 if (usbi_backend.get_configuration)
1547 r = usbi_backend.get_configuration(dev_handle, &tmp);
1549 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1550 usbi_dbg(ctx, "falling back to control message");
1551 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
1552 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1555 } else if (r == 0) {
1556 usbi_err(ctx, "zero bytes returned in ctrl transfer?");
1557 r = LIBUSB_ERROR_IO;
1559 usbi_dbg(ctx, "control failed, error %d", r);
1564 usbi_dbg(ctx, "active config %u", tmp);
1571 /** \ingroup libusb_dev
1572 * Set the active configuration for a device.
1574 * The operating system may or may not have already set an active
1575 * configuration on the device. It is up to your application to ensure the
1576 * correct configuration is selected before you attempt to claim interfaces
1577 * and perform other operations.
1579 * If you call this function on a device already configured with the selected
1580 * configuration, then this function will act as a lightweight device reset:
1581 * it will issue a SET_CONFIGURATION request using the current configuration,
1582 * causing most USB-related device state to be reset (altsetting reset to zero,
1583 * endpoint halts cleared, toggles reset).
1585 * Not all backends support setting the configuration from user space, which
1586 * will be indicated by the return code LIBUSB_ERROR_NOT_SUPPORTED. As this
1587 * suggests that the platform is handling the device configuration itself,
1588 * this error should generally be safe to ignore.
1590 * You cannot change/reset configuration if your application has claimed
1591 * interfaces. It is advised to set the desired configuration before claiming
1594 * Alternatively you can call libusb_release_interface() first. Note if you
1595 * do things this way you must ensure that auto_detach_kernel_driver for
1596 * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
1597 * release the interface(s).
1599 * You cannot change/reset configuration if other applications or drivers have
1600 * claimed interfaces.
1602 * A configuration value of -1 will put the device in unconfigured state.
1603 * The USB specifications state that a configuration value of 0 does this,
1604 * however buggy devices exist which actually have a configuration 0.
1606 * You should always use this function rather than formulating your own
1607 * SET_CONFIGURATION control request. This is because the underlying operating
1608 * system needs to know when such changes happen.
1610 * This is a blocking function.
1612 * \param dev_handle a device handle
1613 * \param configuration the bConfigurationValue of the configuration you
1614 * wish to activate, or -1 if you wish to put the device in an unconfigured
1616 * \returns 0 on success
1617 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1618 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1619 * \returns LIBUSB_ERROR_NOT_SUPPORTED if setting or changing the configuration
1620 * is not supported by the backend
1621 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1622 * \returns another LIBUSB_ERROR code on other failure
1623 * \see libusb_set_auto_detach_kernel_driver()
1625 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev_handle,
1628 usbi_dbg(HANDLE_CTX(dev_handle), "configuration %d", configuration);
1629 if (configuration < -1 || configuration > (int)UINT8_MAX)
1630 return LIBUSB_ERROR_INVALID_PARAM;
1631 return usbi_backend.set_configuration(dev_handle, configuration);
1634 /** \ingroup libusb_dev
1635 * Claim an interface on a given device handle. You must claim the interface
1636 * you wish to use before you can perform I/O on any of its endpoints.
1638 * It is legal to attempt to claim an already-claimed interface, in which
1639 * case libusb just returns 0 without doing anything.
1641 * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
1642 * will be detached if necessary, on failure the detach error is returned.
1644 * Claiming of interfaces is a purely logical operation; it does not cause
1645 * any requests to be sent over the bus. Interface claiming is used to
1646 * instruct the underlying operating system that your application wishes
1647 * to take ownership of the interface.
1649 * This is a non-blocking function.
1651 * \param dev_handle a device handle
1652 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1654 * \returns 0 on success
1655 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1656 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1658 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1659 * \returns a LIBUSB_ERROR code on other failure
1660 * \see libusb_set_auto_detach_kernel_driver()
1662 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev_handle,
1663 int interface_number)
1667 usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
1668 if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
1669 return LIBUSB_ERROR_INVALID_PARAM;
1671 if (!usbi_atomic_load(&dev_handle->dev->attached))
1672 return LIBUSB_ERROR_NO_DEVICE;
1674 usbi_mutex_lock(&dev_handle->lock);
1675 if (dev_handle->claimed_interfaces & (1U << interface_number))
1678 r = usbi_backend.claim_interface(dev_handle, (uint8_t)interface_number);
1680 dev_handle->claimed_interfaces |= 1U << interface_number;
1683 usbi_mutex_unlock(&dev_handle->lock);
1687 /** \ingroup libusb_dev
1688 * Release an interface previously claimed with libusb_claim_interface(). You
1689 * should release all claimed interfaces before closing a device handle.
1691 * This is a blocking function. A SET_INTERFACE control request will be sent
1692 * to the device, resetting interface state to the first alternate setting.
1694 * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
1695 * driver will be re-attached after releasing the interface.
1697 * \param dev_handle a device handle
1698 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1699 * previously-claimed interface
1700 * \returns 0 on success
1701 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1702 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1703 * \returns another LIBUSB_ERROR code on other failure
1704 * \see libusb_set_auto_detach_kernel_driver()
1706 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev_handle,
1707 int interface_number)
1711 usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
1712 if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
1713 return LIBUSB_ERROR_INVALID_PARAM;
1715 usbi_mutex_lock(&dev_handle->lock);
1716 if (!(dev_handle->claimed_interfaces & (1U << interface_number))) {
1717 r = LIBUSB_ERROR_NOT_FOUND;
1721 r = usbi_backend.release_interface(dev_handle, (uint8_t)interface_number);
1723 dev_handle->claimed_interfaces &= ~(1U << interface_number);
1726 usbi_mutex_unlock(&dev_handle->lock);
1730 /** \ingroup libusb_dev
1731 * Activate an alternate setting for an interface. The interface must have
1732 * been previously claimed with libusb_claim_interface().
1734 * You should always use this function rather than formulating your own
1735 * SET_INTERFACE control request. This is because the underlying operating
1736 * system needs to know when such changes happen.
1738 * This is a blocking function.
1740 * \param dev_handle a device handle
1741 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1742 * previously-claimed interface
1743 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1744 * setting to activate
1745 * \returns 0 on success
1746 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1747 * requested alternate setting does not exist
1748 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1749 * \returns another LIBUSB_ERROR code on other failure
1751 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
1752 int interface_number, int alternate_setting)
1754 usbi_dbg(HANDLE_CTX(dev_handle), "interface %d altsetting %d",
1755 interface_number, alternate_setting);
1756 if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
1757 return LIBUSB_ERROR_INVALID_PARAM;
1758 if (alternate_setting < 0 || alternate_setting > (int)UINT8_MAX)
1759 return LIBUSB_ERROR_INVALID_PARAM;
1761 if (!usbi_atomic_load(&dev_handle->dev->attached)) {
1762 usbi_mutex_unlock(&dev_handle->lock);
1763 return LIBUSB_ERROR_NO_DEVICE;
1766 usbi_mutex_lock(&dev_handle->lock);
1767 if (!(dev_handle->claimed_interfaces & (1U << interface_number))) {
1768 usbi_mutex_unlock(&dev_handle->lock);
1769 return LIBUSB_ERROR_NOT_FOUND;
1771 usbi_mutex_unlock(&dev_handle->lock);
1773 return usbi_backend.set_interface_altsetting(dev_handle,
1774 (uint8_t)interface_number, (uint8_t)alternate_setting);
1777 /** \ingroup libusb_dev
1778 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1779 * are unable to receive or transmit data until the halt condition is stalled.
1781 * You should cancel all pending transfers before attempting to clear the halt
1784 * This is a blocking function.
1786 * \param dev_handle a device handle
1787 * \param endpoint the endpoint to clear halt status
1788 * \returns 0 on success
1789 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1790 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1791 * \returns another LIBUSB_ERROR code on other failure
1793 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev_handle,
1794 unsigned char endpoint)
1796 usbi_dbg(HANDLE_CTX(dev_handle), "endpoint 0x%x", endpoint);
1797 if (!usbi_atomic_load(&dev_handle->dev->attached))
1798 return LIBUSB_ERROR_NO_DEVICE;
1800 return usbi_backend.clear_halt(dev_handle, endpoint);
1803 /** \ingroup libusb_dev
1804 * Perform a USB port reset to reinitialize a device. The system will attempt
1805 * to restore the previous configuration and alternate settings after the
1806 * reset has completed.
1808 * If the reset fails, the descriptors change, or the previous state cannot be
1809 * restored, the device will appear to be disconnected and reconnected. This
1810 * means that the device handle is no longer valid (you should close it) and
1811 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1812 * when this is the case.
1814 * This is a blocking function which usually incurs a noticeable delay.
1816 * \param dev_handle a handle of the device to reset
1817 * \returns 0 on success
1818 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1819 * device has been disconnected
1820 * \returns another LIBUSB_ERROR code on other failure
1822 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev_handle)
1824 usbi_dbg(HANDLE_CTX(dev_handle), " ");
1825 if (!usbi_atomic_load(&dev_handle->dev->attached))
1826 return LIBUSB_ERROR_NO_DEVICE;
1828 if (usbi_backend.reset_device)
1829 return usbi_backend.reset_device(dev_handle);
1831 return LIBUSB_ERROR_NOT_SUPPORTED;
1834 /** \ingroup libusb_asyncio
1835 * Allocate up to num_streams usb bulk streams on the specified endpoints. This
1836 * function takes an array of endpoints rather then a single endpoint because
1837 * some protocols require that endpoints are setup with similar stream ids.
1838 * All endpoints passed in must belong to the same interface.
1840 * Note this function may return less streams then requested. Also note that the
1841 * same number of streams are allocated for each endpoint in the endpoint array.
1843 * Stream id 0 is reserved, and should not be used to communicate with devices.
1844 * If libusb_alloc_streams() returns with a value of N, you may use stream ids
1847 * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1849 * \param dev_handle a device handle
1850 * \param num_streams number of streams to try to allocate
1851 * \param endpoints array of endpoints to allocate streams on
1852 * \param num_endpoints length of the endpoints array
1853 * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
1855 int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev_handle,
1856 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1858 usbi_dbg(HANDLE_CTX(dev_handle), "streams %u eps %d", (unsigned)num_streams, num_endpoints);
1860 if (!num_streams || !endpoints || num_endpoints <= 0)
1861 return LIBUSB_ERROR_INVALID_PARAM;
1863 if (!usbi_atomic_load(&dev_handle->dev->attached))
1864 return LIBUSB_ERROR_NO_DEVICE;
1866 if (usbi_backend.alloc_streams)
1867 return usbi_backend.alloc_streams(dev_handle, num_streams, endpoints,
1870 return LIBUSB_ERROR_NOT_SUPPORTED;
1873 /** \ingroup libusb_asyncio
1874 * Free usb bulk streams allocated with libusb_alloc_streams().
1876 * Note streams are automatically free-ed when releasing an interface.
1878 * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1880 * \param dev_handle a device handle
1881 * \param endpoints array of endpoints to free streams on
1882 * \param num_endpoints length of the endpoints array
1883 * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1885 int API_EXPORTED libusb_free_streams(libusb_device_handle *dev_handle,
1886 unsigned char *endpoints, int num_endpoints)
1888 usbi_dbg(HANDLE_CTX(dev_handle), "eps %d", num_endpoints);
1890 if (!endpoints || num_endpoints <= 0)
1891 return LIBUSB_ERROR_INVALID_PARAM;
1893 if (!usbi_atomic_load(&dev_handle->dev->attached))
1894 return LIBUSB_ERROR_NO_DEVICE;
1896 if (usbi_backend.free_streams)
1897 return usbi_backend.free_streams(dev_handle, endpoints,
1900 return LIBUSB_ERROR_NOT_SUPPORTED;
1903 /** \ingroup libusb_asyncio
1904 * Attempts to allocate a block of persistent DMA memory suitable for transfers
1905 * against the given device. If successful, will return a block of memory
1906 * that is suitable for use as "buffer" in \ref libusb_transfer against this
1907 * device. Using this memory instead of regular memory means that the host
1908 * controller can use DMA directly into the buffer to increase performance, and
1909 * also that transfers can no longer fail due to kernel memory fragmentation.
1911 * Note that this means you should not modify this memory (or even data on
1912 * the same cache lines) when a transfer is in progress, although it is legal
1913 * to have several transfers going on within the same memory block.
1915 * Will return NULL on failure. Many systems do not support such zero-copy
1916 * and will always return NULL. Memory allocated with this function must be
1917 * freed with \ref libusb_dev_mem_free. Specifically, this means that the
1918 * flag \ref LIBUSB_TRANSFER_FREE_BUFFER cannot be used to free memory allocated
1919 * with this function.
1921 * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
1923 * \param dev_handle a device handle
1924 * \param length size of desired data buffer
1925 * \returns a pointer to the newly allocated memory, or NULL on failure
1928 unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle,
1931 if (!usbi_atomic_load(&dev_handle->dev->attached))
1934 if (usbi_backend.dev_mem_alloc)
1935 return usbi_backend.dev_mem_alloc(dev_handle, length);
1940 /** \ingroup libusb_asyncio
1941 * Free device memory allocated with libusb_dev_mem_alloc().
1943 * \param dev_handle a device handle
1944 * \param buffer pointer to the previously allocated memory
1945 * \param length size of previously allocated memory
1946 * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1948 int API_EXPORTED libusb_dev_mem_free(libusb_device_handle *dev_handle,
1949 unsigned char *buffer, size_t length)
1951 if (usbi_backend.dev_mem_free)
1952 return usbi_backend.dev_mem_free(dev_handle, buffer, length);
1954 return LIBUSB_ERROR_NOT_SUPPORTED;
1957 /** \ingroup libusb_dev
1958 * Determine if a kernel driver is active on an interface. If a kernel driver
1959 * is active, you cannot claim the interface, and libusb will be unable to
1962 * This functionality is not available on Windows.
1964 * \param dev_handle a device handle
1965 * \param interface_number the interface to check
1966 * \returns 0 if no kernel driver is active
1967 * \returns 1 if a kernel driver is active
1968 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1969 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1971 * \returns another LIBUSB_ERROR code on other failure
1972 * \see libusb_detach_kernel_driver()
1974 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev_handle,
1975 int interface_number)
1977 usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
1979 if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
1980 return LIBUSB_ERROR_INVALID_PARAM;
1982 if (!usbi_atomic_load(&dev_handle->dev->attached))
1983 return LIBUSB_ERROR_NO_DEVICE;
1985 if (usbi_backend.kernel_driver_active)
1986 return usbi_backend.kernel_driver_active(dev_handle, (uint8_t)interface_number);
1988 return LIBUSB_ERROR_NOT_SUPPORTED;
1991 /** \ingroup libusb_dev
1992 * Detach a kernel driver from an interface. If successful, you will then be
1993 * able to claim the interface and perform I/O.
1995 * This functionality is not available on Windows.
1997 * Note that libusb itself also talks to the device through a special kernel
1998 * driver, if this driver is already attached to the device, this call will
1999 * not detach it and return LIBUSB_ERROR_NOT_FOUND.
2001 * \param dev_handle a device handle
2002 * \param interface_number the interface to detach the driver from
2003 * \returns 0 on success
2004 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
2005 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
2006 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
2007 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
2009 * \returns another LIBUSB_ERROR code on other failure
2010 * \see libusb_kernel_driver_active()
2012 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
2013 int interface_number)
2015 usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
2017 if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
2018 return LIBUSB_ERROR_INVALID_PARAM;
2020 if (!usbi_atomic_load(&dev_handle->dev->attached))
2021 return LIBUSB_ERROR_NO_DEVICE;
2023 if (usbi_backend.detach_kernel_driver)
2024 return usbi_backend.detach_kernel_driver(dev_handle, (uint8_t)interface_number);
2026 return LIBUSB_ERROR_NOT_SUPPORTED;
2029 /** \ingroup libusb_dev
2030 * Re-attach an interface's kernel driver, which was previously detached
2031 * using libusb_detach_kernel_driver().
2033 * This functionality is not available on Windows.
2035 * \param dev_handle a device handle
2036 * \param interface_number the interface to attach the driver from
2037 * \returns 0 on success
2038 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
2039 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
2040 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
2041 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
2043 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
2044 * interface is claimed by a program or driver
2045 * \returns another LIBUSB_ERROR code on other failure
2046 * \see libusb_kernel_driver_active()
2048 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
2049 int interface_number)
2051 usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
2053 if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
2054 return LIBUSB_ERROR_INVALID_PARAM;
2056 if (!usbi_atomic_load(&dev_handle->dev->attached))
2057 return LIBUSB_ERROR_NO_DEVICE;
2059 if (usbi_backend.attach_kernel_driver)
2060 return usbi_backend.attach_kernel_driver(dev_handle, (uint8_t)interface_number);
2062 return LIBUSB_ERROR_NOT_SUPPORTED;
2065 /** \ingroup libusb_dev
2066 * Enable/disable libusb's automatic kernel driver detachment. When this is
2067 * enabled libusb will automatically detach the kernel driver on an interface
2068 * when claiming the interface, and attach it when releasing the interface.
2070 * Automatic kernel driver detachment is disabled on newly opened device
2071 * handles by default.
2073 * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
2074 * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
2075 * continue as if this function was never called.
2077 * \param dev_handle a device handle
2078 * \param enable whether to enable or disable auto kernel driver detachment
2080 * \returns LIBUSB_SUCCESS on success
2081 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
2083 * \see libusb_claim_interface()
2084 * \see libusb_release_interface()
2085 * \see libusb_set_configuration()
2087 int API_EXPORTED libusb_set_auto_detach_kernel_driver(
2088 libusb_device_handle *dev_handle, int enable)
2090 if (!(usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
2091 return LIBUSB_ERROR_NOT_SUPPORTED;
2093 dev_handle->auto_detach_kernel_driver = enable;
2094 return LIBUSB_SUCCESS;
2097 /** \ingroup libusb_lib
2098 * \deprecated Use libusb_set_option() instead using the
2099 * \ref LIBUSB_OPTION_LOG_LEVEL option.
2101 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
2103 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2104 ctx = usbi_get_context(ctx);
2105 if (!ctx->debug_fixed) {
2106 level = CLAMP(level, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG);
2107 ctx->debug = (enum libusb_log_level)level;
2115 /** \ingroup libusb_lib
2118 * libusb will redirect its log messages to the provided callback function.
2119 * libusb supports redirection of per context and global log messages.
2120 * Log messages sent to the context will be sent to the global log handler too.
2122 * If libusb is compiled without message logging or USE_SYSTEM_LOGGING_FACILITY
2123 * is defined then global callback function will never be called.
2124 * If ENABLE_DEBUG_LOGGING is defined then per context callback function will
2127 * Since version 1.0.23, \ref LIBUSB_API_VERSION >= 0x01000107
2129 * \param ctx context on which to assign log handler, or NULL for the default
2130 * context. Parameter ignored if only LIBUSB_LOG_CB_GLOBAL mode is requested.
2131 * \param cb pointer to the callback function, or NULL to stop log
2132 * messages redirection
2133 * \param mode mode of callback function operation. Several modes can be
2134 * selected for a single callback function, see \ref libusb_log_cb_mode for
2136 * \see libusb_log_cb, libusb_log_cb_mode
2138 void API_EXPORTED libusb_set_log_cb(libusb_context *ctx, libusb_log_cb cb,
2141 #if defined(ENABLE_LOGGING) && (!defined(ENABLE_DEBUG_LOGGING) || !defined(USE_SYSTEM_LOGGING_FACILITY))
2142 #if !defined(USE_SYSTEM_LOGGING_FACILITY)
2143 if (mode & LIBUSB_LOG_CB_GLOBAL)
2146 #if !defined(ENABLE_DEBUG_LOGGING)
2147 if (mode & LIBUSB_LOG_CB_CONTEXT) {
2148 ctx = usbi_get_context(ctx);
2149 ctx->log_handler = cb;
2161 /** \ingroup libusb_lib
2162 * Set an option in the library.
2164 * Use this function to configure a specific option within the library.
2166 * Some options require one or more arguments to be provided. Consult each
2167 * option's documentation for specific requirements.
2169 * If the context ctx is NULL, the option will be added to a list of default
2170 * options that will be applied to all subsequently created contexts.
2172 * Since version 1.0.22, \ref LIBUSB_API_VERSION >= 0x01000106
2174 * \param ctx context on which to operate
2175 * \param option which option to set
2176 * \param ... any required arguments for the specified option
2178 * \returns LIBUSB_SUCCESS on success
2179 * \returns LIBUSB_ERROR_INVALID_PARAM if the option or arguments are invalid
2180 * \returns LIBUSB_ERROR_NOT_SUPPORTED if the option is valid but not supported
2182 * \returns LIBUSB_ERROR_NOT_FOUND if LIBUSB_OPTION_USE_USBDK is valid on this platform but UsbDk is not available
2184 int API_EXPORTED libusb_set_option(libusb_context *ctx,
2185 enum libusb_option option, ...)
2187 int arg = 0, r = LIBUSB_SUCCESS;
2190 va_start(ap, option);
2191 if (LIBUSB_OPTION_LOG_LEVEL == option) {
2192 arg = va_arg(ap, int);
2193 if (arg < LIBUSB_LOG_LEVEL_NONE || arg > LIBUSB_LOG_LEVEL_DEBUG) {
2194 r = LIBUSB_ERROR_INVALID_PARAM;
2199 if (LIBUSB_SUCCESS != r) {
2203 if (option >= LIBUSB_OPTION_MAX) {
2204 return LIBUSB_ERROR_INVALID_PARAM;
2208 usbi_mutex_static_lock(&default_context_lock);
2209 default_context_options[option].is_set = 1;
2210 if (LIBUSB_OPTION_LOG_LEVEL == option) {
2211 default_context_options[option].arg.ival = arg;
2213 usbi_mutex_static_unlock(&default_context_lock);
2216 ctx = usbi_get_context(ctx);
2218 return LIBUSB_SUCCESS;
2222 case LIBUSB_OPTION_LOG_LEVEL:
2223 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2224 if (!ctx->debug_fixed)
2225 ctx->debug = (enum libusb_log_level)arg;
2229 /* Handle all backend-specific options here */
2230 case LIBUSB_OPTION_USE_USBDK:
2231 case LIBUSB_OPTION_NO_DEVICE_DISCOVERY:
2232 if (usbi_backend.set_option)
2233 return usbi_backend.set_option(ctx, option, ap);
2235 return LIBUSB_ERROR_NOT_SUPPORTED;
2238 case LIBUSB_OPTION_MAX:
2240 return LIBUSB_ERROR_INVALID_PARAM;
2243 return LIBUSB_SUCCESS;;
2246 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2247 /* returns the log level as defined in the LIBUSB_DEBUG environment variable.
2248 * if LIBUSB_DEBUG is not present or not a number, returns LIBUSB_LOG_LEVEL_NONE.
2249 * value is clamped to ensure it is within the valid range of possibilities.
2251 static enum libusb_log_level get_env_debug_level(void)
2253 const char *dbg = getenv("LIBUSB_DEBUG");
2254 enum libusb_log_level level;
2256 int dbg_level = atoi(dbg);
2257 dbg_level = CLAMP(dbg_level, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG);
2258 level = (enum libusb_log_level)dbg_level;
2260 level = LIBUSB_LOG_LEVEL_NONE;
2266 /** \ingroup libusb_lib
2267 * Initialize libusb. This function must be called before calling any other
2270 * If you do not provide an output location for a context pointer, a default
2271 * context will be created. If there was already a default context, it will
2272 * be reused (and nothing will be initialized/reinitialized).
2274 * \param ctx Optional output location for context pointer.
2275 * Only valid on return code 0.
2276 * \returns 0 on success, or a LIBUSB_ERROR code on failure
2277 * \see libusb_contexts
2279 int API_EXPORTED libusb_init(libusb_context **ctx)
2281 size_t priv_size = usbi_backend.context_priv_size;
2282 struct libusb_context *_ctx;
2285 usbi_mutex_static_lock(&default_context_lock);
2287 if (!ctx && usbi_default_context) {
2288 usbi_dbg(usbi_default_context, "reusing default context");
2289 default_context_refcnt++;
2290 usbi_mutex_static_unlock(&default_context_lock);
2294 /* check for first init */
2295 if (!active_contexts_list.next) {
2296 list_init(&active_contexts_list);
2297 usbi_get_monotonic_time(×tamp_origin);
2300 _ctx = calloc(1, PTR_ALIGN(sizeof(*_ctx)) + priv_size);
2302 usbi_mutex_static_unlock(&default_context_lock);
2303 return LIBUSB_ERROR_NO_MEM;
2306 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2307 if (NULL == ctx && default_context_options[LIBUSB_OPTION_LOG_LEVEL].is_set) {
2308 _ctx->debug = default_context_options[LIBUSB_OPTION_LOG_LEVEL].arg.ival;
2310 _ctx->debug = get_env_debug_level();
2312 if (_ctx->debug != LIBUSB_LOG_LEVEL_NONE)
2313 _ctx->debug_fixed = 1;
2316 usbi_mutex_init(&_ctx->usb_devs_lock);
2317 usbi_mutex_init(&_ctx->open_devs_lock);
2318 list_init(&_ctx->usb_devs);
2319 list_init(&_ctx->open_devs);
2321 /* apply default options to all new contexts */
2322 for (enum libusb_option option = 0 ; option < LIBUSB_OPTION_MAX ; option++) {
2323 if (LIBUSB_OPTION_LOG_LEVEL == option || !default_context_options[option].is_set) {
2326 r = libusb_set_option(_ctx, option);
2327 if (LIBUSB_SUCCESS != r)
2331 /* default context must be initialized before calling usbi_dbg */
2333 usbi_default_context = _ctx;
2334 default_context_refcnt = 1;
2335 usbi_dbg(usbi_default_context, "created default context");
2338 usbi_dbg(_ctx, "libusb v%u.%u.%u.%u%s", libusb_version_internal.major, libusb_version_internal.minor,
2339 libusb_version_internal.micro, libusb_version_internal.nano, libusb_version_internal.rc);
2341 r = usbi_io_init(_ctx);
2345 usbi_mutex_static_lock(&active_contexts_lock);
2346 list_add(&_ctx->list, &active_contexts_list);
2347 usbi_mutex_static_unlock(&active_contexts_lock);
2349 if (usbi_backend.init) {
2350 r = usbi_backend.init(_ctx);
2355 /* Initialize hotplug after the initial enumeration is done. */
2356 usbi_hotplug_init(_ctx);
2361 usbi_mutex_static_unlock(&default_context_lock);
2366 usbi_mutex_static_lock(&active_contexts_lock);
2367 list_del(&_ctx->list);
2368 usbi_mutex_static_unlock(&active_contexts_lock);
2370 usbi_hotplug_exit(_ctx);
2375 /* clear default context that was not fully initialized */
2376 usbi_default_context = NULL;
2377 default_context_refcnt = 0;
2380 usbi_mutex_destroy(&_ctx->open_devs_lock);
2381 usbi_mutex_destroy(&_ctx->usb_devs_lock);
2385 usbi_mutex_static_unlock(&default_context_lock);
2390 /** \ingroup libusb_lib
2391 * Deinitialize libusb. Should be called after closing all open devices and
2392 * before your application terminates.
2393 * \param ctx the context to deinitialize, or NULL for the default context
2395 void API_EXPORTED libusb_exit(libusb_context *ctx)
2397 struct libusb_context *_ctx;
2398 struct libusb_device *dev;
2400 usbi_mutex_static_lock(&default_context_lock);
2402 /* if working with default context, only actually do the deinitialization
2403 * if we're the last user */
2405 if (!usbi_default_context) {
2406 usbi_dbg(ctx, "no default context, not initialized?");
2407 usbi_mutex_static_unlock(&default_context_lock);
2411 if (--default_context_refcnt > 0) {
2412 usbi_dbg(ctx, "not destroying default context");
2413 usbi_mutex_static_unlock(&default_context_lock);
2417 usbi_dbg(ctx, "destroying default context");
2418 _ctx = usbi_default_context;
2424 usbi_mutex_static_lock(&active_contexts_lock);
2425 list_del(&_ctx->list);
2426 usbi_mutex_static_unlock(&active_contexts_lock);
2428 if (usbi_backend.exit)
2429 usbi_backend.exit(_ctx);
2432 usbi_default_context = NULL;
2434 usbi_mutex_static_unlock(&default_context_lock);
2436 /* Don't bother with locking after this point because unless there is
2437 * an application bug, nobody will be accessing the context. */
2439 usbi_hotplug_exit(_ctx);
2442 for_each_device(_ctx, dev) {
2443 usbi_warn(_ctx, "device %d.%d still referenced",
2444 dev->bus_number, dev->device_address);
2445 DEVICE_CTX(dev) = NULL;
2448 if (!list_empty(&_ctx->open_devs))
2449 usbi_warn(_ctx, "application left some devices open");
2451 usbi_mutex_destroy(&_ctx->open_devs_lock);
2452 usbi_mutex_destroy(&_ctx->usb_devs_lock);
2457 /** \ingroup libusb_misc
2458 * Check at runtime if the loaded library has a given capability.
2459 * This call should be performed after \ref libusb_init(), to ensure the
2460 * backend has updated its capability set.
2462 * \param capability the \ref libusb_capability to check for
2463 * \returns nonzero if the running library has the capability, 0 otherwise
2465 int API_EXPORTED libusb_has_capability(uint32_t capability)
2467 switch (capability) {
2468 case LIBUSB_CAP_HAS_CAPABILITY:
2470 case LIBUSB_CAP_HAS_HOTPLUG:
2471 return !(usbi_backend.get_device_list);
2472 case LIBUSB_CAP_HAS_HID_ACCESS:
2473 return (usbi_backend.caps & USBI_CAP_HAS_HID_ACCESS);
2474 case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
2475 return (usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
2480 #ifdef ENABLE_LOGGING
2482 /* this is defined in libusbi.h if needed */
2483 #ifdef LIBUSB_PRINTF_WIN32
2485 * Prior to VS2015, Microsoft did not provide the snprintf() function and
2486 * provided a vsnprintf() that did not guarantee NUL-terminated output.
2487 * Microsoft did provide a _snprintf() function, but again it did not
2488 * guarantee NULL-terminated output.
2490 * The below implementations guarantee NUL-terminated output and are
2494 int usbi_snprintf(char *str, size_t size, const char *format, ...)
2499 va_start(args, format);
2500 ret = usbi_vsnprintf(str, size, format, args);
2506 int usbi_vsnprintf(char *str, size_t size, const char *format, va_list args)
2510 ret = _vsnprintf(str, size, format, args);
2511 if (ret < 0 || ret == (int)size) {
2512 /* Output is truncated, ensure buffer is NUL-terminated and
2513 * determine how many characters would have been written. */
2514 str[size - 1] = '\0';
2516 ret = _vsnprintf(NULL, 0, format, args);
2521 #endif /* LIBUSB_PRINTF_WIN32 */
2523 static void log_str(enum libusb_log_level level, const char *str)
2525 #if defined(USE_SYSTEM_LOGGING_FACILITY)
2526 #if defined(__ANDROID__)
2529 case LIBUSB_LOG_LEVEL_NONE: return; /* Impossible, but keeps compiler happy */
2530 case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
2531 case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
2532 case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
2533 case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
2534 default: priority = ANDROID_LOG_UNKNOWN;
2536 __android_log_write(priority, "libusb", str);
2537 #elif defined(_WIN32)
2539 OutputDebugStringA(str);
2540 #elif defined(HAVE_SYSLOG)
2543 case LIBUSB_LOG_LEVEL_NONE: return; /* Impossible, but keeps compiler happy */
2544 case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
2545 case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
2546 case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
2547 case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
2548 default: syslog_level = LOG_INFO;
2550 syslog(syslog_level, "%s", str);
2551 #else /* All of gcc, Clang, Xcode seem to use #warning */
2552 #warning System logging is not supported on this platform. Logging to stderr will be used instead.
2557 /* Global log handler */
2559 log_handler(NULL, level, str);
2562 #endif /* USE_SYSTEM_LOGGING_FACILITY */
2565 static void log_v(struct libusb_context *ctx, enum libusb_log_level level,
2566 const char *function, const char *format, va_list args)
2569 char buf[USBI_MAX_LOG_LEN];
2570 int global_debug, header_len, text_len;
2571 static int has_debug_header_been_displayed = 0;
2573 #ifdef ENABLE_DEBUG_LOGGING
2577 enum libusb_log_level ctx_level;
2579 ctx = usbi_get_context(ctx);
2581 ctx_level = ctx->debug;
2583 ctx_level = get_env_debug_level();
2585 if (ctx_level < level)
2588 global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
2592 case LIBUSB_LOG_LEVEL_NONE: /* Impossible, but keeps compiler happy */
2594 case LIBUSB_LOG_LEVEL_ERROR:
2597 case LIBUSB_LOG_LEVEL_WARNING:
2600 case LIBUSB_LOG_LEVEL_INFO:
2603 case LIBUSB_LOG_LEVEL_DEBUG:
2612 struct timespec timestamp;
2614 if (!has_debug_header_been_displayed) {
2615 has_debug_header_been_displayed = 1;
2616 log_str(LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>" USBI_LOG_LINE_END);
2617 log_str(LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END);
2620 usbi_get_monotonic_time(×tamp);
2621 TIMESPEC_SUB(×tamp, ×tamp_origin, ×tamp);
2623 header_len = snprintf(buf, sizeof(buf),
2624 "[%2ld.%06ld] [%08x] libusb: %s [%s] ",
2625 (long)timestamp.tv_sec, (long)(timestamp.tv_nsec / 1000L), usbi_get_tid(), prefix, function);
2627 header_len = snprintf(buf, sizeof(buf),
2628 "libusb: %s [%s] ", prefix, function);
2631 if (header_len < 0 || header_len >= (int)sizeof(buf)) {
2632 /* Somehow snprintf() failed to write to the buffer,
2633 * remove the header so something useful is output. */
2637 text_len = vsnprintf(buf + header_len, sizeof(buf) - (size_t)header_len,
2639 if (text_len < 0 || text_len + header_len >= (int)sizeof(buf)) {
2640 /* Truncated log output. On some platforms a -1 return value means
2641 * that the output was truncated. */
2642 text_len = (int)sizeof(buf) - header_len;
2644 if (header_len + text_len + (int)sizeof(USBI_LOG_LINE_END) >= (int)sizeof(buf)) {
2645 /* Need to truncate the text slightly to fit on the terminator. */
2646 text_len -= (header_len + text_len + (int)sizeof(USBI_LOG_LINE_END)) - (int)sizeof(buf);
2648 strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
2650 log_str(level, buf);
2652 /* Per-context log handler */
2653 #ifndef ENABLE_DEBUG_LOGGING
2654 if (ctx && ctx->log_handler)
2655 ctx->log_handler(ctx, level, buf);
2659 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
2660 const char *function, const char *format, ...)
2664 va_start(args, format);
2665 log_v(ctx, level, function, format, args);
2669 #endif /* ENABLE_LOGGING */
2671 /** \ingroup libusb_misc
2672 * Returns a constant NULL-terminated string with the ASCII name of a libusb
2673 * error or transfer status code. The caller must not free() the returned
2676 * \param error_code The \ref libusb_error or libusb_transfer_status code to
2677 * return the name of.
2678 * \returns The error name, or the string **UNKNOWN** if the value of
2679 * error_code is not a known error / status code.
2681 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
2683 switch (error_code) {
2684 case LIBUSB_ERROR_IO:
2685 return "LIBUSB_ERROR_IO";
2686 case LIBUSB_ERROR_INVALID_PARAM:
2687 return "LIBUSB_ERROR_INVALID_PARAM";
2688 case LIBUSB_ERROR_ACCESS:
2689 return "LIBUSB_ERROR_ACCESS";
2690 case LIBUSB_ERROR_NO_DEVICE:
2691 return "LIBUSB_ERROR_NO_DEVICE";
2692 case LIBUSB_ERROR_NOT_FOUND:
2693 return "LIBUSB_ERROR_NOT_FOUND";
2694 case LIBUSB_ERROR_BUSY:
2695 return "LIBUSB_ERROR_BUSY";
2696 case LIBUSB_ERROR_TIMEOUT:
2697 return "LIBUSB_ERROR_TIMEOUT";
2698 case LIBUSB_ERROR_OVERFLOW:
2699 return "LIBUSB_ERROR_OVERFLOW";
2700 case LIBUSB_ERROR_PIPE:
2701 return "LIBUSB_ERROR_PIPE";
2702 case LIBUSB_ERROR_INTERRUPTED:
2703 return "LIBUSB_ERROR_INTERRUPTED";
2704 case LIBUSB_ERROR_NO_MEM:
2705 return "LIBUSB_ERROR_NO_MEM";
2706 case LIBUSB_ERROR_NOT_SUPPORTED:
2707 return "LIBUSB_ERROR_NOT_SUPPORTED";
2708 case LIBUSB_ERROR_OTHER:
2709 return "LIBUSB_ERROR_OTHER";
2711 case LIBUSB_TRANSFER_ERROR:
2712 return "LIBUSB_TRANSFER_ERROR";
2713 case LIBUSB_TRANSFER_TIMED_OUT:
2714 return "LIBUSB_TRANSFER_TIMED_OUT";
2715 case LIBUSB_TRANSFER_CANCELLED:
2716 return "LIBUSB_TRANSFER_CANCELLED";
2717 case LIBUSB_TRANSFER_STALL:
2718 return "LIBUSB_TRANSFER_STALL";
2719 case LIBUSB_TRANSFER_NO_DEVICE:
2720 return "LIBUSB_TRANSFER_NO_DEVICE";
2721 case LIBUSB_TRANSFER_OVERFLOW:
2722 return "LIBUSB_TRANSFER_OVERFLOW";
2725 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
2727 return "**UNKNOWN**";
2731 /** \ingroup libusb_misc
2732 * Returns a pointer to const struct libusb_version with the version
2733 * (major, minor, micro, nano and rc) of the running library.
2736 const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
2738 return &libusb_version_internal;