1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
3 * add some functions for no-rooted Android
4 * add optimaization when compiling with gcc
5 * Copyright © 2014-2017 saki <t_saki@serenegiant.com>
7 * Core functions for libusb
8 * Copyright © 2012-2013 Nathan Hjelm <hjelmn@cs.unm.edu>
9 * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
10 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #define LOG_TAG "libusb/core"
30 #if 1 // デバッグ情報を出さない時1
32 #define LOG_NDEBUG // LOGV/LOGD/MARKを出力しない時
34 #undef USE_LOGALL // 指定したLOGxだけを出力
39 #define GET_RAW_DESCRIPTOR
43 #include <assert.h> // XXX add assert for debugging
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
53 #ifdef HAVE_SYS_TIME_H
61 #include <android/log.h>
67 #if defined(OS_ANDROID) // XXX for non rooted android device
68 const struct usbi_os_backend * const usbi_backend = &android_usbfs_backend;
69 #elif defined(OS_LINUX)
70 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
71 #elif defined(OS_DARWIN)
72 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
73 #elif defined(OS_OPENBSD)
74 const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
75 #elif defined(OS_NETBSD)
76 const struct usbi_os_backend * const usbi_backend = &netbsd_backend;
77 #elif defined(OS_WINDOWS)
78 const struct usbi_os_backend * const usbi_backend = &windows_backend;
79 #elif defined(OS_WINCE)
80 const struct usbi_os_backend * const usbi_backend = &wince_backend;
82 #error "Unsupported OS"
85 struct libusb_context *usbi_default_context = NULL;
86 static const struct libusb_version libusb_version_internal =
87 { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
88 LIBUSB_RC, "http://libusb.info" };
89 static int default_context_refcnt = 0;
90 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
91 static struct timeval timestamp_origin = { 0, 0 };
93 usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
94 struct list_head active_contexts_list;
97 int android_generate_device(struct libusb_context *ctx, struct libusb_device **dev,
98 int vid, int pid, const char *serial, int fd, int busnum, int devaddr);
102 * \mainpage libusb-1.0 API Reference
104 * \section intro Introduction
106 * libusb is an open source library that allows you to communicate with USB
107 * devices from userspace. For more info, see the
108 * <a href="http://libusb.info">libusb homepage</a>.
110 * This documentation is aimed at application developers wishing to
111 * communicate with USB peripherals from their own software. After reviewing
112 * this documentation, feedback and questions can be sent to the
113 * <a href="http://mailing-list.libusb.info">libusb-devel mailing list</a>.
115 * This documentation assumes knowledge of how to operate USB devices from
116 * a software standpoint (descriptors, configurations, interfaces, endpoints,
117 * control/bulk/interrupt/isochronous transfers, etc). Full information
118 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
119 * Specification</a> which is available for free download. You can probably
120 * find less verbose introductions by searching the web.
122 * \section features Library features
124 * - All transfer types supported (control/bulk/interrupt/isochronous)
125 * - 2 transfer interfaces:
126 * -# Synchronous (simple)
127 * -# Asynchronous (more complicated, but more powerful)
128 * - Thread safe (although the asynchronous interface means that you
129 * usually won't need to thread)
130 * - Lightweight with lean API
131 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
132 * - Hotplug support (on some platforms). See \ref hotplug.
134 * \section gettingstarted Getting Started
136 * To begin reading the API documentation, start with the Modules page which
137 * links to the different categories of libusb's functionality.
139 * One decision you will have to make is whether to use the synchronous
140 * or the asynchronous data transfer interface. The \ref io documentation
141 * provides some insight into this topic.
143 * Some example programs can be found in the libusb source distribution under
144 * the "examples" subdirectory. The libusb homepage includes a list of
145 * real-life project examples which use libusb.
147 * \section errorhandling Error handling
149 * libusb functions typically return 0 on success or a negative error code
150 * on failure. These negative error codes relate to LIBUSB_ERROR constants
151 * which are listed on the \ref misc "miscellaneous" documentation page.
153 * \section msglog Debug message logging
155 * libusb uses stderr for all logging. By default, logging is set to NONE,
156 * which means that no output will be produced. However, unless the library
157 * has been compiled with logging disabled, then any application calls to
158 * libusb_set_debug(), or the setting of the environmental variable
159 * LIBUSB_DEBUG outside of the application, can result in logging being
160 * produced. Your application should therefore not close stderr, but instead
161 * direct it to the null device if its output is undesireable.
163 * The libusb_set_debug() function can be used to enable logging of certain
164 * messages. Under standard configuration, libusb doesn't really log much
165 * so you are advised to use this function to enable all error/warning/
166 * informational messages. It will help debug problems with your software.
168 * The logged messages are unstructured. There is no one-to-one correspondence
169 * between messages being logged and success or failure return codes from
170 * libusb functions. There is no format to the messages, so you should not
171 * try to capture or parse them. They are not and will not be localized.
172 * These messages are not intended to being passed to your application user;
173 * instead, you should interpret the error codes returned from libusb functions
174 * and provide appropriate notification to the user. The messages are simply
175 * there to aid you as a programmer, and if you're confused because you're
176 * getting a strange error code from a libusb function, enabling message
177 * logging may give you a suitable explanation.
179 * The LIBUSB_DEBUG environment variable can be used to enable message logging
180 * at run-time. This environment variable should be set to a log level number,
181 * which is interpreted the same as the libusb_set_debug() parameter. When this
182 * environment variable is set, the message logging verbosity level is fixed
183 * and libusb_set_debug() effectively does nothing.
185 * libusb can be compiled without any logging functions, useful for embedded
186 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
187 * variable have no effects.
189 * libusb can also be compiled with verbose debugging messages always. When
190 * the library is compiled in this way, all messages of all verbosities are
191 * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
194 * \section remarks Other remarks
196 * libusb does have imperfections. The \ref caveats "caveats" page attempts
201 * \page caveats Caveats
203 * \section devresets Device resets
205 * The libusb_reset_device() function allows you to reset a device. If your
206 * program has to call such a function, it should obviously be aware that
207 * the reset will cause device state to change (e.g. register values may be
210 * The problem is that any other program could reset the device your program
211 * is working with, at any time. libusb does not offer a mechanism to inform
212 * you when this has happened, so if someone else resets your device it will
213 * not be clear to your own program why the device state has changed.
215 * Ultimately, this is a limitation of writing drivers in userspace.
216 * Separation from the USB stack in the underlying kernel makes it difficult
217 * for the operating system to deliver such notifications to your program.
218 * The Linux kernel USB stack allows such reset notifications to be delivered
219 * to in-kernel USB drivers, but it is not clear how such notifications could
220 * be delivered to second-class drivers that live in userspace.
222 * \section blockonly Blocking-only functionality
224 * The functionality listed below is only available through synchronous,
225 * blocking functions. There are no asynchronous/non-blocking alternatives,
226 * and no clear ways of implementing these.
228 * - Configuration activation (libusb_set_configuration())
229 * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
230 * - Releasing of interfaces (libusb_release_interface())
231 * - Clearing of halt/stall condition (libusb_clear_halt())
232 * - Device resets (libusb_reset_device())
234 * \section configsel Configuration selection and handling
236 * When libusb presents a device handle to an application, there is a chance
237 * that the corresponding device may be in unconfigured state. For devices
238 * with multiple configurations, there is also a chance that the configuration
239 * currently selected is not the one that the application wants to use.
241 * The obvious solution is to add a call to libusb_set_configuration() early
242 * on during your device initialization routines, but there are caveats to
244 * -# If the device is already in the desired configuration, calling
245 * libusb_set_configuration() using the same configuration value will cause
246 * a lightweight device reset. This may not be desirable behaviour.
247 * -# libusb will be unable to change configuration if the device is in
248 * another configuration and other programs or drivers have claimed
249 * interfaces under that configuration.
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.)
259 * One solution to some of the above problems is to consider the currently
260 * active configuration. If the configuration we want is already active, then
261 * we don't have to select any configuration:
263 cfg = libusb_get_configuration(dev);
265 libusb_set_configuration(dev, desired);
268 * This is probably suitable for most scenarios, but is inherently racy:
269 * another application or driver may change the selected configuration
270 * <em>after</em> the libusb_get_configuration() call.
272 * Even in cases where libusb_set_configuration() succeeds, consider that other
273 * applications or drivers may change configuration after your application
274 * calls libusb_set_configuration().
276 * One possible way to lock your device into a specific configuration is as
278 * -# Set the desired configuration (or use the logic above to realise that
279 * it is already in the desired configuration)
280 * -# Claim the interface that you wish to use
281 * -# Check that the currently active configuration is the one that you want
284 * The above method works because once an interface is claimed, no application
285 * or driver is able to select another configuration.
287 * \section earlycomp Early transfer completion
289 * NOTE: This section is currently Linux-centric. I am not sure if any of these
290 * considerations apply to Darwin or other platforms.
292 * When a transfer completes early (i.e. when less data is received/sent in
293 * any one packet than the transfer buffer allows for) then libusb is designed
294 * to terminate the transfer immediately, not transferring or receiving any
295 * more data unless other transfers have been queued by the user.
297 * On legacy platforms, libusb is unable to do this in all situations. After
298 * the incomplete packet occurs, "surplus" data may be transferred. For recent
299 * versions of libusb, this information is kept (the data length of the
300 * transfer is updated) and, for device-to-host transfers, any surplus data was
301 * added to the buffer. Still, this is not a nice solution because it loses the
302 * information about the end of the short packet, and the user probably wanted
303 * that surplus data to arrive in the next logical transfer.
306 * \section zlp Zero length packets
308 * - libusb is able to send a packet of zero length to an endpoint simply by
309 * submitting a transfer of zero length.
310 * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
311 * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
315 * \page contexts Contexts
317 * It is possible that libusb may be used simultaneously from two independent
318 * libraries linked into the same executable. For example, if your application
319 * has a plugin-like system which allows the user to dynamically load a range
320 * of modules into your program, it is feasible that two independently
321 * developed modules may both use libusb.
323 * libusb is written to allow for these multiple user scenarios. The two
324 * "instances" of libusb will not interfere: libusb_set_debug() calls
325 * from one user will not affect the same settings for other users, other
326 * users can continue using libusb after one of them calls libusb_exit(), etc.
328 * This is made possible through libusb's <em>context</em> concept. When you
329 * call libusb_init(), you are (optionally) given a context. You can then pass
330 * this context pointer back into future libusb functions.
332 * In order to keep things simple for more simplistic applications, it is
333 * legal to pass NULL to all functions requiring a context pointer (as long as
334 * you're sure no other code will attempt to use libusb from the same process).
335 * When you pass NULL, the default context will be used. The default context
336 * is created the first time a process calls libusb_init() when no other
337 * context is alive. Contexts are destroyed during libusb_exit().
339 * The default context is reference-counted and can be shared. That means that
340 * if libusb_init(NULL) is called twice within the same process, the two
341 * users end up sharing the same context. The deinitialization and freeing of
342 * the default context will only happen when the last user calls libusb_exit().
343 * In other words, the default context is created and initialized when its
344 * reference count goes from 0 to 1, and is deinitialized and destroyed when
345 * its reference count goes from 1 to 0.
347 * You may be wondering why only a subset of libusb functions require a
348 * context pointer in their function definition. Internally, libusb stores
349 * context pointers in other objects (e.g. libusb_device instances) and hence
350 * can infer the context from those objects.
354 * @defgroup lib Library initialization/deinitialization
355 * This page details how to initialize and deinitialize libusb. Initialization
356 * must be performed before using any libusb functionality, and similarly you
357 * must not call any libusb functions after deinitialization.
361 * @defgroup dev Device handling and enumeration
362 * The functionality documented below is designed to help with the following
364 * - Enumerating the USB devices currently attached to the system
365 * - Choosing a device to operate from your software
366 * - Opening and closing the chosen device
368 * \section nutshell In a nutshell...
370 * The description below really makes things sound more complicated than they
371 * actually are. The following sequence of function calls will be suitable
372 * for almost all scenarios and does not require you to have such a deep
373 * understanding of the resource management issues:
376 libusb_device **list;
377 libusb_device *found = NULL;
378 ssize_t cnt = libusb_get_device_list(NULL, &list);
384 for (i = 0; i < cnt; i++) {
385 libusb_device *device = list[i];
386 if (is_interesting(device)) {
393 libusb_device_handle *handle;
395 err = libusb_open(found, &handle);
401 libusb_free_device_list(list, 1);
404 * The two important points:
405 * - You asked libusb_free_device_list() to unreference the devices (2nd
407 * - You opened the device before freeing the list and unreferencing the
410 * If you ended up with a handle, you can now proceed to perform I/O on the
413 * \section devshandles Devices and device handles
414 * libusb has a concept of a USB device, represented by the
415 * \ref libusb_device opaque type. A device represents a USB device that
416 * is currently or was previously connected to the system. Using a reference
417 * to a device, you can determine certain information about the device (e.g.
418 * you can read the descriptor data).
420 * The libusb_get_device_list() function can be used to obtain a list of
421 * devices currently connected to the system. This is known as device
424 * Just because you have a reference to a device does not mean it is
425 * necessarily usable. The device may have been unplugged, you may not have
426 * permission to operate such device, or another program or driver may be
429 * When you've found a device that you'd like to operate, you must ask
430 * libusb to open the device using the libusb_open() function. Assuming
431 * success, libusb then returns you a <em>device handle</em>
432 * (a \ref libusb_device_handle pointer). All "real" I/O operations then
433 * operate on the handle rather than the original device pointer.
435 * \section devref Device discovery and reference counting
437 * Device discovery (i.e. calling libusb_get_device_list()) returns a
438 * freshly-allocated list of devices. The list itself must be freed when
439 * you are done with it. libusb also needs to know when it is OK to free
440 * the contents of the list - the devices themselves.
442 * To handle these issues, libusb provides you with two separate items:
443 * - A function to free the list itself
444 * - A reference counting system for the devices inside
446 * New devices presented by the libusb_get_device_list() function all have a
447 * reference count of 1. You can increase and decrease reference count using
448 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
449 * its reference count reaches 0.
451 * With the above information in mind, the process of opening a device can
452 * be viewed as follows:
453 * -# Discover devices using libusb_get_device_list().
454 * -# Choose the device that you want to operate, and call libusb_open().
455 * -# Unref all devices in the discovered device list.
456 * -# Free the discovered device list.
458 * The order is important - you must not unreference the device before
459 * attempting to open it, because unreferencing it may destroy the device.
461 * For convenience, the libusb_free_device_list() function includes a
462 * parameter to optionally unreference all the devices in the list before
463 * freeing the list itself. This combines steps 3 and 4 above.
465 * As an implementation detail, libusb_open() actually adds a reference to
466 * the device in question. This is because the device remains available
467 * through the handle via libusb_get_device(). The reference is deleted during
471 /** @defgroup misc Miscellaneous */
473 /* we traverse usbfs without knowing how many devices we are going to find.
474 * so we create this discovered_devs model which is similar to a linked-list
475 * which grows when required. it can be freed once discovery has completed,
476 * eliminating the need for a list node in the libusb_device structure
478 #define DISCOVERED_DEVICES_SIZE_STEP 8
480 static struct discovered_devs *discovered_devs_alloc(void) {
482 struct discovered_devs *ret =
483 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
487 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
492 /* append a device to the discovered devices collection. may realloc itself,
493 * returning new discdevs. returns NULL on realloc failure. */
494 struct discovered_devs *discovered_devs_append(
495 struct discovered_devs *discdevs, struct libusb_device *dev) {
497 size_t len = discdevs->len;
500 /* if there is space, just append the device */
501 if (LIKELY(len < discdevs->capacity)) {
502 discdevs->devices[len] = libusb_ref_device(dev);
507 /* exceeded capacity, need to grow */
508 usbi_dbg("need to increase capacity");
509 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
510 discdevs = usbi_reallocf(discdevs,
511 sizeof(*discdevs) + (sizeof(void *) * capacity));
512 if (LIKELY(discdevs)) {
513 discdevs->capacity = capacity;
514 discdevs->devices[len] = libusb_ref_device(dev);
521 static void discovered_devs_free(struct discovered_devs *discdevs) {
525 for (i = 0; i < discdevs->len; i++)
526 libusb_unref_device(discdevs->devices[i]);
531 /* Allocate a new device with a specific session ID. The returned device has
532 * a reference count of 1. */
533 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
534 unsigned long session_id) {
536 size_t priv_size = usbi_backend->device_priv_size;
537 struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
543 r = usbi_mutex_init(&dev->lock, NULL);
551 dev->session_data = session_id;
552 dev->speed = LIBUSB_SPEED_UNKNOWN;
554 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
555 usbi_connect_device(dev);
561 void usbi_connect_device(struct libusb_device *dev) {
563 libusb_hotplug_message message;
566 memset(&message, 0, sizeof(message));
567 message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED;
568 message.device = dev;
571 usbi_mutex_lock(&dev->ctx->usb_devs_lock);
573 list_add(&dev->list, &dev->ctx->usb_devs);
575 usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
577 /* Signal that an event has occurred for this device if we support hotplug AND
578 * the hotplug pipe is ready. This prevents an event from getting raised during
579 * initial enumeration. */
580 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)
581 && dev->ctx->hotplug_pipe[1] > 0) {
582 ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
583 if (UNLIKELY(sizeof(message) != ret)) {
584 usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
589 void usbi_disconnect_device(struct libusb_device *dev) {
591 libusb_hotplug_message message;
592 struct libusb_context *ctx = dev->ctx;
595 memset(&message, 0, sizeof(message));
596 message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT;
597 message.device = dev;
598 usbi_mutex_lock(&dev->lock);
602 usbi_mutex_unlock(&dev->lock);
604 usbi_mutex_lock(&ctx->usb_devs_lock);
606 list_del(&dev->list);
608 usbi_mutex_unlock(&ctx->usb_devs_lock);
610 /* Signal that an event has occurred for this device if we support hotplug AND
611 * the hotplug pipe is ready. This prevents an event from getting raised during
612 * initial enumeration. libusb_handle_events will take care of dereferencing the
614 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)
615 && dev->ctx->hotplug_pipe[1] > 0) {
616 ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
617 if (UNLIKELY(sizeof(message) != ret)) {
618 usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
623 /* Perform some final sanity checks on a newly discovered device. If this
624 * function fails (negative return code), the device should not be added
625 * to the discovered device list. */
626 int usbi_sanitize_device(struct libusb_device *dev) {
629 uint8_t num_configurations;
631 r = usbi_device_cache_descriptor(dev);
635 num_configurations = dev->device_descriptor.bNumConfigurations;
636 if UNLIKELY(num_configurations > USB_MAXCONFIG) {
637 usbi_err(DEVICE_CTX(dev), "too many configurations");
638 return LIBUSB_ERROR_IO;
639 } else if (0 == num_configurations)
640 usbi_dbg("zero configurations, maybe an unauthorized device");
642 dev->num_configurations = num_configurations;
643 return LIBUSB_SUCCESS;
646 /* Examine libusb's internal list of known devices, looking for one with
647 * a specific session ID. Returns the matching device if it was found, and
649 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
650 unsigned long session_id) {
652 struct libusb_device *dev;
653 struct libusb_device *ret = NULL;
655 usbi_mutex_lock(&ctx->usb_devs_lock);
657 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
658 if (dev->session_data == session_id) {
659 ret = libusb_ref_device(dev);
663 usbi_mutex_unlock(&ctx->usb_devs_lock);
669 * Returns a list of USB devices currently attached to the system. This is
670 * your entry point into finding a USB device to operate.
672 * You are expected to unreference all the devices when you are done with
673 * them, and then free the list with libusb_free_device_list(). Note that
674 * libusb_free_device_list() can unref all the devices for you. Be careful
675 * not to unreference a device you are about to open until after you have
678 * This return value of this function indicates the number of devices in
679 * the resultant list. The list is actually one element larger, as it is
682 * \param ctx the context to operate on, or NULL for the default context
683 * \param list output location for a list of devices. Must be later freed with
684 * libusb_free_device_list().
685 * \returns the number of devices in the outputted list, or any
686 * \ref libusb_error according to errors encountered by the backend.
688 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
689 libusb_device ***list) {
693 struct discovered_devs *discdevs = discovered_devs_alloc();
694 struct libusb_device **ret;
697 USBI_GET_CONTEXT(ctx);
700 if (UNLIKELY(!discdevs))
701 return LIBUSB_ERROR_NO_MEM;
703 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
704 LOGD("backend provides hotplug support");
705 struct libusb_device *dev;
707 if (usbi_backend->hotplug_poll)
708 usbi_backend->hotplug_poll();
710 usbi_mutex_lock(&ctx->usb_devs_lock);
712 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
714 discdevs = discovered_devs_append(discdevs, dev);
716 if (UNLIKELY(!discdevs)) {
717 r = LIBUSB_ERROR_NO_MEM;
722 usbi_mutex_unlock(&ctx->usb_devs_lock);
724 LOGD("backend does not provide hotplug support");
725 r = usbi_backend->get_device_list(ctx, &discdevs);
728 if (UNLIKELY(r < 0)) {
733 /* convert discovered_devs into a list */
735 ret = calloc(len + 1, sizeof(struct libusb_device *));
736 if (UNLIKELY(!ret)) {
737 LOGE("LIBUSB_ERROR_NO_MEM");
738 len = LIBUSB_ERROR_NO_MEM;
743 for (i = 0; i < len; i++) {
744 struct libusb_device *dev = discdevs->devices[i];
745 ret[i] = libusb_ref_device(dev);
750 discovered_devs_free(discdevs);
755 * search device with specific vender ID and product ID
756 * TODO it is better to check serial number for multiple device connection with same vender ID and product ID
757 * @return null if not found
758 * @param vid: vender ID, 0 means don't care
759 * @param pid: product ID, 0 means don't care
760 * @param sn: serial number(currently not use)
761 * @param fd: file descripter that need to access device on no-rooted Android
762 * @return null if not found
764 libusb_device *libusb_find_device(libusb_context *ctx, const int vid,
765 const int pid, const char* sn, int fd) {
769 libusb_device **devs;
770 // get list of devices
771 int cnt = libusb_get_device_list(ctx, &devs);
772 if (UNLIKELY(cnt < 0)) {
773 LOGI("failed to get device list");
774 usbi_dbg("failed to get device list");
779 libusb_device *device = NULL;
780 struct libusb_device_descriptor desc;
781 LOGI("try to find specific device:cnt=%d", cnt);
782 for (i = 0; i < cnt; i++) {
783 r = libusb_get_device_descriptor(devs[i], &desc);
784 if (UNLIKELY(r < 0)) {
785 LOGI("failed to get device descriptor");
786 usbi_dbg("failed to get device descriptor");
789 if ((!vid || (desc.idVendor == vid))
790 && (!pid || (desc.idProduct == pid))) {
793 libusb_ref_device(device);
798 libusb_free_device_list(devs, 1);
803 * Frees a list of devices previously discovered using
804 * libusb_get_device_list(). If the unref_devices parameter is set, the
805 * reference count of each device in the list is decremented by 1.
806 * \param list the list to free
807 * \param unref_devices whether to unref the devices in the list
809 void API_EXPORTED libusb_free_device_list(libusb_device **list,
817 struct libusb_device *dev;
819 while ((dev = list[i++]) != NULL)
820 libusb_unref_device(dev);
826 * Get the number of the bus that a device is connected to.
827 * \param dev a device
828 * \returns the bus number
830 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev) {
832 return dev->bus_number;
836 * Get the number of the port that a device is connected to.
837 * Unless the OS does something funky, or you are hot-plugging USB extension cards,
838 * the port number returned by this call is usually guaranteed to be uniquely tied
839 * to a physical port, meaning that different devices plugged on the same physical
840 * port should return the same port number.
842 * But outside of this, there is no guarantee that the port number returned by this
843 * call will remain the same, or even match the order in which ports have been
844 * numbered by the HUB/HCD manufacturer.
846 * \param dev a device
847 * \returns the port number (0 if not available)
849 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev) {
851 return dev->port_number;
855 * Get the list of all port numbers from root for the specified device
857 * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
858 * \param dev a device
859 * \param port_numbers the array that should contain the port numbers
860 * \param port_numbers_len the maximum length of the array. As per the USB 3.0
861 * specs, the current maximum limit for the depth is 7.
862 * \returns the number of elements filled
863 * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
865 int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
866 uint8_t* port_numbers, int port_numbers_len) {
868 int i = port_numbers_len;
869 struct libusb_context *ctx = DEVICE_CTX(dev);
871 if UNLIKELY(port_numbers_len <= 0)
872 return LIBUSB_ERROR_INVALID_PARAM;
874 // HCDs can be listed as devices with port #0
875 while ((dev) && (dev->port_number != 0)) {
877 usbi_warn(ctx, "port numbers array is too small");
878 return LIBUSB_ERROR_OVERFLOW;
880 port_numbers[i] = dev->port_number;
881 dev = dev->parent_dev;
883 if (i < port_numbers_len)
884 memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
885 return port_numbers_len - i;
889 * Deprecated please use libusb_get_port_numbers instead.
891 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
892 uint8_t* port_numbers, uint8_t port_numbers_len) {
896 return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
900 * Get the the parent from the specified device.
901 * \param dev a device
902 * \returns the device parent or NULL if not available
903 * You should issue a \ref libusb_get_device_list() before calling this
904 * function and make sure that you only access the parent before issuing
905 * \ref libusb_free_device_list(). The reason is that libusb currently does
906 * not maintain a permanent list of device instances, and therefore can
907 * only guarantee that parents are fully instantiated within a
908 * libusb_get_device_list() - libusb_free_device_list() block.
911 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev) {
913 return dev->parent_dev;
917 * Get the address of the device on the bus it is connected to.
918 * \param dev a device
919 * \returns the device address
921 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev) {
923 return dev->device_address;
927 * Get the negotiated connection speed for a device.
928 * \param dev a device
929 * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
930 * the OS doesn't know or doesn't support returning the negotiated speed.
932 int API_EXPORTED libusb_get_device_speed(libusb_device *dev) {
937 static const struct libusb_endpoint_descriptor *find_endpoint(
938 struct libusb_config_descriptor *config, unsigned char endpoint) {
941 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
942 const struct libusb_interface *iface = &config->interface[iface_idx];
945 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
947 const struct libusb_interface_descriptor *altsetting
948 = &iface->altsetting[altsetting_idx];
951 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
952 const struct libusb_endpoint_descriptor *ep =
953 &altsetting->endpoint[ep_idx];
954 if (ep->bEndpointAddress == endpoint)
963 * Convenience function to retrieve the wMaxPacketSize value for a particular
964 * endpoint in the active device configuration.
966 * This function was originally intended to be of assistance when setting up
967 * isochronous transfers, but a design mistake resulted in this function
968 * instead. It simply returns the wMaxPacketSize value without considering
969 * its contents. If you're dealing with isochronous transfers, you probably
970 * want libusb_get_max_iso_packet_size() instead.
972 * \param dev a device
973 * \param endpoint address of the endpoint in question
974 * \returns the wMaxPacketSize value
975 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
976 * \returns LIBUSB_ERROR_OTHER on other failure
978 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
979 unsigned char endpoint) {
981 struct libusb_config_descriptor *config;
982 const struct libusb_endpoint_descriptor *ep;
985 r = libusb_get_active_config_descriptor(dev, &config);
986 if (UNLIKELY(r < 0)) {
987 usbi_err(DEVICE_CTX(dev),
988 "could not retrieve active config descriptor");
989 return LIBUSB_ERROR_OTHER;
992 ep = find_endpoint(config, endpoint);
994 r = LIBUSB_ERROR_NOT_FOUND;
998 r = ep->wMaxPacketSize;
1001 libusb_free_config_descriptor(config);
1006 * Calculate the maximum packet size which a specific endpoint is capable is
1007 * sending or receiving in the duration of 1 microframe
1009 * Only the active configuration is examined. The calculation is based on the
1010 * wMaxPacketSize field in the endpoint descriptor as described in section
1011 * 9.6.6 in the USB 2.0 specifications.
1013 * If acting on an isochronous or interrupt endpoint, this function will
1014 * multiply the value found in bits 0:10 by the number of transactions per
1015 * microframe (determined by bits 11:12). Otherwise, this function just
1016 * returns the numeric value found in bits 0:10.
1018 * This function is useful for setting up isochronous transfers, for example
1019 * you might pass the return value from this function to
1020 * libusb_set_iso_packet_lengths() in order to set the length field of every
1021 * isochronous packet in a transfer.
1025 * \param dev a device
1026 * \param endpoint address of the endpoint in question
1027 * \returns the maximum packet size which can be sent/received on this endpoint
1028 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1029 * \returns LIBUSB_ERROR_OTHER on other failure
1031 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
1032 unsigned char endpoint) {
1034 struct libusb_config_descriptor *config;
1035 const struct libusb_endpoint_descriptor *ep;
1036 enum libusb_transfer_type ep_type;
1040 r = libusb_get_active_config_descriptor(dev, &config);
1041 if (UNLIKELY(r < 0)) {
1042 usbi_err(DEVICE_CTX(dev),
1043 "could not retrieve active config descriptor");
1044 return LIBUSB_ERROR_OTHER;
1047 ep = find_endpoint(config, endpoint);
1048 if (UNLIKELY(!ep)) {
1049 r = LIBUSB_ERROR_NOT_FOUND;
1053 val = ep->wMaxPacketSize;
1054 ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
1057 if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
1058 || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1059 r *= (1 + ((val >> 11) & 3));
1062 libusb_free_config_descriptor(config);
1067 * Increment the reference count of a device.
1068 * \param dev the device to reference
1069 * \returns the same device
1072 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev) {
1075 usbi_mutex_lock(&dev->lock);
1077 refcnt = ++dev->refcnt;
1079 usbi_mutex_unlock(&dev->lock);
1080 // LOGI("refcnt=%d", refcnt);
1085 * Decrement the reference count of a device. If the decrement operation
1086 * causes the reference count to reach zero, the device shall be destroyed.
1087 * \param dev the device to unreference
1089 void API_EXPORTED libusb_unref_device(libusb_device *dev) {
1096 usbi_mutex_lock(&dev->lock);
1098 refcnt = --dev->refcnt;
1100 usbi_mutex_unlock(&dev->lock);
1101 // LOGI("refcnt=%d", dev->refcnt);
1104 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
1106 libusb_unref_device(dev->parent_dev);
1108 if (usbi_backend->destroy_device)
1109 usbi_backend->destroy_device(dev);
1111 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1112 /* backend does not support hotplug */
1113 usbi_disconnect_device(dev);
1116 usbi_mutex_destroy(&dev->lock);
1122 * Interrupt the iteration of the event handling thread, so that it picks
1125 void usbi_fd_notification(struct libusb_context *ctx) {
1127 unsigned char dummy = 1;
1130 if (UNLIKELY(ctx == NULL))
1133 /* record that we are messing with poll fds */
1134 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1136 ctx->pollfd_modify++;
1138 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1140 /* write some data on control pipe to interrupt event handlers */
1141 r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1142 if (UNLIKELY(r <= 0)) {
1143 usbi_warn(ctx, "internal signalling write failed");
1144 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1146 ctx->pollfd_modify--;
1148 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1152 /* take event handling lock */
1153 libusb_lock_events(ctx);
1155 /* read the dummy data */
1156 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1157 if (UNLIKELY(r <= 0))
1158 usbi_warn(ctx, "internal signalling read failed");
1160 /* we're done with modifying poll fds */
1161 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1163 ctx->pollfd_modify--;
1165 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1167 /* Release event handling lock and wake up event waiters */
1168 libusb_unlock_events(ctx);
1172 * Open a device and obtain a device handle. A handle allows you to perform
1173 * I/O on the device in question.
1175 * Internally, this function adds a reference to the device and makes it
1176 * available to you through libusb_get_device(). This reference is removed
1177 * during libusb_close().
1179 * This is a non-blocking function; no requests are sent over the bus.
1181 * \param dev the device to open
1182 * \param handle output location for the returned device handle pointer. Only
1183 * populated when the return code is 0.
1184 * \returns 0 on success
1185 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
1186 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1187 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1188 * \returns another LIBUSB_ERROR code on other failure
1190 int API_EXPORTED libusb_open(libusb_device *dev, libusb_device_handle **handle) {
1192 struct libusb_context *ctx = DEVICE_CTX(dev);
1193 struct libusb_device_handle *_handle;
1194 size_t priv_size = usbi_backend->device_handle_priv_size;
1196 usbi_dbg("open (bus/addr)=(%d.%d)", dev->bus_number, dev->device_address);
1198 if (UNLIKELY(!dev->attached)) {
1199 return LIBUSB_ERROR_NO_DEVICE;
1202 _handle = malloc(sizeof(*_handle) + priv_size);
1203 if (UNLIKELY(!_handle))
1204 return LIBUSB_ERROR_NO_MEM;
1206 r = usbi_mutex_init(&_handle->lock, NULL);
1209 return LIBUSB_ERROR_OTHER;
1212 _handle->dev = libusb_ref_device(dev);
1213 _handle->auto_detach_kernel_driver = 0;
1214 _handle->claimed_interfaces = 0;
1215 memset(&_handle->os_priv, 0, priv_size);
1217 r = usbi_backend->open(_handle);
1218 if (UNLIKELY(r < 0)) {
1219 usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
1220 libusb_unref_device(dev);
1221 usbi_mutex_destroy(&_handle->lock);
1226 usbi_mutex_lock(&ctx->open_devs_lock);
1228 list_add(&_handle->list, &ctx->open_devs);
1230 usbi_mutex_unlock(&ctx->open_devs_lock);
1233 /* At this point, we want to interrupt any existing event handlers so
1234 * that they realise the addition of the new device's poll fd. One
1235 * example when this is desirable is if the user is running a separate
1236 * dedicated libusb events handling thread, which is running with a long
1237 * or infinite timeout. We want to interrupt that iteration of the loop,
1238 * so that it picks up the new fd, and then continues. */
1239 usbi_fd_notification(ctx);
1241 return LIBUSB_SUCCESS;
1244 int API_EXPORTED libusb_set_device_fd(libusb_device *dev, int fd) {
1246 return usbi_backend->set_device_fd(dev, fd);
1249 libusb_device * LIBUSB_CALL libusb_get_device_with_fd(libusb_context *ctx,
1250 int vid, int pid, const char *serial, int fd, int busnum, int devaddr) {
1254 struct libusb_device *device = NULL;
1255 // android_generate_device内でusbi_alloc_deviceが呼ばれた時に参照カウンタは1
1256 int ret = android_generate_device(ctx, &device, vid, pid, serial, fd, busnum, devaddr);
1258 LOGD("android_generate_device failed:err=%d", ret);
1266 * Convenience function for finding a device with a particular
1267 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1268 * for those scenarios where you are using libusb to knock up a quick test
1269 * application - it allows you to avoid calling libusb_get_device_list() and
1270 * worrying about traversing/freeing the list.
1272 * This function has limitations and is hence not intended for use in real
1273 * applications: if multiple devices have the same IDs it will only
1274 * give you the first one, etc.
1276 * \param ctx the context to operate on, or NULL for the default context
1277 * \param vendor_id the idVendor value to search for
1278 * \param product_id the idProduct value to search for
1279 * \returns a handle for the first found device, or NULL on error or if the
1280 * device could not be found. */
1282 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1283 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id) {
1285 struct libusb_device **devs;
1286 struct libusb_device *found = NULL;
1287 struct libusb_device *dev;
1288 struct libusb_device_handle *handle = NULL;
1292 if (libusb_get_device_list(ctx, &devs) < 0)
1295 while ((dev = devs[i++]) != NULL) {
1296 struct libusb_device_descriptor desc;
1297 r = libusb_get_device_descriptor(dev, &desc);
1298 if (UNLIKELY(r < 0))
1300 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1307 r = libusb_open(found, &handle);
1308 if (UNLIKELY(r < 0))
1313 libusb_free_device_list(devs, 1);
1317 static void do_close(struct libusb_context *ctx,
1318 struct libusb_device_handle *dev_handle) {
1320 struct usbi_transfer *itransfer;
1321 struct usbi_transfer *tmp;
1323 libusb_lock_events(ctx);
1325 /* remove any transfers in flight that are for this device */
1326 usbi_mutex_lock(&ctx->flying_transfers_lock);
1328 /* safe iteration because transfers may be being deleted */
1329 list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer)
1331 struct libusb_transfer *transfer =
1332 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1334 if (transfer->dev_handle != dev_handle)
1337 if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1339 "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1341 if (itransfer->flags & USBI_TRANSFER_CANCELLING)
1343 "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1346 "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1349 /* remove from the list of in-flight transfers and make sure
1350 * we don't accidentally use the device handle in the future
1351 * (or that such accesses will be easily caught and identified as a crash)
1353 usbi_mutex_lock(&itransfer->lock);
1355 list_del(&itransfer->list);
1356 transfer->dev_handle = NULL;
1358 usbi_mutex_unlock(&itransfer->lock);
1360 /* it is up to the user to free up the actual transfer struct. this is
1361 * just making sure that we don't attempt to process the transfer after
1362 * the device handle is invalid
1365 "Removed transfer %p from the in-flight list because device handle %p closed",
1366 transfer, dev_handle);
1369 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1371 libusb_unlock_events(ctx);
1373 usbi_mutex_lock(&ctx->open_devs_lock);
1375 list_del(&dev_handle->list);
1377 usbi_mutex_unlock(&ctx->open_devs_lock);
1379 usbi_backend->close(dev_handle);
1380 libusb_unref_device(dev_handle->dev);
1381 usbi_mutex_destroy(&dev_handle->lock);
1386 * Close a device handle. Should be called on all open handles before your
1387 * application exits.
1389 * Internally, this function destroys the reference that was added by
1390 * libusb_open() on the given device.
1392 * This is a non-blocking function; no requests are sent over the bus.
1394 * \param dev_handle the handle to close
1396 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle) {
1398 struct libusb_context *ctx;
1399 unsigned char dummy = 1;
1402 if (UNLIKELY(!dev_handle))
1406 ctx = HANDLE_CTX(dev_handle);
1408 /* Similarly to libusb_open(), we want to interrupt all event handlers
1409 * at this point. More importantly, we want to perform the actual close of
1410 * the device while holding the event handling lock (preventing any other
1411 * thread from doing event handling) because we will be removing a file
1412 * descriptor from the polling loop. */
1414 /* record that we are messing with poll fds */
1415 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1417 ctx->pollfd_modify++;
1419 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1421 /* write some data on control pipe to interrupt event handlers */
1422 r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1423 if (UNLIKELY(r <= 0)) {
1424 usbi_warn(ctx, "internal signalling write failed, closing anyway");
1425 do_close(ctx, dev_handle);
1426 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1428 ctx->pollfd_modify--;
1430 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1434 /* take event handling lock */
1435 libusb_lock_events(ctx); // XXX crash
1437 /* read the dummy data */
1438 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy)); // XXX crash
1439 if (UNLIKELY(r <= 0)) {
1440 usbi_warn(ctx, "internal signalling read failed, closing anyway");
1443 /* Close the device */
1444 do_close(ctx, dev_handle); // XXX this function internally call libusb_lock_events/libusb_unlock_events
1445 // while libusb_lock_events is already called and will hang-up on some OS?
1447 /* we're done with modifying poll fds */
1448 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1450 ctx->pollfd_modify--;
1452 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1454 /* Release event handling lock and wake up event waiters */
1455 libusb_unlock_events(ctx);
1459 * Get the underlying device for a handle. This function does not modify
1460 * the reference count of the returned device, so do not feel compelled to
1461 * unreference it when you are done.
1462 * \param dev_handle a device handle
1463 * \returns the underlying device
1466 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle) {
1468 return dev_handle->dev;
1472 * Determine the bConfigurationValue of the currently active configuration.
1474 * You could formulate your own control request to obtain this information,
1475 * but this function has the advantage that it may be able to retrieve the
1476 * information from operating system caches (no I/O involved).
1478 * If the OS does not cache this information, then this function will block
1479 * while a control transfer is submitted to retrieve the information.
1481 * This function will return a value of 0 in the <tt>config</tt> output
1482 * parameter if the device is in unconfigured state.
1484 * \param dev a device handle
1485 * \param config output location for the bConfigurationValue of the active
1486 * configuration (only valid for return code 0)
1487 * \returns 0 on success
1488 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1489 * \returns another LIBUSB_ERROR code on other failure
1491 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
1493 int r = LIBUSB_ERROR_NOT_SUPPORTED;
1496 if (usbi_backend->get_configuration)
1497 r = usbi_backend->get_configuration(dev, config);
1499 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1501 usbi_dbg("falling back to control message");
1502 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1503 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1505 usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
1506 r = LIBUSB_ERROR_IO;
1507 } else if (r == 1) {
1511 usbi_dbg("control failed, error %d", r);
1516 usbi_dbg("active config %d", *config);
1522 * Set the active configuration for a device.
1524 * The operating system may or may not have already set an active
1525 * configuration on the device. It is up to your application to ensure the
1526 * correct configuration is selected before you attempt to claim interfaces
1527 * and perform other operations.
1529 * If you call this function on a device already configured with the selected
1530 * configuration, then this function will act as a lightweight device reset:
1531 * it will issue a SET_CONFIGURATION request using the current configuration,
1532 * causing most USB-related device state to be reset (altsetting reset to zero,
1533 * endpoint halts cleared, toggles reset).
1535 * You cannot change/reset configuration if your application has claimed
1536 * interfaces. It is advised to set the desired configuration before claiming
1539 * Alternatively you can call libusb_release_interface() first. Note if you
1540 * do things this way you must ensure that auto_detach_kernel_driver for
1541 * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
1542 * release the interface(s).
1544 * You cannot change/reset configuration if other applications or drivers have
1545 * claimed interfaces.
1547 * A configuration value of -1 will put the device in unconfigured state.
1548 * The USB specifications state that a configuration value of 0 does this,
1549 * however buggy devices exist which actually have a configuration 0.
1551 * You should always use this function rather than formulating your own
1552 * SET_CONFIGURATION control request. This is because the underlying operating
1553 * system needs to know when such changes happen.
1555 * This is a blocking function.
1557 * \param dev a device handle
1558 * \param configuration the bConfigurationValue of the configuration you
1559 * wish to activate, or -1 if you wish to put the device in unconfigured state
1560 * \returns 0 on success
1561 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1562 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1563 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1564 * \returns another LIBUSB_ERROR code on other failure
1565 * \see libusb_set_auto_detach_kernel_driver()
1567 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
1568 int configuration) {
1570 usbi_dbg("configuration %d", configuration);
1571 return usbi_backend->set_configuration(dev, configuration);
1575 * Claim an interface on a given device handle. You must claim the interface
1576 * you wish to use before you can perform I/O on any of its endpoints.
1578 * It is legal to attempt to claim an already-claimed interface, in which
1579 * case libusb just returns 0 without doing anything.
1581 * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
1582 * will be detached if necessary, on failure the detach error is returned.
1584 * Claiming of interfaces is a purely logical operation; it does not cause
1585 * any requests to be sent over the bus. Interface claiming is used to
1586 * instruct the underlying operating system that your application wishes
1587 * to take ownership of the interface.
1589 * This is a non-blocking function.
1591 * \param dev a device handle
1592 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1594 * \returns 0 on success
1595 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1596 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1598 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1599 * \returns a LIBUSB_ERROR code on other failure
1600 * \see libusb_set_auto_detach_kernel_driver()
1602 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
1603 int interface_number) {
1607 int r = LIBUSB_SUCCESS;
1609 usbi_dbg("interface %d", interface_number);
1610 LOGD("interface %d", interface_number);
1612 if (interface_number >= USB_MAXINTERFACES) {
1613 RETURN(LIBUSB_ERROR_INVALID_PARAM, int);
1616 if (UNLIKELY(!dev->dev->attached)) {
1617 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1620 usbi_mutex_lock(&dev->lock);
1621 if (!(dev->claimed_interfaces & (1 << interface_number))) {
1622 r = usbi_backend->claim_interface(dev, interface_number);
1623 if (r == LIBUSB_ERROR_BUSY) {
1624 // EBUSYが返ってきた時はたぶんカーネルドライバーがアタッチされているから
1625 // デタッチ要求してから再度claimしてみる
1626 LOGV("request detach kernel driver and retry claim interface");
1627 r = usbi_backend->release_interface(dev, interface_number);
1628 libusb_detach_kernel_driver(dev, interface_number);
1630 r = usbi_backend->claim_interface(dev, interface_number);
1634 dev->claimed_interfaces |= 1 << interface_number;
1637 LOGV("already claimed");
1639 usbi_mutex_unlock(&dev->lock);
1645 * Release an interface previously claimed with libusb_claim_interface(). You
1646 * should release all claimed interfaces before closing a device handle.
1648 * This is a blocking function. A SET_INTERFACE control request will be sent
1649 * to the device, resetting interface state to the first alternate setting.
1651 * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
1652 * driver will be re-attached after releasing the interface.
1654 * \param dev a device handle
1655 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1656 * previously-claimed interface
1657 * \returns 0 on success
1658 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1659 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1660 * \returns another LIBUSB_ERROR code on other failure
1661 * \see libusb_set_auto_detach_kernel_driver()
1663 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
1664 int interface_number) {
1670 LOGD("interface %d", interface_number);
1671 usbi_dbg("interface %d", interface_number);
1672 if (UNLIKELY(interface_number >= USB_MAXINTERFACES))
1673 RETURN(LIBUSB_ERROR_INVALID_PARAM, int);
1675 usbi_mutex_lock(&dev->lock);
1677 if (dev->claimed_interfaces & (1 << interface_number)) {
1678 r = usbi_backend->release_interface(dev, interface_number);
1681 dev->claimed_interfaces &= ~(1 << interface_number);
1685 r = LIBUSB_ERROR_NOT_FOUND;
1688 usbi_mutex_unlock(&dev->lock);
1694 * Activate an alternate setting for an interface. The interface must have
1695 * been previously claimed with libusb_claim_interface().
1697 * You should always use this function rather than formulating your own
1698 * SET_INTERFACE control request. This is because the underlying operating
1699 * system needs to know when such changes happen.
1701 * This is a blocking function.
1703 * \param dev a device handle
1704 * \param interface_number the <tt>bInterfaceNumber</tt> of the
1705 * previously-claimed interface
1706 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1707 * setting to activate
1708 * \returns 0 on success
1709 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1710 * requested alternate setting does not exist
1711 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1712 * \returns another LIBUSB_ERROR code on other failure
1714 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
1715 int interface_number, int alternate_setting) {
1717 usbi_dbg("interface %d altsetting %d", interface_number, alternate_setting);
1718 if (interface_number >= USB_MAXINTERFACES)
1719 return LIBUSB_ERROR_INVALID_PARAM;
1721 usbi_mutex_lock(&dev->lock);
1723 if (UNLIKELY(!dev->dev->attached)) {
1724 usbi_mutex_unlock(&dev->lock);
1725 return LIBUSB_ERROR_NO_DEVICE;
1728 if (UNLIKELY(!(dev->claimed_interfaces & (1 << interface_number)))) {
1729 usbi_mutex_unlock(&dev->lock);
1730 return LIBUSB_ERROR_NOT_FOUND;
1733 usbi_mutex_unlock(&dev->lock);
1735 return usbi_backend->set_interface_altsetting(dev, interface_number,
1740 * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1741 * are unable to receive or transmit data until the halt condition is stalled.
1743 * You should cancel all pending transfers before attempting to clear the halt
1746 * This is a blocking function.
1748 * \param dev a device handle
1749 * \param endpoint the endpoint to clear halt status
1750 * \returns 0 on success
1751 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1752 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1753 * \returns another LIBUSB_ERROR code on other failure
1755 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
1756 unsigned char endpoint) {
1758 usbi_dbg("endpoint %x", endpoint);
1759 if (UNLIKELY(!dev->dev->attached))
1760 return LIBUSB_ERROR_NO_DEVICE;
1762 return usbi_backend->clear_halt(dev, endpoint);
1766 * Perform a USB port reset to reinitialize a device. The system will attempt
1767 * to restore the previous configuration and alternate settings after the
1768 * reset has completed.
1770 * If the reset fails, the descriptors change, or the previous state cannot be
1771 * restored, the device will appear to be disconnected and reconnected. This
1772 * means that the device handle is no longer valid (you should close it) and
1773 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1774 * when this is the case.
1776 * This is a blocking function which usually incurs a noticeable delay.
1778 * \param dev a handle of the device to reset
1779 * \returns 0 on success
1780 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1781 * device has been disconnected
1782 * \returns another LIBUSB_ERROR code on other failure
1784 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev) {
1787 if (UNLIKELY(!dev->dev->attached))
1788 return LIBUSB_ERROR_NO_DEVICE;
1790 return usbi_backend->reset_device(dev);
1793 /** \ingroup asyncio
1794 * Allocate up to num_streams usb bulk streams on the specified endpoints. This
1795 * function takes an array of endpoints rather then a single endpoint because
1796 * some protocols require that endpoints are setup with similar stream ids.
1797 * All endpoints passed in must belong to the same interface.
1799 * Note this function may return less streams then requested. Also note that the
1800 * same number of streams are allocated for each endpoint in the endpoint array.
1802 * Stream id 0 is reserved, and should not be used to communicate with devices.
1803 * If libusb_alloc_streams() returns with a value of N, you may use stream ids
1806 * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1808 * \param dev a device handle
1809 * \param num_streams number of streams to try to allocate
1810 * \param endpoints array of endpoints to allocate streams on
1811 * \param num_endpoints length of the endpoints array
1812 * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
1814 int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev,
1815 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1817 usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints);
1819 if UNLIKELY(!dev->dev->attached)
1820 return LIBUSB_ERROR_NO_DEVICE;
1822 if LIKELY(usbi_backend->alloc_streams)
1823 return usbi_backend->alloc_streams(dev, num_streams, endpoints,
1826 return LIBUSB_ERROR_NOT_SUPPORTED;
1829 /** \ingroup asyncio
1830 * Free usb bulk streams allocated with libusb_alloc_streams().
1832 * Note streams are automatically free-ed when releasing an interface.
1834 * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1836 * \param dev a device handle
1837 * \param endpoints array of endpoints to free streams on
1838 * \param num_endpoints length of the endpoints array
1839 * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1841 int API_EXPORTED libusb_free_streams(libusb_device_handle *dev,
1842 unsigned char *endpoints, int num_endpoints)
1846 LOGD("eps %d", num_endpoints);
1847 usbi_dbg("eps %d", num_endpoints);
1849 if UNLIKELY(!dev->dev->attached) {
1850 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1853 if LIKELY(usbi_backend->free_streams) {
1854 RETURN(usbi_backend->free_streams(dev, endpoints, num_endpoints), int);
1856 RETURN(LIBUSB_ERROR_NOT_SUPPORTED, int);
1861 * Determine if a kernel driver is active on an interface. If a kernel driver
1862 * is active, you cannot claim the interface, and libusb will be unable to
1865 * This functionality is not available on Windows.
1867 * \param dev a device handle
1868 * \param interface_number the interface to check
1869 * \returns 0 if no kernel driver is active
1870 * \returns 1 if a kernel driver is active
1871 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1872 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1874 * \returns another LIBUSB_ERROR code on other failure
1875 * \see libusb_detach_kernel_driver()
1877 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
1878 int interface_number) {
1882 LOGD("interface %d", interface_number);
1883 usbi_dbg("interface %d", interface_number);
1885 if (UNLIKELY(!dev->dev->attached)) {
1886 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1889 if LIKELY(usbi_backend->kernel_driver_active) {
1890 RETURN(usbi_backend->kernel_driver_active(dev, interface_number), int);
1892 RETURN(LIBUSB_ERROR_NOT_SUPPORTED, int);
1897 * Detach a kernel driver from an interface. If successful, you will then be
1898 * able to claim the interface and perform I/O.
1900 * This functionality is not available on Darwin or Windows.
1902 * Note that libusb itself also talks to the device through a special kernel
1903 * driver, if this driver is already attached to the device, this call will
1904 * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1906 * \param dev a device handle
1907 * \param interface_number the interface to detach the driver from
1908 * \returns 0 on success
1909 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1910 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1911 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1912 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1914 * \returns another LIBUSB_ERROR code on other failure
1915 * \see libusb_kernel_driver_active()
1917 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
1918 int interface_number) {
1920 usbi_dbg("interface %d", interface_number);
1922 if (UNLIKELY(!dev->dev->attached))
1923 return LIBUSB_ERROR_NO_DEVICE;
1925 if (LIKELY(usbi_backend->detach_kernel_driver))
1926 return usbi_backend->detach_kernel_driver(dev, interface_number);
1928 return LIBUSB_ERROR_NOT_SUPPORTED;
1932 * Re-attach an interface's kernel driver, which was previously detached
1933 * using libusb_detach_kernel_driver(). This call is only effective on
1934 * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1936 * This functionality is not available on Darwin or Windows.
1938 * \param dev a device handle
1939 * \param interface_number the interface to attach the driver from
1940 * \returns 0 on success
1941 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1942 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1943 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1944 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1946 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1947 * interface is claimed by a program or driver
1948 * \returns another LIBUSB_ERROR code on other failure
1949 * \see libusb_kernel_driver_active()
1951 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
1952 int interface_number) {
1956 LOGD("interface %d", interface_number);
1957 usbi_dbg("interface %d", interface_number);
1959 if (UNLIKELY(!dev->dev->attached)) {
1960 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1963 if (LIKELY(usbi_backend->attach_kernel_driver)) {
1964 RETURN(usbi_backend->attach_kernel_driver(dev, interface_number), int);
1966 RETURN(LIBUSB_ERROR_NOT_SUPPORTED, int);
1971 * Enable/disable libusb's automatic kernel driver detachment. When this is
1972 * enabled libusb will automatically detach the kernel driver on an interface
1973 * when claiming the interface, and attach it when releasing the interface.
1975 * Automatic kernel driver detachment is disabled on newly opened device
1976 * handles by default.
1978 * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
1979 * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
1980 * continue as if this function was never called.
1982 * \param dev a device handle
1983 * \param enable whether to enable or disable auto kernel driver detachment
1985 * \returns LIBUSB_SUCCESS on success
1986 * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1988 * \see libusb_claim_interface()
1989 * \see libusb_release_interface()
1990 * \see libusb_set_configuration()
1992 int API_EXPORTED libusb_set_auto_detach_kernel_driver(libusb_device_handle *dev,
1997 LOGD("enable=%d", enable);
1998 if (!(usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER)) {
1999 LOGD("does not support detach kernel driver");
2000 RETURN(LIBUSB_ERROR_NOT_SUPPORTED, int);
2003 dev->auto_detach_kernel_driver = enable;
2004 RETURN(LIBUSB_SUCCESS, int);
2008 * Set log message verbosity.
2010 * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
2011 * printed. If you choose to increase the message verbosity level, ensure
2012 * that your application does not close the stdout/stderr file descriptors.
2014 * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusb is conservative
2015 * with its message logging and most of the time, will only log messages that
2016 * explain error conditions and other oddities. This will help you debug
2019 * If the LIBUSB_DEBUG environment variable was set when libusb was
2020 * initialized, this function does nothing: the message verbosity is fixed
2021 * to the value in the environment variable.
2023 * If libusb was compiled without any message logging, this function does
2024 * nothing: you'll never get any messages.
2026 * If libusb was compiled with verbose debug message logging, this function
2027 * does nothing: you'll always get messages from all levels.
2029 * \param ctx the context to operate on, or NULL for the default context
2030 * \param level debug level to set
2032 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level) {
2034 USBI_GET_CONTEXT(ctx);
2035 if (!ctx->debug_fixed)
2039 int API_EXPORTED libusb_init2(libusb_context **context, const char *usbfs) {
2041 struct libusb_device *dev, *next;
2042 char *dbg = getenv("LIBUSB_DEBUG");
2043 struct libusb_context *ctx;
2044 static int first_init = 1;
2047 usbi_mutex_static_lock(&default_context_lock);
2049 if (!timestamp_origin.tv_sec) {
2050 usbi_gettimeofday(×tamp_origin, NULL);
2053 if (!context && usbi_default_context) {
2054 usbi_dbg("reusing default context");
2055 LOGI("reusing default context");
2056 default_context_refcnt++;
2057 usbi_mutex_static_unlock(&default_context_lock);
2058 return LIBUSB_SUCCESS;
2061 ctx = calloc(1, sizeof(*ctx));
2062 if (UNLIKELY(!ctx)) {
2063 r = LIBUSB_ERROR_NO_MEM;
2067 #ifdef ENABLE_DEBUG_LOGGING
2068 ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
2071 if (UNLIKELY(dbg)) {
2072 ctx->debug = atoi(dbg);
2074 ctx->debug_fixed = 1;
2077 /* default context should be initialized before calling usbi_dbg */
2078 if (!usbi_default_context) {
2079 usbi_default_context = ctx;
2080 default_context_refcnt++;
2081 usbi_dbg("created default context");
2084 LOGI("libusb v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
2085 libusb_version_internal.micro, libusb_version_internal.nano);
2087 usbi_dbg("libusb v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
2088 libusb_version_internal.micro, libusb_version_internal.nano);
2090 usbi_mutex_init(&ctx->usb_devs_lock, NULL);
2091 usbi_mutex_init(&ctx->open_devs_lock, NULL);
2092 usbi_mutex_init(&ctx->hotplug_cbs_lock, NULL);
2093 list_init(&ctx->usb_devs);
2094 list_init(&ctx->open_devs);
2095 list_init(&ctx->hotplug_cbs);
2097 usbi_mutex_static_lock(&active_contexts_lock);
2101 list_init(&active_contexts_list);
2103 list_add(&ctx->list, &active_contexts_list);
2105 usbi_mutex_static_unlock(&active_contexts_lock);
2107 if (LIKELY(usbfs && strlen(usbfs) > 0)) {
2108 LOGD("call usbi_backend->init2");
2109 if (usbi_backend->init2) {
2110 r = usbi_backend->init2(ctx, usbfs);
2112 LOGE("failed to call usbi_backend->init2, err=%d", r);
2116 LOGE("has no usbi_backend->init2");
2120 LOGD("call usbi_backend->init");
2121 if (usbi_backend->init) {
2122 r = usbi_backend->init(ctx);
2129 r = usbi_io_init(ctx);
2130 if (UNLIKELY(r < 0))
2131 goto err_backend_exit;
2133 usbi_mutex_static_unlock(&default_context_lock);
2138 RETURN(LIBUSB_SUCCESS, int);
2141 LOGI("err_backend_exit");
2142 if (usbi_backend->exit)
2143 usbi_backend->exit();
2145 LOGI("err_free_ctx");
2146 if (ctx == usbi_default_context)
2147 usbi_default_context = NULL;
2149 usbi_mutex_static_lock(&active_contexts_lock);
2151 list_del(&ctx->list);
2153 usbi_mutex_static_unlock(&active_contexts_lock);
2155 usbi_mutex_lock(&ctx->usb_devs_lock);
2157 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device)
2159 list_del(&dev->list);
2160 libusb_unref_device(dev);
2163 usbi_mutex_unlock(&ctx->usb_devs_lock);
2165 usbi_mutex_destroy(&ctx->open_devs_lock);
2166 usbi_mutex_destroy(&ctx->usb_devs_lock);
2167 usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2172 usbi_mutex_static_unlock(&default_context_lock);
2177 * Initialize libusb. This function must be called before calling any other
2180 * If you do not provide an output location for a context pointer, a default
2181 * context will be created. If there was already a default context, it will
2182 * be reused (and nothing will be initialized/reinitialized).
2184 * \param context Optional output location for context pointer.
2185 * Only valid on return code 0.
2186 * \returns 0 on success, or a LIBUSB_ERROR code on failure
2189 int API_EXPORTED libusb_init(libusb_context **context) {
2191 return libusb_init2(context, NULL);
2193 struct libusb_device *dev, *next;
2194 char *dbg = getenv("LIBUSB_DEBUG");
2195 struct libusb_context *ctx;
2196 static int first_init = 1;
2199 usbi_mutex_static_lock(&default_context_lock);
2201 if (!timestamp_origin.tv_sec) {
2202 usbi_gettimeofday(×tamp_origin, NULL);
2205 if (!context && usbi_default_context) {
2206 usbi_dbg("reusing default context");
2207 default_context_refcnt++;
2208 usbi_mutex_static_unlock(&default_context_lock);
2209 return LIBUSB_SUCCESS;
2212 ctx = calloc(1, sizeof(*ctx));
2213 if (UNLIKELY(!ctx)) {
2214 r = LIBUSB_ERROR_NO_MEM;
2218 #ifdef ENABLE_DEBUG_LOGGING
2219 ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
2222 if (UNLIKELY(dbg)) {
2223 ctx->debug = atoi(dbg);
2225 ctx->debug_fixed = 1;
2228 /* default context should be initialized before calling usbi_dbg */
2229 if (!usbi_default_context) {
2230 usbi_default_context = ctx;
2231 default_context_refcnt++;
2232 usbi_dbg("created default context");
2235 usbi_dbg("libusb v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
2236 libusb_version_internal.micro, libusb_version_internal.nano);
2238 usbi_mutex_init(&ctx->usb_devs_lock, NULL);
2239 usbi_mutex_init(&ctx->open_devs_lock, NULL);
2240 usbi_mutex_init(&ctx->hotplug_cbs_lock, NULL);
2241 list_init(&ctx->usb_devs);
2242 list_init(&ctx->open_devs);
2243 list_init(&ctx->hotplug_cbs);
2245 usbi_mutex_static_lock(&active_contexts_lock);
2249 list_init(&active_contexts_list);
2251 list_add(&ctx->list, &active_contexts_list);
2253 usbi_mutex_static_unlock(&active_contexts_lock);
2255 if (usbi_backend->init) {
2256 r = usbi_backend->init(ctx);
2261 r = usbi_io_init(ctx);
2262 if (UNLIKELY(r < 0))
2263 goto err_backend_exit;
2265 usbi_mutex_static_unlock(&default_context_lock);
2270 return LIBUSB_SUCCESS;
2273 if (usbi_backend->exit)
2274 usbi_backend->exit();
2276 if (ctx == usbi_default_context)
2277 usbi_default_context = NULL;
2279 usbi_mutex_static_lock(&active_contexts_lock);
2281 list_del(&ctx->list);
2283 usbi_mutex_static_unlock(&active_contexts_lock);
2285 usbi_mutex_lock(&ctx->usb_devs_lock);
2287 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device)
2289 list_del(&dev->list);
2290 libusb_unref_device(dev);
2293 usbi_mutex_unlock(&ctx->usb_devs_lock);
2295 usbi_mutex_destroy(&ctx->open_devs_lock);
2296 usbi_mutex_destroy(&ctx->usb_devs_lock);
2297 usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2301 usbi_mutex_static_unlock(&default_context_lock);
2307 * Deinitialize libusb. Should be called after closing all open devices and
2308 * before your application terminates.
2309 * \param ctx the context to deinitialize, or NULL for the default context
2311 void API_EXPORTED libusb_exit(struct libusb_context *ctx) {
2313 struct libusb_device *dev, *next;
2314 struct timeval tv = { 0, 0 };
2317 USBI_GET_CONTEXT(ctx);
2319 /* if working with default context, only actually do the deinitialization
2320 * if we're the last user */
2321 usbi_mutex_static_lock(&default_context_lock);
2322 if (ctx == usbi_default_context) {
2323 if (--default_context_refcnt > 0) {
2324 usbi_dbg("not destroying default context");
2325 usbi_mutex_static_unlock(&default_context_lock);
2328 usbi_dbg("destroying default context");
2329 usbi_default_context = NULL;
2331 usbi_mutex_static_unlock(&default_context_lock);
2333 usbi_mutex_static_lock(&active_contexts_lock);
2335 list_del(&ctx->list);
2337 usbi_mutex_static_unlock(&active_contexts_lock);
2339 if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
2340 usbi_hotplug_deregister_all(ctx);
2343 * Ensure any pending unplug events are read from the hotplug
2344 * pipe. The usb_device-s hold in the events are no longer part
2345 * of usb_devs, but the events still hold a reference!
2347 * Note we don't do this if the application has left devices
2348 * open (which implies a buggy app) to avoid packet completion
2349 * handlers running when the app does not expect them to run.
2351 if (list_empty(&ctx->open_devs))
2352 libusb_handle_events_timeout(ctx, &tv);
2354 usbi_mutex_lock(&ctx->usb_devs_lock);
2356 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device)
2358 list_del(&dev->list);
2359 libusb_unref_device(dev);
2362 usbi_mutex_unlock(&ctx->usb_devs_lock);
2365 /* a few sanity checks. don't bother with locking because unless
2366 * there is an application bug, nobody will be accessing these. */
2367 if (!list_empty(&ctx->usb_devs))
2368 usbi_warn(ctx, "some libusb_devices were leaked");
2369 if (!list_empty(&ctx->open_devs))
2370 usbi_warn(ctx, "application left some devices open");
2373 if (usbi_backend->exit)
2374 usbi_backend->exit();
2376 usbi_mutex_destroy(&ctx->open_devs_lock);
2377 usbi_mutex_destroy(&ctx->usb_devs_lock);
2378 usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2383 * Check at runtime if the loaded library has a given capability.
2384 * This call should be performed after \ref libusb_init(), to ensure the
2385 * backend has updated its capability set.
2387 * \param capability the \ref libusb_capability to check for
2388 * \returns nonzero if the running library has the capability, 0 otherwise
2390 int API_EXPORTED libusb_has_capability(uint32_t capability) {
2392 switch (capability) {
2393 case LIBUSB_CAP_HAS_CAPABILITY:
2395 case LIBUSB_CAP_HAS_HOTPLUG:
2396 return !(usbi_backend->get_device_list);
2397 case LIBUSB_CAP_HAS_HID_ACCESS:
2398 return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS);
2399 case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
2400 return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
2402 return LIBUSB_SUCCESS;
2405 /* this is defined in libusbi.h if needed */
2406 #ifdef LIBUSB_GETTIMEOFDAY_WIN32
2409 * Implementation according to:
2410 * The Open Group Base Specifications Issue 6
2411 * IEEE Std 1003.1, 2004 Edition
2415 * THIS SOFTWARE IS NOT COPYRIGHTED
2417 * This source code is offered for use in the public domain. You may
2418 * use, modify or distribute it freely.
2420 * This code is distributed in the hope that it will be useful but
2421 * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
2422 * DISCLAIMED. This includes but is not limited to warranties of
2423 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2426 * Danny Smith <dannysmith@users.sourceforge.net>
2429 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
2430 #define _W32_FT_OFFSET (116444736000000000)
2432 int usbi_gettimeofday(struct timeval *tp, void *tzp)
2435 unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
2441 #if defined(OS_WINCE)
2444 SystemTimeToFileTime(&st, &_now.ft);
2446 GetSystemTimeAsFileTime (&_now.ft);
2448 tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
2449 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
2451 /* Always return 0 as per Open Group Base Specifications Issue 6.
2452 Do not set errno on error. */
2453 return LIBUSB_SUCCESS;
2457 static void usbi_log_str(struct libusb_context *ctx,
2458 enum libusb_log_level level, const char * str) {
2460 #if defined(USE_SYSTEM_LOGGING_FACILITY)
2461 #if defined(OS_WINDOWS) || defined(OS_WINCE)
2462 /* Windows CE only supports the Unicode version of OutputDebugString. */
2463 WCHAR wbuf[USBI_MAX_LOG_LEN];
2464 MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
2465 OutputDebugStringW(wbuf);
2466 #elif defined(__ANDROID__)
2467 int priority = ANDROID_LOG_UNKNOWN;
2469 case LIBUSB_LOG_LEVEL_NONE: break; // XXX add to avoid warning when compiling with clang
2470 case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
2471 case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
2472 case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
2473 case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
2475 __android_log_write(priority, "libusb", str);
2476 #elif defined(HAVE_SYSLOG_FUNC)
2477 int syslog_level = LOG_INFO;
2479 case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
2480 case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
2481 case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
2482 case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
2484 syslog(syslog_level, "%s", str);
2485 #else /* All of gcc, Clang, XCode seem to use #warning */
2486 #warning System logging is not supported on this platform. Logging to stderr will be used instead.
2491 #endif /* USE_SYSTEM_LOGGING_FACILITY */
2496 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
2497 const char *function, const char *format, va_list args) {
2500 const char *prefix = "";
2502 char buf[USBI_MAX_LOG_LEN];
2504 int global_debug, header_len, text_len;
2505 static int has_debug_header_been_displayed = 0;
2507 #ifdef ENABLE_DEBUG_LOGGING
2513 USBI_GET_CONTEXT(ctx);
2515 ctx_level = ctx->debug;
2517 char *dbg = getenv("LIBUSB_DEBUG");
2519 ctx_level = atoi(dbg);
2524 global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
2528 if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING)
2530 if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO)
2532 if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG)
2536 usbi_gettimeofday(&now, NULL);
2537 if ((global_debug) && (!has_debug_header_been_displayed)) {
2538 has_debug_header_been_displayed = 1;
2539 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>\n");
2540 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------\n");
2542 if (now.tv_usec < timestamp_origin.tv_usec) {
2544 now.tv_usec += 1000000;
2546 now.tv_sec -= timestamp_origin.tv_sec;
2547 now.tv_usec -= timestamp_origin.tv_usec;
2550 case LIBUSB_LOG_LEVEL_INFO:
2553 case LIBUSB_LOG_LEVEL_WARNING:
2556 case LIBUSB_LOG_LEVEL_ERROR:
2559 case LIBUSB_LOG_LEVEL_DEBUG:
2562 case LIBUSB_LOG_LEVEL_NONE:
2570 header_len = snprintf(buf, sizeof(buf), "[%s] ", function);
2573 header_len = snprintf(buf, sizeof(buf),
2574 "[%2d.%06d] [%08x] libusb: %s [%s] ", (int) now.tv_sec,
2575 (int) now.tv_usec, usbi_get_tid(), prefix, function);
2577 header_len = snprintf(buf, sizeof(buf),
2578 "libusb:%s [%s] ", prefix, function);
2582 if (header_len < 0 || header_len >= sizeof(buf)) {
2583 /* Somehow snprintf failed to write to the buffer,
2584 * remove the header so something useful is output. */
2587 /* Make sure buffer is NUL terminated */
2588 buf[header_len] = '\0';
2589 text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len, format, args);
2590 if (text_len < 0 || text_len + header_len >= sizeof(buf)) {
2591 /* Truncated log output. On some platforms a -1 return value means
2592 * that the output was truncated. */
2593 text_len = sizeof(buf) - header_len;
2595 if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
2596 /* Need to truncate the text slightly to fit on the terminator. */
2597 text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
2599 strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
2601 usbi_log_str(ctx, level, buf);
2604 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
2605 const char *function, const char *format, ...) {
2609 va_start(args, format);
2610 usbi_log_v(ctx, level, function, format, args);
2615 * Returns a constant NULL-terminated string with the ASCII name of a libusb
2616 * error or transfer status code. The caller must not free() the returned
2619 * \param error_code The \ref libusb_error or libusb_transfer_status code to
2620 * return the name of.
2621 * \returns The error name, or the string **UNKNOWN** if the value of
2622 * error_code is not a known error / status code.
2624 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code) {
2626 switch (error_code) {
2627 case LIBUSB_ERROR_IO:
2628 return "LIBUSB_ERROR_IO";
2629 case LIBUSB_ERROR_INVALID_PARAM:
2630 return "LIBUSB_ERROR_INVALID_PARAM";
2631 case LIBUSB_ERROR_ACCESS:
2632 return "LIBUSB_ERROR_ACCESS";
2633 case LIBUSB_ERROR_NO_DEVICE:
2634 return "LIBUSB_ERROR_NO_DEVICE";
2635 case LIBUSB_ERROR_NOT_FOUND:
2636 return "LIBUSB_ERROR_NOT_FOUND";
2637 case LIBUSB_ERROR_BUSY:
2638 return "LIBUSB_ERROR_BUSY";
2639 case LIBUSB_ERROR_TIMEOUT:
2640 return "LIBUSB_ERROR_TIMEOUT";
2641 case LIBUSB_ERROR_OVERFLOW:
2642 return "LIBUSB_ERROR_OVERFLOW";
2643 case LIBUSB_ERROR_PIPE:
2644 return "LIBUSB_ERROR_PIPE";
2645 case LIBUSB_ERROR_INTERRUPTED:
2646 return "LIBUSB_ERROR_INTERRUPTED";
2647 case LIBUSB_ERROR_NO_MEM:
2648 return "LIBUSB_ERROR_NO_MEM";
2649 case LIBUSB_ERROR_NOT_SUPPORTED:
2650 return "LIBUSB_ERROR_NOT_SUPPORTED";
2651 case LIBUSB_ERROR_OTHER:
2652 return "LIBUSB_ERROR_OTHER";
2654 case LIBUSB_TRANSFER_ERROR:
2655 return "LIBUSB_TRANSFER_ERROR";
2656 case LIBUSB_TRANSFER_TIMED_OUT:
2657 return "LIBUSB_TRANSFER_TIMED_OUT";
2658 case LIBUSB_TRANSFER_CANCELLED:
2659 return "LIBUSB_TRANSFER_CANCELLED";
2660 case LIBUSB_TRANSFER_STALL:
2661 return "LIBUSB_TRANSFER_STALL";
2662 case LIBUSB_TRANSFER_NO_DEVICE:
2663 return "LIBUSB_TRANSFER_NO_DEVICE";
2664 case LIBUSB_TRANSFER_OVERFLOW:
2665 return "LIBUSB_TRANSFER_OVERFLOW";
2668 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
2670 return "**UNKNOWN**";
2675 * Returns a pointer to const struct libusb_version with the version
2676 * (major, minor, micro, nano and rc) of the running library.
2679 const struct libusb_version * LIBUSB_CALL libusb_get_version(void) {
2681 return &libusb_version_internal;