Fix issue 1) not recognizes some usb device, 2) reconnect when ffmpeg encoder error
[rtmpclient.git] / app / src / main / jni / libusb-1.0.22 / libusb / core.c
1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2 /*
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>
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33 #ifdef HAVE_SYS_TIME_H
34 #include <sys/time.h>
35 #endif
36 #ifdef HAVE_SYSLOG_H
37 #include <syslog.h>
38 #endif
39
40 #ifdef __ANDROID__
41 #include <android/log.h>
42 #endif
43
44 #include "libusbi.h"
45 #include "hotplug.h"
46
47 struct libusb_context *usbi_default_context = NULL;
48 static const struct libusb_version libusb_version_internal =
49         { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
50           LIBUSB_RC, "http://libusb.info" };
51 static int default_context_refcnt = 0;
52 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
53 static struct timespec timestamp_origin = { 0, 0 };
54
55 usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
56 struct list_head active_contexts_list;
57
58 /**
59  * \mainpage libusb-1.0 API Reference
60  *
61  * \section intro Introduction
62  *
63  * libusb is an open source library that allows you to communicate with USB
64  * devices from userspace. For more info, see the
65  * <a href="http://libusb.info">libusb homepage</a>.
66  *
67  * This documentation is aimed at application developers wishing to
68  * communicate with USB peripherals from their own software. After reviewing
69  * this documentation, feedback and questions can be sent to the
70  * <a href="http://mailing-list.libusb.info">libusb-devel mailing list</a>.
71  *
72  * This documentation assumes knowledge of how to operate USB devices from
73  * a software standpoint (descriptors, configurations, interfaces, endpoints,
74  * control/bulk/interrupt/isochronous transfers, etc). Full information
75  * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
76  * Specification</a> which is available for free download. You can probably
77  * find less verbose introductions by searching the web.
78  *
79  * \section API Application Programming Interface (API)
80  *
81  * See the \ref libusb_api page for a complete list of the libusb functions.
82  *
83  * \section features Library features
84  *
85  * - All transfer types supported (control/bulk/interrupt/isochronous)
86  * - 2 transfer interfaces:
87  *    -# Synchronous (simple)
88  *    -# Asynchronous (more complicated, but more powerful)
89  * - Thread safe (although the asynchronous interface means that you
90  *   usually won't need to thread)
91  * - Lightweight with lean API
92  * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
93  * - Hotplug support (on some platforms). See \ref libusb_hotplug.
94  *
95  * \section gettingstarted Getting Started
96  *
97  * To begin reading the API documentation, start with the Modules page which
98  * links to the different categories of libusb's functionality.
99  *
100  * One decision you will have to make is whether to use the synchronous
101  * or the asynchronous data transfer interface. The \ref libusb_io documentation
102  * provides some insight into this topic.
103  *
104  * Some example programs can be found in the libusb source distribution under
105  * the "examples" subdirectory. The libusb homepage includes a list of
106  * real-life project examples which use libusb.
107  *
108  * \section errorhandling Error handling
109  *
110  * libusb functions typically return 0 on success or a negative error code
111  * on failure. These negative error codes relate to LIBUSB_ERROR constants
112  * which are listed on the \ref libusb_misc "miscellaneous" documentation page.
113  *
114  * \section msglog Debug message logging
115  *
116  * libusb uses stderr for all logging. By default, logging is set to NONE,
117  * which means that no output will be produced. However, unless the library
118  * has been compiled with logging disabled, then any application calls to
119  * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level), or the setting of the
120  * environmental variable LIBUSB_DEBUG outside of the application, can result
121  * in logging being produced. Your application should therefore not close
122  * stderr, but instead direct it to the null device if its output is
123  * undesirable.
124  *
125  * The libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) function can be
126  * used to enable logging of certain messages. Under standard configuration,
127  * libusb doesn't really log much so you are advised to use this function
128  * to enable all error/warning/ informational messages. It will help debug
129  * problems with your software.
130  *
131  * The logged messages are unstructured. There is no one-to-one correspondence
132  * between messages being logged and success or failure return codes from
133  * libusb functions. There is no format to the messages, so you should not
134  * try to capture or parse them. They are not and will not be localized.
135  * These messages are not intended to being passed to your application user;
136  * instead, you should interpret the error codes returned from libusb functions
137  * and provide appropriate notification to the user. The messages are simply
138  * there to aid you as a programmer, and if you're confused because you're
139  * getting a strange error code from a libusb function, enabling message
140  * logging may give you a suitable explanation.
141  *
142  * The LIBUSB_DEBUG environment variable can be used to enable message logging
143  * at run-time. This environment variable should be set to a log level number,
144  * which is interpreted the same as the
145  * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) parameter. When this
146  * environment variable is set, the message logging verbosity level is fixed
147  * and libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) effectively does
148  * nothing.
149  *
150  * libusb can be compiled without any logging functions, useful for embedded
151  * systems. In this case, libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level)
152  * and the LIBUSB_DEBUG environment variable have no effects.
153  *
154  * libusb can also be compiled with verbose debugging messages always. When
155  * the library is compiled in this way, all messages of all verbosities are
156  * always logged. libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) and
157  * the LIBUSB_DEBUG environment variable have no effects.
158  *
159  * \section remarks Other remarks
160  *
161  * libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts
162  * to document these.
163  */
164
165 /**
166  * \page libusb_caveats Caveats
167  *
168  * \section fork Fork considerations
169  *
170  * libusb is <em>not</em> designed to work across fork() calls. Depending on
171  * the platform, there may be resources in the parent process that are not
172  * available to the child (e.g. the hotplug monitor thread on Linux). In
173  * addition, since the parent and child will share libusb's internal file
174  * descriptors, using libusb in any way from the child could cause the parent
175  * process's \ref libusb_context to get into an inconsistent state.
176  *
177  * On Linux, libusb's file descriptors will be marked as CLOEXEC, which means
178  * that it is safe to fork() and exec() without worrying about the child
179  * process needing to clean up state or having access to these file descriptors.
180  * Other platforms may not be so forgiving, so consider yourself warned!
181  *
182  * \section devresets Device resets
183  *
184  * The libusb_reset_device() function allows you to reset a device. If your
185  * program has to call such a function, it should obviously be aware that
186  * the reset will cause device state to change (e.g. register values may be
187  * reset).
188  *
189  * The problem is that any other program could reset the device your program
190  * is working with, at any time. libusb does not offer a mechanism to inform
191  * you when this has happened, so if someone else resets your device it will
192  * not be clear to your own program why the device state has changed.
193  *
194  * Ultimately, this is a limitation of writing drivers in userspace.
195  * Separation from the USB stack in the underlying kernel makes it difficult
196  * for the operating system to deliver such notifications to your program.
197  * The Linux kernel USB stack allows such reset notifications to be delivered
198  * to in-kernel USB drivers, but it is not clear how such notifications could
199  * be delivered to second-class drivers that live in userspace.
200  *
201  * \section blockonly Blocking-only functionality
202  *
203  * The functionality listed below is only available through synchronous,
204  * blocking functions. There are no asynchronous/non-blocking alternatives,
205  * and no clear ways of implementing these.
206  *
207  * - Configuration activation (libusb_set_configuration())
208  * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
209  * - Releasing of interfaces (libusb_release_interface())
210  * - Clearing of halt/stall condition (libusb_clear_halt())
211  * - Device resets (libusb_reset_device())
212  *
213  * \section configsel Configuration selection and handling
214  *
215  * When libusb presents a device handle to an application, there is a chance
216  * that the corresponding device may be in unconfigured state. For devices
217  * with multiple configurations, there is also a chance that the configuration
218  * currently selected is not the one that the application wants to use.
219  *
220  * The obvious solution is to add a call to libusb_set_configuration() early
221  * on during your device initialization routines, but there are caveats to
222  * be aware of:
223  * -# If the device is already in the desired configuration, calling
224  *    libusb_set_configuration() using the same configuration value will cause
225  *    a lightweight device reset. This may not be desirable behaviour.
226  * -# In the case where the desired configuration is already active, libusb
227  *    may not even be able to perform a lightweight device reset. For example,
228  *    take my USB keyboard with fingerprint reader: I'm interested in driving
229  *    the fingerprint reader interface through libusb, but the kernel's
230  *    USB-HID driver will almost always have claimed the keyboard interface.
231  *    Because the kernel has claimed an interface, it is not even possible to
232  *    perform the lightweight device reset, so libusb_set_configuration() will
233  *    fail. (Luckily the device in question only has a single configuration.)
234  * -# libusb will be unable to set a configuration if other programs or
235  *    drivers have claimed interfaces. In particular, this means that kernel
236  *    drivers must be detached from all the interfaces before
237  *    libusb_set_configuration() may succeed.
238  *
239  * One solution to some of the above problems is to consider the currently
240  * active configuration. If the configuration we want is already active, then
241  * we don't have to select any configuration:
242 \code
243 cfg = -1;
244 libusb_get_configuration(dev, &cfg);
245 if (cfg != desired)
246         libusb_set_configuration(dev, desired);
247 \endcode
248  *
249  * This is probably suitable for most scenarios, but is inherently racy:
250  * another application or driver may change the selected configuration
251  * <em>after</em> the libusb_get_configuration() call.
252  *
253  * Even in cases where libusb_set_configuration() succeeds, consider that other
254  * applications or drivers may change configuration after your application
255  * calls libusb_set_configuration().
256  *
257  * One possible way to lock your device into a specific configuration is as
258  * follows:
259  * -# Set the desired configuration (or use the logic above to realise that
260  *    it is already in the desired configuration)
261  * -# Claim the interface that you wish to use
262  * -# Check that the currently active configuration is the one that you want
263  *    to use.
264  *
265  * The above method works because once an interface is claimed, no application
266  * or driver is able to select another configuration.
267  *
268  * \section earlycomp Early transfer completion
269  *
270  * NOTE: This section is currently Linux-centric. I am not sure if any of these
271  * considerations apply to Darwin or other platforms.
272  *
273  * When a transfer completes early (i.e. when less data is received/sent in
274  * any one packet than the transfer buffer allows for) then libusb is designed
275  * to terminate the transfer immediately, not transferring or receiving any
276  * more data unless other transfers have been queued by the user.
277  *
278  * On legacy platforms, libusb is unable to do this in all situations. After
279  * the incomplete packet occurs, "surplus" data may be transferred. For recent
280  * versions of libusb, this information is kept (the data length of the
281  * transfer is updated) and, for device-to-host transfers, any surplus data was
282  * added to the buffer. Still, this is not a nice solution because it loses the
283  * information about the end of the short packet, and the user probably wanted
284  * that surplus data to arrive in the next logical transfer.
285  *
286  * \section zlp Zero length packets
287  *
288  * - libusb is able to send a packet of zero length to an endpoint simply by
289  * submitting a transfer of zero length.
290  * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
291  * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
292  */
293
294 /**
295  * \page libusb_contexts Contexts
296  *
297  * It is possible that libusb may be used simultaneously from two independent
298  * libraries linked into the same executable. For example, if your application
299  * has a plugin-like system which allows the user to dynamically load a range
300  * of modules into your program, it is feasible that two independently
301  * developed modules may both use libusb.
302  *
303  * libusb is written to allow for these multiple user scenarios. The two
304  * "instances" of libusb will not interfere: libusb_set_option() calls
305  * from one user will not affect the same settings for other users, other
306  * users can continue using libusb after one of them calls libusb_exit(), etc.
307  *
308  * This is made possible through libusb's <em>context</em> concept. When you
309  * call libusb_init(), you are (optionally) given a context. You can then pass
310  * this context pointer back into future libusb functions.
311  *
312  * In order to keep things simple for more simplistic applications, it is
313  * legal to pass NULL to all functions requiring a context pointer (as long as
314  * you're sure no other code will attempt to use libusb from the same process).
315  * When you pass NULL, the default context will be used. The default context
316  * is created the first time a process calls libusb_init() when no other
317  * context is alive. Contexts are destroyed during libusb_exit().
318  *
319  * The default context is reference-counted and can be shared. That means that
320  * if libusb_init(NULL) is called twice within the same process, the two
321  * users end up sharing the same context. The deinitialization and freeing of
322  * the default context will only happen when the last user calls libusb_exit().
323  * In other words, the default context is created and initialized when its
324  * reference count goes from 0 to 1, and is deinitialized and destroyed when
325  * its reference count goes from 1 to 0.
326  *
327  * You may be wondering why only a subset of libusb functions require a
328  * context pointer in their function definition. Internally, libusb stores
329  * context pointers in other objects (e.g. libusb_device instances) and hence
330  * can infer the context from those objects.
331  */
332
333  /**
334   * \page libusb_api Application Programming Interface
335   *
336   * This is the complete list of libusb functions, structures and
337   * enumerations in alphabetical order.
338   *
339   * \section Functions
340   * - libusb_alloc_streams()
341   * - libusb_alloc_transfer()
342   * - libusb_attach_kernel_driver()
343   * - libusb_bulk_transfer()
344   * - libusb_cancel_transfer()
345   * - libusb_claim_interface()
346   * - libusb_clear_halt()
347   * - libusb_close()
348   * - libusb_control_transfer()
349   * - libusb_control_transfer_get_data()
350   * - libusb_control_transfer_get_setup()
351   * - libusb_cpu_to_le16()
352   * - libusb_detach_kernel_driver()
353   * - libusb_dev_mem_alloc()
354   * - libusb_dev_mem_free()
355   * - libusb_error_name()
356   * - libusb_event_handler_active()
357   * - libusb_event_handling_ok()
358   * - libusb_exit()
359   * - libusb_fill_bulk_stream_transfer()
360   * - libusb_fill_bulk_transfer()
361   * - libusb_fill_control_setup()
362   * - libusb_fill_control_transfer()
363   * - libusb_fill_interrupt_transfer()
364   * - libusb_fill_iso_transfer()
365   * - libusb_free_bos_descriptor()
366   * - libusb_free_config_descriptor()
367   * - libusb_free_container_id_descriptor()
368   * - libusb_free_device_list()
369   * - libusb_free_pollfds()
370   * - libusb_free_ss_endpoint_companion_descriptor()
371   * - libusb_free_ss_usb_device_capability_descriptor()
372   * - libusb_free_streams()
373   * - libusb_free_transfer()
374   * - libusb_free_usb_2_0_extension_descriptor()
375   * - libusb_get_active_config_descriptor()
376   * - libusb_get_bos_descriptor()
377   * - libusb_get_bus_number()
378   * - libusb_get_config_descriptor()
379   * - libusb_get_config_descriptor_by_value()
380   * - libusb_get_configuration()
381   * - libusb_get_container_id_descriptor()
382   * - libusb_get_descriptor()
383   * - libusb_get_device()
384   * - libusb_get_device_address()
385   * - libusb_get_device_descriptor()
386   * - libusb_get_device_list()
387   * - libusb_get_device_speed()
388   * - libusb_get_iso_packet_buffer()
389   * - libusb_get_iso_packet_buffer_simple()
390   * - libusb_get_max_iso_packet_size()
391   * - libusb_get_max_packet_size()
392   * - libusb_get_next_timeout()
393   * - libusb_get_parent()
394   * - libusb_get_pollfds()
395   * - libusb_get_port_number()
396   * - libusb_get_port_numbers()
397   * - libusb_get_port_path()
398   * - libusb_get_ss_endpoint_companion_descriptor()
399   * - libusb_get_ss_usb_device_capability_descriptor()
400   * - libusb_get_string_descriptor()
401   * - libusb_get_string_descriptor_ascii()
402   * - libusb_get_usb_2_0_extension_descriptor()
403   * - libusb_get_version()
404   * - libusb_handle_events()
405   * - libusb_handle_events_completed()
406   * - libusb_handle_events_locked()
407   * - libusb_handle_events_timeout()
408   * - libusb_handle_events_timeout_completed()
409   * - libusb_has_capability()
410   * - libusb_hotplug_deregister_callback()
411   * - libusb_hotplug_register_callback()
412   * - libusb_init()
413   * - libusb_interrupt_event_handler()
414   * - libusb_interrupt_transfer()
415   * - libusb_kernel_driver_active()
416   * - libusb_lock_events()
417   * - libusb_lock_event_waiters()
418   * - libusb_open()
419   * - libusb_open_device_with_vid_pid()
420   * - libusb_pollfds_handle_timeouts()
421   * - libusb_ref_device()
422   * - libusb_release_interface()
423   * - libusb_reset_device()
424   * - libusb_set_auto_detach_kernel_driver()
425   * - libusb_set_configuration()
426   * - libusb_set_debug()
427   * - libusb_set_interface_alt_setting()
428   * - libusb_set_iso_packet_lengths()
429   * - libusb_set_option()
430   * - libusb_setlocale()
431   * - libusb_set_pollfd_notifiers()
432   * - libusb_strerror()
433   * - libusb_submit_transfer()
434   * - libusb_transfer_get_stream_id()
435   * - libusb_transfer_set_stream_id()
436   * - libusb_try_lock_events()
437   * - libusb_unlock_events()
438   * - libusb_unlock_event_waiters()
439   * - libusb_unref_device()
440   * - libusb_wait_for_event()
441   *
442   * \section Structures
443   * - libusb_bos_descriptor
444   * - libusb_bos_dev_capability_descriptor
445   * - libusb_config_descriptor
446   * - libusb_container_id_descriptor
447   * - \ref libusb_context
448   * - libusb_control_setup
449   * - \ref libusb_device
450   * - libusb_device_descriptor
451   * - \ref libusb_device_handle
452   * - libusb_endpoint_descriptor
453   * - libusb_interface
454   * - libusb_interface_descriptor
455   * - libusb_iso_packet_descriptor
456   * - libusb_pollfd
457   * - libusb_ss_endpoint_companion_descriptor
458   * - libusb_ss_usb_device_capability_descriptor
459   * - libusb_transfer
460   * - libusb_usb_2_0_extension_descriptor
461   * - libusb_version
462   *
463   * \section Enums
464   * - \ref libusb_bos_type
465   * - \ref libusb_capability
466   * - \ref libusb_class_code
467   * - \ref libusb_descriptor_type
468   * - \ref libusb_endpoint_direction
469   * - \ref libusb_error
470   * - \ref libusb_iso_sync_type
471   * - \ref libusb_iso_usage_type
472   * - \ref libusb_log_level
473   * - \ref libusb_option
474   * - \ref libusb_request_recipient
475   * - \ref libusb_request_type
476   * - \ref libusb_speed
477   * - \ref libusb_ss_usb_device_capability_attributes
478   * - \ref libusb_standard_request
479   * - \ref libusb_supported_speed
480   * - \ref libusb_transfer_flags
481   * - \ref libusb_transfer_status
482   * - \ref libusb_transfer_type
483   * - \ref libusb_usb_2_0_extension_attributes
484   */
485
486 /**
487  * @defgroup libusb_lib Library initialization/deinitialization
488  * This page details how to initialize and deinitialize libusb. Initialization
489  * must be performed before using any libusb functionality, and similarly you
490  * must not call any libusb functions after deinitialization.
491  */
492
493 /**
494  * @defgroup libusb_dev Device handling and enumeration
495  * The functionality documented below is designed to help with the following
496  * operations:
497  * - Enumerating the USB devices currently attached to the system
498  * - Choosing a device to operate from your software
499  * - Opening and closing the chosen device
500  *
501  * \section nutshell In a nutshell...
502  *
503  * The description below really makes things sound more complicated than they
504  * actually are. The following sequence of function calls will be suitable
505  * for almost all scenarios and does not require you to have such a deep
506  * understanding of the resource management issues:
507  * \code
508 // discover devices
509 libusb_device **list;
510 libusb_device *found = NULL;
511 ssize_t cnt = libusb_get_device_list(NULL, &list);
512 ssize_t i = 0;
513 int err = 0;
514 if (cnt < 0)
515         error();
516
517 for (i = 0; i < cnt; i++) {
518         libusb_device *device = list[i];
519         if (is_interesting(device)) {
520                 found = device;
521                 break;
522         }
523 }
524
525 if (found) {
526         libusb_device_handle *handle;
527
528         err = libusb_open(found, &handle);
529         if (err)
530                 error();
531         // etc
532 }
533
534 libusb_free_device_list(list, 1);
535 \endcode
536  *
537  * The two important points:
538  * - You asked libusb_free_device_list() to unreference the devices (2nd
539  *   parameter)
540  * - You opened the device before freeing the list and unreferencing the
541  *   devices
542  *
543  * If you ended up with a handle, you can now proceed to perform I/O on the
544  * device.
545  *
546  * \section devshandles Devices and device handles
547  * libusb has a concept of a USB device, represented by the
548  * \ref libusb_device opaque type. A device represents a USB device that
549  * is currently or was previously connected to the system. Using a reference
550  * to a device, you can determine certain information about the device (e.g.
551  * you can read the descriptor data).
552  *
553  * The libusb_get_device_list() function can be used to obtain a list of
554  * devices currently connected to the system. This is known as device
555  * discovery.
556  *
557  * Just because you have a reference to a device does not mean it is
558  * necessarily usable. The device may have been unplugged, you may not have
559  * permission to operate such device, or another program or driver may be
560  * using the device.
561  *
562  * When you've found a device that you'd like to operate, you must ask
563  * libusb to open the device using the libusb_open() function. Assuming
564  * success, libusb then returns you a <em>device handle</em>
565  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
566  * operate on the handle rather than the original device pointer.
567  *
568  * \section devref Device discovery and reference counting
569  *
570  * Device discovery (i.e. calling libusb_get_device_list()) returns a
571  * freshly-allocated list of devices. The list itself must be freed when
572  * you are done with it. libusb also needs to know when it is OK to free
573  * the contents of the list - the devices themselves.
574  *
575  * To handle these issues, libusb provides you with two separate items:
576  * - A function to free the list itself
577  * - A reference counting system for the devices inside
578  *
579  * New devices presented by the libusb_get_device_list() function all have a
580  * reference count of 1. You can increase and decrease reference count using
581  * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
582  * its reference count reaches 0.
583  *
584  * With the above information in mind, the process of opening a device can
585  * be viewed as follows:
586  * -# Discover devices using libusb_get_device_list().
587  * -# Choose the device that you want to operate, and call libusb_open().
588  * -# Unref all devices in the discovered device list.
589  * -# Free the discovered device list.
590  *
591  * The order is important - you must not unreference the device before
592  * attempting to open it, because unreferencing it may destroy the device.
593  *
594  * For convenience, the libusb_free_device_list() function includes a
595  * parameter to optionally unreference all the devices in the list before
596  * freeing the list itself. This combines steps 3 and 4 above.
597  *
598  * As an implementation detail, libusb_open() actually adds a reference to
599  * the device in question. This is because the device remains available
600  * through the handle via libusb_get_device(). The reference is deleted during
601  * libusb_close().
602  */
603
604 /** @defgroup libusb_misc Miscellaneous */
605
606 /* we traverse usbfs without knowing how many devices we are going to find.
607  * so we create this discovered_devs model which is similar to a linked-list
608  * which grows when required. it can be freed once discovery has completed,
609  * eliminating the need for a list node in the libusb_device structure
610  * itself. */
611 #define DISCOVERED_DEVICES_SIZE_STEP 8
612
613 static struct discovered_devs *discovered_devs_alloc(void)
614 {
615         struct discovered_devs *ret =
616                 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
617
618         if (ret) {
619                 ret->len = 0;
620                 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
621         }
622         return ret;
623 }
624
625 static void discovered_devs_free(struct discovered_devs *discdevs)
626 {
627         size_t i;
628
629         for (i = 0; i < discdevs->len; i++)
630                 libusb_unref_device(discdevs->devices[i]);
631
632         free(discdevs);
633 }
634
635 /* append a device to the discovered devices collection. may realloc itself,
636  * returning new discdevs. returns NULL on realloc failure. */
637 struct discovered_devs *discovered_devs_append(
638         struct discovered_devs *discdevs, struct libusb_device *dev)
639 {
640         size_t len = discdevs->len;
641         size_t capacity;
642         struct discovered_devs *new_discdevs;
643
644         /* if there is space, just append the device */
645         if (len < discdevs->capacity) {
646                 discdevs->devices[len] = libusb_ref_device(dev);
647                 discdevs->len++;
648                 return discdevs;
649         }
650
651         /* exceeded capacity, need to grow */
652         usbi_dbg("need to increase capacity");
653         capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
654         /* can't use usbi_reallocf here because in failure cases it would
655          * free the existing discdevs without unreferencing its devices. */
656         new_discdevs = realloc(discdevs,
657                 sizeof(*discdevs) + (sizeof(void *) * capacity));
658         if (!new_discdevs) {
659                 discovered_devs_free(discdevs);
660                 return NULL;
661         }
662
663         discdevs = new_discdevs;
664         discdevs->capacity = capacity;
665         discdevs->devices[len] = libusb_ref_device(dev);
666         discdevs->len++;
667
668         return discdevs;
669 }
670
671 /* Allocate a new device with a specific session ID. The returned device has
672  * a reference count of 1. */
673 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
674         unsigned long session_id)
675 {
676         size_t priv_size = usbi_backend.device_priv_size;
677         struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
678         int r;
679
680         if (!dev)
681                 return NULL;
682
683         r = usbi_mutex_init(&dev->lock);
684         if (r) {
685                 free(dev);
686                 return NULL;
687         }
688
689         dev->ctx = ctx;
690         dev->refcnt = 1;
691         dev->session_data = session_id;
692         dev->speed = LIBUSB_SPEED_UNKNOWN;
693
694         if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
695                 usbi_connect_device (dev);
696         }
697
698         return dev;
699 }
700
701 void usbi_connect_device(struct libusb_device *dev)
702 {
703         struct libusb_context *ctx = DEVICE_CTX(dev);
704
705         dev->attached = 1;
706
707         usbi_mutex_lock(&dev->ctx->usb_devs_lock);
708         list_add(&dev->list, &dev->ctx->usb_devs);
709         usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
710
711         /* Signal that an event has occurred for this device if we support hotplug AND
712          * the hotplug message list is ready. This prevents an event from getting raised
713          * during initial enumeration. */
714         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
715                 usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED);
716         }
717 }
718
719 void usbi_disconnect_device(struct libusb_device *dev)
720 {
721         struct libusb_context *ctx = DEVICE_CTX(dev);
722
723         usbi_mutex_lock(&dev->lock);
724         dev->attached = 0;
725         usbi_mutex_unlock(&dev->lock);
726
727         usbi_mutex_lock(&ctx->usb_devs_lock);
728         list_del(&dev->list);
729         usbi_mutex_unlock(&ctx->usb_devs_lock);
730
731         /* Signal that an event has occurred for this device if we support hotplug AND
732          * the hotplug message list is ready. This prevents an event from getting raised
733          * during initial enumeration. libusb_handle_events will take care of dereferencing
734          * the device. */
735         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
736                 usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);
737         }
738 }
739
740 /* Perform some final sanity checks on a newly discovered device. If this
741  * function fails (negative return code), the device should not be added
742  * to the discovered device list. */
743 int usbi_sanitize_device(struct libusb_device *dev)
744 {
745         int r;
746         uint8_t num_configurations;
747
748         r = usbi_device_cache_descriptor(dev);
749         if (r < 0)
750                 return r;
751
752         num_configurations = dev->device_descriptor.bNumConfigurations;
753         if (num_configurations > USB_MAXCONFIG) {
754                 usbi_err(DEVICE_CTX(dev), "too many configurations");
755                 return LIBUSB_ERROR_IO;
756         } else if (0 == num_configurations)
757                 usbi_dbg("zero configurations, maybe an unauthorized device");
758
759         dev->num_configurations = num_configurations;
760         return 0;
761 }
762
763 /* Examine libusb's internal list of known devices, looking for one with
764  * a specific session ID. Returns the matching device if it was found, and
765  * NULL otherwise. */
766 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
767         unsigned long session_id)
768 {
769         struct libusb_device *dev;
770         struct libusb_device *ret = NULL;
771
772         usbi_mutex_lock(&ctx->usb_devs_lock);
773         list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
774                 if (dev->session_data == session_id) {
775                         ret = libusb_ref_device(dev);
776                         break;
777                 }
778         usbi_mutex_unlock(&ctx->usb_devs_lock);
779
780         return ret;
781 }
782
783 /** @ingroup libusb_dev
784  * Returns a list of USB devices currently attached to the system. This is
785  * your entry point into finding a USB device to operate.
786  *
787  * You are expected to unreference all the devices when you are done with
788  * them, and then free the list with libusb_free_device_list(). Note that
789  * libusb_free_device_list() can unref all the devices for you. Be careful
790  * not to unreference a device you are about to open until after you have
791  * opened it.
792  *
793  * This return value of this function indicates the number of devices in
794  * the resultant list. The list is actually one element larger, as it is
795  * NULL-terminated.
796  *
797  * \param ctx the context to operate on, or NULL for the default context
798  * \param list output location for a list of devices. Must be later freed with
799  * libusb_free_device_list().
800  * \returns the number of devices in the outputted list, or any
801  * \ref libusb_error according to errors encountered by the backend.
802  */
803 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
804         libusb_device ***list)
805 {
806         struct discovered_devs *discdevs = discovered_devs_alloc();
807         struct libusb_device **ret;
808         int r = 0;
809         ssize_t i, len;
810         USBI_GET_CONTEXT(ctx);
811         usbi_dbg("");
812
813         if (!discdevs)
814                 return LIBUSB_ERROR_NO_MEM;
815
816         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
817                 /* backend provides hotplug support */
818                 struct libusb_device *dev;
819
820                 if (usbi_backend.hotplug_poll)
821                         usbi_backend.hotplug_poll();
822
823                 usbi_mutex_lock(&ctx->usb_devs_lock);
824                 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
825                         discdevs = discovered_devs_append(discdevs, dev);
826
827                         if (!discdevs) {
828                                 r = LIBUSB_ERROR_NO_MEM;
829                                 break;
830                         }
831                 }
832                 usbi_mutex_unlock(&ctx->usb_devs_lock);
833         } else {
834                 /* backend does not provide hotplug support */
835                 r = usbi_backend.get_device_list(ctx, &discdevs);
836         }
837
838         if (r < 0) {
839                 len = r;
840                 goto out;
841         }
842
843         /* convert discovered_devs into a list */
844         len = discdevs->len;
845         ret = calloc(len + 1, sizeof(struct libusb_device *));
846         if (!ret) {
847                 len = LIBUSB_ERROR_NO_MEM;
848                 goto out;
849         }
850
851         ret[len] = NULL;
852         for (i = 0; i < len; i++) {
853                 struct libusb_device *dev = discdevs->devices[i];
854                 ret[i] = libusb_ref_device(dev);
855         }
856         *list = ret;
857
858 out:
859         if (discdevs)
860                 discovered_devs_free(discdevs);
861         return len;
862 }
863
864 /** \ingroup libusb_dev
865  * Frees a list of devices previously discovered using
866  * libusb_get_device_list(). If the unref_devices parameter is set, the
867  * reference count of each device in the list is decremented by 1.
868  * \param list the list to free
869  * \param unref_devices whether to unref the devices in the list
870  */
871 void API_EXPORTED libusb_free_device_list(libusb_device **list,
872         int unref_devices)
873 {
874         if (!list)
875                 return;
876
877         if (unref_devices) {
878                 int i = 0;
879                 struct libusb_device *dev;
880
881                 while ((dev = list[i++]) != NULL)
882                         libusb_unref_device(dev);
883         }
884         free(list);
885 }
886
887 /** \ingroup libusb_dev
888  * Get the number of the bus that a device is connected to.
889  * \param dev a device
890  * \returns the bus number
891  */
892 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
893 {
894         return dev->bus_number;
895 }
896
897 /** \ingroup libusb_dev
898  * Get the number of the port that a device is connected to.
899  * Unless the OS does something funky, or you are hot-plugging USB extension cards,
900  * the port number returned by this call is usually guaranteed to be uniquely tied
901  * to a physical port, meaning that different devices plugged on the same physical
902  * port should return the same port number.
903  *
904  * But outside of this, there is no guarantee that the port number returned by this
905  * call will remain the same, or even match the order in which ports have been
906  * numbered by the HUB/HCD manufacturer.
907  *
908  * \param dev a device
909  * \returns the port number (0 if not available)
910  */
911 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
912 {
913         return dev->port_number;
914 }
915
916 /** \ingroup libusb_dev
917  * Get the list of all port numbers from root for the specified device
918  *
919  * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
920  * \param dev a device
921  * \param port_numbers the array that should contain the port numbers
922  * \param port_numbers_len the maximum length of the array. As per the USB 3.0
923  * specs, the current maximum limit for the depth is 7.
924  * \returns the number of elements filled
925  * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
926  */
927 int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
928         uint8_t* port_numbers, int port_numbers_len)
929 {
930         int i = port_numbers_len;
931         struct libusb_context *ctx = DEVICE_CTX(dev);
932
933         if (port_numbers_len <= 0)
934                 return LIBUSB_ERROR_INVALID_PARAM;
935
936         // HCDs can be listed as devices with port #0
937         while((dev) && (dev->port_number != 0)) {
938                 if (--i < 0) {
939                         usbi_warn(ctx, "port numbers array is too small");
940                         return LIBUSB_ERROR_OVERFLOW;
941                 }
942                 port_numbers[i] = dev->port_number;
943                 dev = dev->parent_dev;
944         }
945         if (i < port_numbers_len)
946                 memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
947         return port_numbers_len - i;
948 }
949
950 /** \ingroup libusb_dev
951  * Deprecated please use libusb_get_port_numbers instead.
952  */
953 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
954         uint8_t* port_numbers, uint8_t port_numbers_len)
955 {
956         UNUSED(ctx);
957
958         return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
959 }
960
961 /** \ingroup libusb_dev
962  * Get the the parent from the specified device.
963  * \param dev a device
964  * \returns the device parent or NULL if not available
965  * You should issue a \ref libusb_get_device_list() before calling this
966  * function and make sure that you only access the parent before issuing
967  * \ref libusb_free_device_list(). The reason is that libusb currently does
968  * not maintain a permanent list of device instances, and therefore can
969  * only guarantee that parents are fully instantiated within a 
970  * libusb_get_device_list() - libusb_free_device_list() block.
971  */
972 DEFAULT_VISIBILITY
973 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
974 {
975         return dev->parent_dev;
976 }
977
978 /** \ingroup libusb_dev
979  * Get the address of the device on the bus it is connected to.
980  * \param dev a device
981  * \returns the device address
982  */
983 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
984 {
985         return dev->device_address;
986 }
987
988 /** \ingroup libusb_dev
989  * Get the negotiated connection speed for a device.
990  * \param dev a device
991  * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
992  * the OS doesn't know or doesn't support returning the negotiated speed.
993  */
994 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
995 {
996         return dev->speed;
997 }
998
999 static const struct libusb_endpoint_descriptor *find_endpoint(
1000         struct libusb_config_descriptor *config, unsigned char endpoint)
1001 {
1002         int iface_idx;
1003         for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
1004                 const struct libusb_interface *iface = &config->interface[iface_idx];
1005                 int altsetting_idx;
1006
1007                 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
1008                                 altsetting_idx++) {
1009                         const struct libusb_interface_descriptor *altsetting
1010                                 = &iface->altsetting[altsetting_idx];
1011                         int ep_idx;
1012
1013                         for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
1014                                 const struct libusb_endpoint_descriptor *ep =
1015                                         &altsetting->endpoint[ep_idx];
1016                                 if (ep->bEndpointAddress == endpoint)
1017                                         return ep;
1018                         }
1019                 }
1020         }
1021         return NULL;
1022 }
1023
1024 /** \ingroup libusb_dev
1025  * Convenience function to retrieve the wMaxPacketSize value for a particular
1026  * endpoint in the active device configuration.
1027  *
1028  * This function was originally intended to be of assistance when setting up
1029  * isochronous transfers, but a design mistake resulted in this function
1030  * instead. It simply returns the wMaxPacketSize value without considering
1031  * its contents. If you're dealing with isochronous transfers, you probably
1032  * want libusb_get_max_iso_packet_size() instead.
1033  *
1034  * \param dev a device
1035  * \param endpoint address of the endpoint in question
1036  * \returns the wMaxPacketSize value
1037  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1038  * \returns LIBUSB_ERROR_OTHER on other failure
1039  */
1040 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
1041         unsigned char endpoint)
1042 {
1043         struct libusb_config_descriptor *config;
1044         const struct libusb_endpoint_descriptor *ep;
1045         int r;
1046
1047         r = libusb_get_active_config_descriptor(dev, &config);
1048         if (r < 0) {
1049                 usbi_err(DEVICE_CTX(dev),
1050                         "could not retrieve active config descriptor");
1051                 return LIBUSB_ERROR_OTHER;
1052         }
1053
1054         ep = find_endpoint(config, endpoint);
1055         if (!ep) {
1056                 r = LIBUSB_ERROR_NOT_FOUND;
1057                 goto out;
1058         }
1059
1060         r = ep->wMaxPacketSize;
1061
1062 out:
1063         libusb_free_config_descriptor(config);
1064         return r;
1065 }
1066
1067 /** \ingroup libusb_dev
1068  * Calculate the maximum packet size which a specific endpoint is capable is
1069  * sending or receiving in the duration of 1 microframe
1070  *
1071  * Only the active configuration is examined. The calculation is based on the
1072  * wMaxPacketSize field in the endpoint descriptor as described in section
1073  * 9.6.6 in the USB 2.0 specifications.
1074  *
1075  * If acting on an isochronous or interrupt endpoint, this function will
1076  * multiply the value found in bits 0:10 by the number of transactions per
1077  * microframe (determined by bits 11:12). Otherwise, this function just
1078  * returns the numeric value found in bits 0:10.
1079  *
1080  * This function is useful for setting up isochronous transfers, for example
1081  * you might pass the return value from this function to
1082  * libusb_set_iso_packet_lengths() in order to set the length field of every
1083  * isochronous packet in a transfer.
1084  *
1085  * Since v1.0.3.
1086  *
1087  * \param dev a device
1088  * \param endpoint address of the endpoint in question
1089  * \returns the maximum packet size which can be sent/received on this endpoint
1090  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1091  * \returns LIBUSB_ERROR_OTHER on other failure
1092  */
1093 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
1094         unsigned char endpoint)
1095 {
1096         struct libusb_config_descriptor *config;
1097         const struct libusb_endpoint_descriptor *ep;
1098         enum libusb_transfer_type ep_type;
1099         uint16_t val;
1100         int r;
1101
1102         r = libusb_get_active_config_descriptor(dev, &config);
1103         if (r < 0) {
1104                 usbi_err(DEVICE_CTX(dev),
1105                         "could not retrieve active config descriptor");
1106                 return LIBUSB_ERROR_OTHER;
1107         }
1108
1109         ep = find_endpoint(config, endpoint);
1110         if (!ep) {
1111                 r = LIBUSB_ERROR_NOT_FOUND;
1112                 goto out;
1113         }
1114
1115         val = ep->wMaxPacketSize;
1116         ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
1117
1118         r = val & 0x07ff;
1119         if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
1120                         || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1121                 r *= (1 + ((val >> 11) & 3));
1122
1123 out:
1124         libusb_free_config_descriptor(config);
1125         return r;
1126 }
1127
1128 /** \ingroup libusb_dev
1129  * Increment the reference count of a device.
1130  * \param dev the device to reference
1131  * \returns the same device
1132  */
1133 DEFAULT_VISIBILITY
1134 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
1135 {
1136         usbi_mutex_lock(&dev->lock);
1137         dev->refcnt++;
1138         usbi_mutex_unlock(&dev->lock);
1139         return dev;
1140 }
1141
1142 /** \ingroup libusb_dev
1143  * Decrement the reference count of a device. If the decrement operation
1144  * causes the reference count to reach zero, the device shall be destroyed.
1145  * \param dev the device to unreference
1146  */
1147 void API_EXPORTED libusb_unref_device(libusb_device *dev)
1148 {
1149         int refcnt;
1150
1151         if (!dev)
1152                 return;
1153
1154         usbi_mutex_lock(&dev->lock);
1155         refcnt = --dev->refcnt;
1156         usbi_mutex_unlock(&dev->lock);
1157
1158         if (refcnt == 0) {
1159                 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
1160
1161                 libusb_unref_device(dev->parent_dev);
1162
1163                 if (usbi_backend.destroy_device)
1164                         usbi_backend.destroy_device(dev);
1165
1166                 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1167                         /* backend does not support hotplug */
1168                         usbi_disconnect_device(dev);
1169                 }
1170
1171                 usbi_mutex_destroy(&dev->lock);
1172                 free(dev);
1173         }
1174 }
1175
1176 /*
1177  * Signal the event pipe so that the event handling thread will be
1178  * interrupted to process an internal event.
1179  */
1180 int usbi_signal_event(struct libusb_context *ctx)
1181 {
1182         unsigned char dummy = 1;
1183         ssize_t r;
1184
1185         /* write some data on event pipe to interrupt event handlers */
1186         r = usbi_write(ctx->event_pipe[1], &dummy, sizeof(dummy));
1187         if (r != sizeof(dummy)) {
1188                 usbi_warn(ctx, "internal signalling write failed");
1189                 return LIBUSB_ERROR_IO;
1190         }
1191
1192         return 0;
1193 }
1194
1195 /*
1196  * Clear the event pipe so that the event handling will no longer be
1197  * interrupted.
1198  */
1199 int usbi_clear_event(struct libusb_context *ctx)
1200 {
1201         unsigned char dummy;
1202         ssize_t r;
1203
1204         /* read some data on event pipe to clear it */
1205         r = usbi_read(ctx->event_pipe[0], &dummy, sizeof(dummy));
1206         if (r != sizeof(dummy)) {
1207                 usbi_warn(ctx, "internal signalling read failed");
1208                 return LIBUSB_ERROR_IO;
1209         }
1210
1211         return 0;
1212 }
1213
1214 libusb_device * LIBUSB_CALL libusb_get_device_with_fd(libusb_context *ctx,
1215         int vid, int pid, const char *serial, int fd, int busnum, int devaddr) {
1216         usbi_dbg("libusb_get_device_with_fd, fd:%d, serial:%s", fd, serial);
1217
1218         struct libusb_device *device = NULL;
1219         // android_generate_device内でusbi_alloc_deviceが呼ばれた時に参照カウンタは1
1220         int ret = linux_generate_device(ctx, &device, vid, pid, serial, fd, busnum, devaddr);
1221         if (ret) {
1222                 usbi_err(ctx, "libusb_get_device_with_fd");
1223                 device = NULL;
1224         }
1225         return device;
1226 }
1227
1228
1229 /** \ingroup libusb_dev
1230  * Open a device and obtain a device handle. A handle allows you to perform
1231  * I/O on the device in question.
1232  *
1233  * Internally, this function adds a reference to the device and makes it
1234  * available to you through libusb_get_device(). This reference is removed
1235  * during libusb_close().
1236  *
1237  * This is a non-blocking function; no requests are sent over the bus.
1238  *
1239  * \param dev the device to open
1240  * \param dev_handle output location for the returned device handle pointer. Only
1241  * populated when the return code is 0.
1242  * \returns 0 on success
1243  * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
1244  * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1245  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1246  * \returns another LIBUSB_ERROR code on other failure
1247  */
1248 int API_EXPORTED libusb_open(libusb_device *dev,
1249         libusb_device_handle **dev_handle)
1250 {
1251         struct libusb_context *ctx = DEVICE_CTX(dev);
1252         struct libusb_device_handle *_dev_handle;
1253         size_t priv_size = usbi_backend.device_handle_priv_size;
1254         int r;
1255         usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
1256         __android_log_write(ANDROID_LOG_ERROR, "libusb", "haha");
1257
1258         if (!dev->attached) {
1259                 return LIBUSB_ERROR_NO_DEVICE;
1260         }
1261
1262         _dev_handle = malloc(sizeof(*_dev_handle) + priv_size);
1263         if (!_dev_handle)
1264                 return LIBUSB_ERROR_NO_MEM;
1265
1266         r = usbi_mutex_init(&_dev_handle->lock);
1267         if (r) {
1268                 free(_dev_handle);
1269                 return LIBUSB_ERROR_OTHER;
1270         }
1271
1272         _dev_handle->dev = libusb_ref_device(dev);
1273         _dev_handle->auto_detach_kernel_driver = 0;
1274         _dev_handle->claimed_interfaces = 0;
1275         memset(&_dev_handle->os_priv, 0, priv_size);
1276
1277         r = usbi_backend.open(_dev_handle);
1278         if (r < 0) {
1279                 usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
1280                 libusb_unref_device(dev);
1281                 usbi_mutex_destroy(&_dev_handle->lock);
1282                 free(_dev_handle);
1283                 return r;
1284         }
1285
1286         usbi_mutex_lock(&ctx->open_devs_lock);
1287         list_add(&_dev_handle->list, &ctx->open_devs);
1288         usbi_mutex_unlock(&ctx->open_devs_lock);
1289         *dev_handle = _dev_handle;
1290
1291         return 0;
1292 }
1293
1294 /** \ingroup libusb_dev
1295  * Convenience function for finding a device with a particular
1296  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1297  * for those scenarios where you are using libusb to knock up a quick test
1298  * application - it allows you to avoid calling libusb_get_device_list() and
1299  * worrying about traversing/freeing the list.
1300  *
1301  * This function has limitations and is hence not intended for use in real
1302  * applications: if multiple devices have the same IDs it will only
1303  * give you the first one, etc.
1304  *
1305  * \param ctx the context to operate on, or NULL for the default context
1306  * \param vendor_id the idVendor value to search for
1307  * \param product_id the idProduct value to search for
1308  * \returns a device handle for the first found device, or NULL on error
1309  * or if the device could not be found. */
1310 DEFAULT_VISIBILITY
1311 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1312         libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1313 {
1314         struct libusb_device **devs;
1315         struct libusb_device *found = NULL;
1316         struct libusb_device *dev;
1317         struct libusb_device_handle *dev_handle = NULL;
1318         size_t i = 0;
1319         int r;
1320
1321         if (libusb_get_device_list(ctx, &devs) < 0)
1322                 return NULL;
1323
1324         while ((dev = devs[i++]) != NULL) {
1325                 struct libusb_device_descriptor desc;
1326                 r = libusb_get_device_descriptor(dev, &desc);
1327                 if (r < 0)
1328                         goto out;
1329                 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1330                         found = dev;
1331                         break;
1332                 }
1333         }
1334
1335         if (found) {
1336                 r = libusb_open(found, &dev_handle);
1337                 if (r < 0)
1338                         dev_handle = NULL;
1339         }
1340
1341 out:
1342         libusb_free_device_list(devs, 1);
1343         return dev_handle;
1344 }
1345
1346 static void do_close(struct libusb_context *ctx,
1347         struct libusb_device_handle *dev_handle)
1348 {
1349         struct usbi_transfer *itransfer;
1350         struct usbi_transfer *tmp;
1351
1352         /* remove any transfers in flight that are for this device */
1353         usbi_mutex_lock(&ctx->flying_transfers_lock);
1354
1355         /* safe iteration because transfers may be being deleted */
1356         list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
1357                 struct libusb_transfer *transfer =
1358                         USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1359
1360                 if (transfer->dev_handle != dev_handle)
1361                         continue;
1362
1363                 usbi_mutex_lock(&itransfer->lock);
1364                 if (!(itransfer->state_flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1365                         usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1366
1367                         if (itransfer->state_flags & USBI_TRANSFER_CANCELLING)
1368                                 usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1369                         else
1370                                 usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1371                 }
1372                 usbi_mutex_unlock(&itransfer->lock);
1373
1374                 /* remove from the list of in-flight transfers and make sure
1375                  * we don't accidentally use the device handle in the future
1376                  * (or that such accesses will be easily caught and identified as a crash)
1377                  */
1378                 list_del(&itransfer->list);
1379                 transfer->dev_handle = NULL;
1380
1381                 /* it is up to the user to free up the actual transfer struct.  this is
1382                  * just making sure that we don't attempt to process the transfer after
1383                  * the device handle is invalid
1384                  */
1385                 usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
1386                          transfer, dev_handle);
1387         }
1388         usbi_mutex_unlock(&ctx->flying_transfers_lock);
1389
1390         usbi_mutex_lock(&ctx->open_devs_lock);
1391         list_del(&dev_handle->list);
1392         usbi_mutex_unlock(&ctx->open_devs_lock);
1393
1394         usbi_backend.close(dev_handle);
1395         libusb_unref_device(dev_handle->dev);
1396         usbi_mutex_destroy(&dev_handle->lock);
1397         free(dev_handle);
1398 }
1399
1400 /** \ingroup libusb_dev
1401  * Close a device handle. Should be called on all open handles before your
1402  * application exits.
1403  *
1404  * Internally, this function destroys the reference that was added by
1405  * libusb_open() on the given device.
1406  *
1407  * This is a non-blocking function; no requests are sent over the bus.
1408  *
1409  * \param dev_handle the device handle to close
1410  */
1411 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1412 {
1413         struct libusb_context *ctx;
1414         int handling_events;
1415         int pending_events;
1416
1417         if (!dev_handle)
1418                 return;
1419         usbi_dbg("");
1420
1421         ctx = HANDLE_CTX(dev_handle);
1422         handling_events = usbi_handling_events(ctx);
1423
1424         /* Similarly to libusb_open(), we want to interrupt all event handlers
1425          * at this point. More importantly, we want to perform the actual close of
1426          * the device while holding the event handling lock (preventing any other
1427          * thread from doing event handling) because we will be removing a file
1428          * descriptor from the polling loop. If this is being called by the current
1429          * event handler, we can bypass the interruption code because we already
1430          * hold the event handling lock. */
1431
1432         if (!handling_events) {
1433                 /* Record that we are closing a device.
1434                  * Only signal an event if there are no prior pending events. */
1435                 usbi_mutex_lock(&ctx->event_data_lock);
1436                 pending_events = usbi_pending_events(ctx);
1437                 ctx->device_close++;
1438                 if (!pending_events)
1439                         usbi_signal_event(ctx);
1440                 usbi_mutex_unlock(&ctx->event_data_lock);
1441
1442                 /* take event handling lock */
1443                 libusb_lock_events(ctx);
1444         }
1445
1446         /* Close the device */
1447         do_close(ctx, dev_handle);
1448
1449         if (!handling_events) {
1450                 /* We're done with closing this device.
1451                  * Clear the event pipe if there are no further pending events. */
1452                 usbi_mutex_lock(&ctx->event_data_lock);
1453                 ctx->device_close--;
1454                 pending_events = usbi_pending_events(ctx);
1455                 if (!pending_events)
1456                         usbi_clear_event(ctx);
1457                 usbi_mutex_unlock(&ctx->event_data_lock);
1458
1459                 /* Release event handling lock and wake up event waiters */
1460                 libusb_unlock_events(ctx);
1461         }
1462 }
1463
1464 /** \ingroup libusb_dev
1465  * Get the underlying device for a device handle. This function does not modify
1466  * the reference count of the returned device, so do not feel compelled to
1467  * unreference it when you are done.
1468  * \param dev_handle a device handle
1469  * \returns the underlying device
1470  */
1471 DEFAULT_VISIBILITY
1472 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1473 {
1474         return dev_handle->dev;
1475 }
1476
1477 /** \ingroup libusb_dev
1478  * Determine the bConfigurationValue of the currently active configuration.
1479  *
1480  * You could formulate your own control request to obtain this information,
1481  * but this function has the advantage that it may be able to retrieve the
1482  * information from operating system caches (no I/O involved).
1483  *
1484  * If the OS does not cache this information, then this function will block
1485  * while a control transfer is submitted to retrieve the information.
1486  *
1487  * This function will return a value of 0 in the <tt>config</tt> output
1488  * parameter if the device is in unconfigured state.
1489  *
1490  * \param dev_handle a device handle
1491  * \param config output location for the bConfigurationValue of the active
1492  * configuration (only valid for return code 0)
1493  * \returns 0 on success
1494  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1495  * \returns another LIBUSB_ERROR code on other failure
1496  */
1497 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev_handle,
1498         int *config)
1499 {
1500         int r = LIBUSB_ERROR_NOT_SUPPORTED;
1501
1502         usbi_dbg("");
1503         if (usbi_backend.get_configuration)
1504                 r = usbi_backend.get_configuration(dev_handle, config);
1505
1506         if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1507                 uint8_t tmp = 0;
1508                 usbi_dbg("falling back to control message");
1509                 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
1510                         LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1511                 if (r == 0) {
1512                         usbi_err(HANDLE_CTX(dev_handle), "zero bytes returned in ctrl transfer?");
1513                         r = LIBUSB_ERROR_IO;
1514                 } else if (r == 1) {
1515                         r = 0;
1516                         *config = tmp;
1517                 } else {
1518                         usbi_dbg("control failed, error %d", r);
1519                 }
1520         }
1521
1522         if (r == 0)
1523                 usbi_dbg("active config %d", *config);
1524
1525         return r;
1526 }
1527
1528 /** \ingroup libusb_dev
1529  * Set the active configuration for a device.
1530  *
1531  * The operating system may or may not have already set an active
1532  * configuration on the device. It is up to your application to ensure the
1533  * correct configuration is selected before you attempt to claim interfaces
1534  * and perform other operations.
1535  *
1536  * If you call this function on a device already configured with the selected
1537  * configuration, then this function will act as a lightweight device reset:
1538  * it will issue a SET_CONFIGURATION request using the current configuration,
1539  * causing most USB-related device state to be reset (altsetting reset to zero,
1540  * endpoint halts cleared, toggles reset).
1541  *
1542  * You cannot change/reset configuration if your application has claimed
1543  * interfaces. It is advised to set the desired configuration before claiming
1544  * interfaces.
1545  *
1546  * Alternatively you can call libusb_release_interface() first. Note if you
1547  * do things this way you must ensure that auto_detach_kernel_driver for
1548  * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
1549  * release the interface(s).
1550  *
1551  * You cannot change/reset configuration if other applications or drivers have
1552  * claimed interfaces.
1553  *
1554  * A configuration value of -1 will put the device in unconfigured state.
1555  * The USB specifications state that a configuration value of 0 does this,
1556  * however buggy devices exist which actually have a configuration 0.
1557  *
1558  * You should always use this function rather than formulating your own
1559  * SET_CONFIGURATION control request. This is because the underlying operating
1560  * system needs to know when such changes happen.
1561  *
1562  * This is a blocking function.
1563  *
1564  * \param dev_handle a device handle
1565  * \param configuration the bConfigurationValue of the configuration you
1566  * wish to activate, or -1 if you wish to put the device in an unconfigured
1567  * state
1568  * \returns 0 on success
1569  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1570  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1571  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1572  * \returns another LIBUSB_ERROR code on other failure
1573  * \see libusb_set_auto_detach_kernel_driver()
1574  */
1575 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev_handle,
1576         int configuration)
1577 {
1578         usbi_dbg("configuration %d", configuration);
1579         return usbi_backend.set_configuration(dev_handle, configuration);
1580 }
1581
1582 /** \ingroup libusb_dev
1583  * Claim an interface on a given device handle. You must claim the interface
1584  * you wish to use before you can perform I/O on any of its endpoints.
1585  *
1586  * It is legal to attempt to claim an already-claimed interface, in which
1587  * case libusb just returns 0 without doing anything.
1588  *
1589  * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
1590  * will be detached if necessary, on failure the detach error is returned.
1591  *
1592  * Claiming of interfaces is a purely logical operation; it does not cause
1593  * any requests to be sent over the bus. Interface claiming is used to
1594  * instruct the underlying operating system that your application wishes
1595  * to take ownership of the interface.
1596  *
1597  * This is a non-blocking function.
1598  *
1599  * \param dev_handle a device handle
1600  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1601  * wish to claim
1602  * \returns 0 on success
1603  * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1604  * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1605  * interface
1606  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1607  * \returns a LIBUSB_ERROR code on other failure
1608  * \see libusb_set_auto_detach_kernel_driver()
1609  */
1610 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev_handle,
1611         int interface_number)
1612 {
1613         int r = 0;
1614
1615         usbi_dbg("interface %d", interface_number);
1616         if (interface_number >= USB_MAXINTERFACES)
1617                 return LIBUSB_ERROR_INVALID_PARAM;
1618
1619         if (!dev_handle->dev->attached)
1620                 return LIBUSB_ERROR_NO_DEVICE;
1621
1622         usbi_mutex_lock(&dev_handle->lock);
1623         if (dev_handle->claimed_interfaces & (1 << interface_number))
1624                 goto out;
1625
1626         r = usbi_backend.claim_interface(dev_handle, interface_number);
1627         if (r == 0)
1628                 dev_handle->claimed_interfaces |= 1 << interface_number;
1629
1630 out:
1631         usbi_mutex_unlock(&dev_handle->lock);
1632         return r;
1633 }
1634
1635 /** \ingroup libusb_dev
1636  * Release an interface previously claimed with libusb_claim_interface(). You
1637  * should release all claimed interfaces before closing a device handle.
1638  *
1639  * This is a blocking function. A SET_INTERFACE control request will be sent
1640  * to the device, resetting interface state to the first alternate setting.
1641  *
1642  * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
1643  * driver will be re-attached after releasing the interface.
1644  *
1645  * \param dev_handle a device handle
1646  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1647  * previously-claimed interface
1648  * \returns 0 on success
1649  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1650  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1651  * \returns another LIBUSB_ERROR code on other failure
1652  * \see libusb_set_auto_detach_kernel_driver()
1653  */
1654 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev_handle,
1655         int interface_number)
1656 {
1657         int r;
1658
1659         usbi_dbg("interface %d", interface_number);
1660         if (interface_number >= USB_MAXINTERFACES)
1661                 return LIBUSB_ERROR_INVALID_PARAM;
1662
1663         usbi_mutex_lock(&dev_handle->lock);
1664         if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
1665                 r = LIBUSB_ERROR_NOT_FOUND;
1666                 goto out;
1667         }
1668
1669         r = usbi_backend.release_interface(dev_handle, interface_number);
1670         if (r == 0)
1671                 dev_handle->claimed_interfaces &= ~(1 << interface_number);
1672
1673 out:
1674         usbi_mutex_unlock(&dev_handle->lock);
1675         return r;
1676 }
1677
1678 /** \ingroup libusb_dev
1679  * Activate an alternate setting for an interface. The interface must have
1680  * been previously claimed with libusb_claim_interface().
1681  *
1682  * You should always use this function rather than formulating your own
1683  * SET_INTERFACE control request. This is because the underlying operating
1684  * system needs to know when such changes happen.
1685  *
1686  * This is a blocking function.
1687  *
1688  * \param dev_handle a device handle
1689  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1690  * previously-claimed interface
1691  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1692  * setting to activate
1693  * \returns 0 on success
1694  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1695  * requested alternate setting does not exist
1696  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1697  * \returns another LIBUSB_ERROR code on other failure
1698  */
1699 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
1700         int interface_number, int alternate_setting)
1701 {
1702         usbi_dbg("interface %d altsetting %d",
1703                 interface_number, alternate_setting);
1704         if (interface_number >= USB_MAXINTERFACES)
1705                 return LIBUSB_ERROR_INVALID_PARAM;
1706
1707         usbi_mutex_lock(&dev_handle->lock);
1708         if (!dev_handle->dev->attached) {
1709                 usbi_mutex_unlock(&dev_handle->lock);
1710                 return LIBUSB_ERROR_NO_DEVICE;
1711         }
1712
1713         if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
1714                 usbi_mutex_unlock(&dev_handle->lock);
1715                 return LIBUSB_ERROR_NOT_FOUND;
1716         }
1717         usbi_mutex_unlock(&dev_handle->lock);
1718
1719         return usbi_backend.set_interface_altsetting(dev_handle, interface_number,
1720                 alternate_setting);
1721 }
1722
1723 /** \ingroup libusb_dev
1724  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1725  * are unable to receive or transmit data until the halt condition is stalled.
1726  *
1727  * You should cancel all pending transfers before attempting to clear the halt
1728  * condition.
1729  *
1730  * This is a blocking function.
1731  *
1732  * \param dev_handle a device handle
1733  * \param endpoint the endpoint to clear halt status
1734  * \returns 0 on success
1735  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1736  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1737  * \returns another LIBUSB_ERROR code on other failure
1738  */
1739 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev_handle,
1740         unsigned char endpoint)
1741 {
1742         usbi_dbg("endpoint %x", endpoint);
1743         if (!dev_handle->dev->attached)
1744                 return LIBUSB_ERROR_NO_DEVICE;
1745
1746         return usbi_backend.clear_halt(dev_handle, endpoint);
1747 }
1748
1749 /** \ingroup libusb_dev
1750  * Perform a USB port reset to reinitialize a device. The system will attempt
1751  * to restore the previous configuration and alternate settings after the
1752  * reset has completed.
1753  *
1754  * If the reset fails, the descriptors change, or the previous state cannot be
1755  * restored, the device will appear to be disconnected and reconnected. This
1756  * means that the device handle is no longer valid (you should close it) and
1757  * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1758  * when this is the case.
1759  *
1760  * This is a blocking function which usually incurs a noticeable delay.
1761  *
1762  * \param dev_handle a handle of the device to reset
1763  * \returns 0 on success
1764  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1765  * device has been disconnected
1766  * \returns another LIBUSB_ERROR code on other failure
1767  */
1768 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev_handle)
1769 {
1770         usbi_dbg("");
1771         if (!dev_handle->dev->attached)
1772                 return LIBUSB_ERROR_NO_DEVICE;
1773
1774         return usbi_backend.reset_device(dev_handle);
1775 }
1776
1777 /** \ingroup libusb_asyncio
1778  * Allocate up to num_streams usb bulk streams on the specified endpoints. This
1779  * function takes an array of endpoints rather then a single endpoint because
1780  * some protocols require that endpoints are setup with similar stream ids.
1781  * All endpoints passed in must belong to the same interface.
1782  *
1783  * Note this function may return less streams then requested. Also note that the
1784  * same number of streams are allocated for each endpoint in the endpoint array.
1785  *
1786  * Stream id 0 is reserved, and should not be used to communicate with devices.
1787  * If libusb_alloc_streams() returns with a value of N, you may use stream ids
1788  * 1 to N.
1789  *
1790  * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1791  *
1792  * \param dev_handle a device handle
1793  * \param num_streams number of streams to try to allocate
1794  * \param endpoints array of endpoints to allocate streams on
1795  * \param num_endpoints length of the endpoints array
1796  * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
1797  */
1798 int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev_handle,
1799         uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1800 {
1801         usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints);
1802
1803         if (!dev_handle->dev->attached)
1804                 return LIBUSB_ERROR_NO_DEVICE;
1805
1806         if (usbi_backend.alloc_streams)
1807                 return usbi_backend.alloc_streams(dev_handle, num_streams, endpoints,
1808                                                    num_endpoints);
1809         else
1810                 return LIBUSB_ERROR_NOT_SUPPORTED;
1811 }
1812
1813 /** \ingroup libusb_asyncio
1814  * Free usb bulk streams allocated with libusb_alloc_streams().
1815  *
1816  * Note streams are automatically free-ed when releasing an interface.
1817  *
1818  * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1819  *
1820  * \param dev_handle a device handle
1821  * \param endpoints array of endpoints to free streams on
1822  * \param num_endpoints length of the endpoints array
1823  * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1824  */
1825 int API_EXPORTED libusb_free_streams(libusb_device_handle *dev_handle,
1826         unsigned char *endpoints, int num_endpoints)
1827 {
1828         usbi_dbg("eps %d", num_endpoints);
1829
1830         if (!dev_handle->dev->attached)
1831                 return LIBUSB_ERROR_NO_DEVICE;
1832
1833         if (usbi_backend.free_streams)
1834                 return usbi_backend.free_streams(dev_handle, endpoints,
1835                                                   num_endpoints);
1836         else
1837                 return LIBUSB_ERROR_NOT_SUPPORTED;
1838 }
1839
1840 /** \ingroup libusb_asyncio
1841  * Attempts to allocate a block of persistent DMA memory suitable for transfers
1842  * against the given device. If successful, will return a block of memory
1843  * that is suitable for use as "buffer" in \ref libusb_transfer against this
1844  * device. Using this memory instead of regular memory means that the host
1845  * controller can use DMA directly into the buffer to increase performance, and
1846  * also that transfers can no longer fail due to kernel memory fragmentation.
1847  *
1848  * Note that this means you should not modify this memory (or even data on
1849  * the same cache lines) when a transfer is in progress, although it is legal
1850  * to have several transfers going on within the same memory block.
1851  *
1852  * Will return NULL on failure. Many systems do not support such zerocopy
1853  * and will always return NULL. Memory allocated with this function must be
1854  * freed with \ref libusb_dev_mem_free. Specifically, this means that the
1855  * flag \ref LIBUSB_TRANSFER_FREE_BUFFER cannot be used to free memory allocated
1856  * with this function.
1857  *
1858  * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
1859  *
1860  * \param dev_handle a device handle
1861  * \param length size of desired data buffer
1862  * \returns a pointer to the newly allocated memory, or NULL on failure
1863  */
1864 DEFAULT_VISIBILITY
1865 unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle,
1866         size_t length)
1867 {
1868         if (!dev_handle->dev->attached)
1869                 return NULL;
1870
1871         if (usbi_backend.dev_mem_alloc)
1872                 return usbi_backend.dev_mem_alloc(dev_handle, length);
1873         else
1874                 return NULL;
1875 }
1876
1877 /** \ingroup libusb_asyncio
1878  * Free device memory allocated with libusb_dev_mem_alloc().
1879  *
1880  * \param dev_handle a device handle
1881  * \param buffer pointer to the previously allocated memory
1882  * \param length size of previously allocated memory
1883  * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1884  */
1885 int API_EXPORTED libusb_dev_mem_free(libusb_device_handle *dev_handle,
1886         unsigned char *buffer, size_t length)
1887 {
1888         if (usbi_backend.dev_mem_free)
1889                 return usbi_backend.dev_mem_free(dev_handle, buffer, length);
1890         else
1891                 return LIBUSB_ERROR_NOT_SUPPORTED;
1892 }
1893
1894 /** \ingroup libusb_dev
1895  * Determine if a kernel driver is active on an interface. If a kernel driver
1896  * is active, you cannot claim the interface, and libusb will be unable to
1897  * perform I/O.
1898  *
1899  * This functionality is not available on Windows.
1900  *
1901  * \param dev_handle a device handle
1902  * \param interface_number the interface to check
1903  * \returns 0 if no kernel driver is active
1904  * \returns 1 if a kernel driver is active
1905  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1906  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1907  * is not available
1908  * \returns another LIBUSB_ERROR code on other failure
1909  * \see libusb_detach_kernel_driver()
1910  */
1911 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev_handle,
1912         int interface_number)
1913 {
1914         usbi_dbg("interface %d", interface_number);
1915
1916         if (!dev_handle->dev->attached)
1917                 return LIBUSB_ERROR_NO_DEVICE;
1918
1919         if (usbi_backend.kernel_driver_active)
1920                 return usbi_backend.kernel_driver_active(dev_handle, interface_number);
1921         else
1922                 return LIBUSB_ERROR_NOT_SUPPORTED;
1923 }
1924
1925 /** \ingroup libusb_dev
1926  * Detach a kernel driver from an interface. If successful, you will then be
1927  * able to claim the interface and perform I/O.
1928  *
1929  * This functionality is not available on Darwin or Windows.
1930  *
1931  * Note that libusb itself also talks to the device through a special kernel
1932  * driver, if this driver is already attached to the device, this call will
1933  * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1934  *
1935  * \param dev_handle a device handle
1936  * \param interface_number the interface to detach the driver from
1937  * \returns 0 on success
1938  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1939  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1940  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1941  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1942  * is not available
1943  * \returns another LIBUSB_ERROR code on other failure
1944  * \see libusb_kernel_driver_active()
1945  */
1946 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
1947         int interface_number)
1948 {
1949         usbi_dbg("interface %d", interface_number);
1950
1951         if (!dev_handle->dev->attached)
1952                 return LIBUSB_ERROR_NO_DEVICE;
1953
1954         if (usbi_backend.detach_kernel_driver)
1955                 return usbi_backend.detach_kernel_driver(dev_handle, interface_number);
1956         else
1957                 return LIBUSB_ERROR_NOT_SUPPORTED;
1958 }
1959
1960 /** \ingroup libusb_dev
1961  * Re-attach an interface's kernel driver, which was previously detached
1962  * using libusb_detach_kernel_driver(). This call is only effective on
1963  * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1964  *
1965  * This functionality is not available on Darwin or Windows.
1966  *
1967  * \param dev_handle a device handle
1968  * \param interface_number the interface to attach the driver from
1969  * \returns 0 on success
1970  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1971  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1972  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1973  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1974  * is not available
1975  * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1976  * interface is claimed by a program or driver
1977  * \returns another LIBUSB_ERROR code on other failure
1978  * \see libusb_kernel_driver_active()
1979  */
1980 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
1981         int interface_number)
1982 {
1983         usbi_dbg("interface %d", interface_number);
1984
1985         if (!dev_handle->dev->attached)
1986                 return LIBUSB_ERROR_NO_DEVICE;
1987
1988         if (usbi_backend.attach_kernel_driver)
1989                 return usbi_backend.attach_kernel_driver(dev_handle, interface_number);
1990         else
1991                 return LIBUSB_ERROR_NOT_SUPPORTED;
1992 }
1993
1994 /** \ingroup libusb_dev
1995  * Enable/disable libusb's automatic kernel driver detachment. When this is
1996  * enabled libusb will automatically detach the kernel driver on an interface
1997  * when claiming the interface, and attach it when releasing the interface.
1998  *
1999  * Automatic kernel driver detachment is disabled on newly opened device
2000  * handles by default.
2001  *
2002  * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
2003  * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
2004  * continue as if this function was never called.
2005  *
2006  * \param dev_handle a device handle
2007  * \param enable whether to enable or disable auto kernel driver detachment
2008  *
2009  * \returns LIBUSB_SUCCESS on success
2010  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
2011  * is not available
2012  * \see libusb_claim_interface()
2013  * \see libusb_release_interface()
2014  * \see libusb_set_configuration()
2015  */
2016 int API_EXPORTED libusb_set_auto_detach_kernel_driver(
2017         libusb_device_handle *dev_handle, int enable)
2018 {
2019         if (!(usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
2020                 return LIBUSB_ERROR_NOT_SUPPORTED;
2021
2022         dev_handle->auto_detach_kernel_driver = enable;
2023         return LIBUSB_SUCCESS;
2024 }
2025
2026 /** \ingroup libusb_lib
2027  * \deprecated Use libusb_set_option() instead using the
2028  * \ref LIBUSB_OPTION_LOG_LEVEL option.
2029  */
2030 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
2031 {
2032 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2033         USBI_GET_CONTEXT(ctx);
2034         if (!ctx->debug_fixed) {
2035                 level = CLAMP(level, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG);
2036                 ctx->debug = (enum libusb_log_level)level;
2037         }
2038 #else
2039         UNUSED(ctx);
2040         UNUSED(level);
2041 #endif
2042 }
2043
2044 /** \ingroup libusb_lib
2045  * Set an option in the library.
2046  *
2047  * Use this function to configure a specific option within the library.
2048  *
2049  * Some options require one or more arguments to be provided. Consult each
2050  * option's documentation for specific requirements.
2051  *
2052  * Since version 1.0.22, \ref LIBUSB_API_VERSION >= 0x01000106
2053  *
2054  * \param ctx context on which to operate
2055  * \param option which option to set
2056  * \param ... any required arguments for the specified option
2057  *
2058  * \returns LIBUSB_SUCCESS on success
2059  * \returns LIBUSB_ERROR_INVALID_PARAM if the option or arguments are invalid
2060  * \returns LIBUSB_ERROR_NOT_SUPPORTED if the option is valid but not supported
2061  * on this platform
2062  */
2063 int API_EXPORTED libusb_set_option(libusb_context *ctx,
2064         enum libusb_option option, ...)
2065 {
2066         int arg, r = LIBUSB_SUCCESS;
2067         va_list ap;
2068
2069         USBI_GET_CONTEXT(ctx);
2070
2071         va_start(ap, option);
2072         switch (option) {
2073         case LIBUSB_OPTION_LOG_LEVEL:
2074                 arg = va_arg(ap, int);
2075                 if (arg < LIBUSB_LOG_LEVEL_NONE || arg > LIBUSB_LOG_LEVEL_DEBUG) {
2076                         r = LIBUSB_ERROR_INVALID_PARAM;
2077                         break;
2078                 }
2079 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2080                 if (!ctx->debug_fixed)
2081                         ctx->debug = (enum libusb_log_level)arg;
2082 #endif
2083                 break;
2084
2085         /* Handle all backend-specific options here */
2086         case LIBUSB_OPTION_USE_USBDK:
2087                 if (usbi_backend.set_option)
2088                         r = usbi_backend.set_option(ctx, option, ap);
2089                 else
2090                         r = LIBUSB_ERROR_NOT_SUPPORTED;
2091                 break;
2092
2093         default:
2094                 r = LIBUSB_ERROR_INVALID_PARAM;
2095         }
2096         va_end(ap);
2097
2098         return r;
2099 }
2100
2101 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2102 /* returns the log level as defined in the LIBUSB_DEBUG environment variable.
2103  * if LIBUSB_DEBUG is not present or not a number, returns LIBUSB_LOG_LEVEL_NONE.
2104  * value is clamped to ensure it is within the valid range of possibilities.
2105  */
2106 static enum libusb_log_level get_env_debug_level(void)
2107 {
2108         const char *dbg = getenv("LIBUSB_DEBUG");
2109         enum libusb_log_level level;
2110         if (dbg) {
2111                 int dbg_level = atoi(dbg);
2112                 dbg_level = CLAMP(dbg_level, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG);
2113                 level = (enum libusb_log_level)dbg_level;
2114         } else {
2115                 level = LIBUSB_LOG_LEVEL_NONE;
2116         }
2117         return level;
2118 }
2119 #endif
2120
2121 /** \ingroup libusb_lib
2122  * Initialize libusb. This function must be called before calling any other
2123  * libusb function.
2124  *
2125  * If you do not provide an output location for a context pointer, a default
2126  * context will be created. If there was already a default context, it will
2127  * be reused (and nothing will be initialized/reinitialized).
2128  *
2129  * \param context Optional output location for context pointer.
2130  * Only valid on return code 0.
2131  * \returns 0 on success, or a LIBUSB_ERROR code on failure
2132  * \see libusb_contexts
2133  */
2134 int API_EXPORTED libusb_init(libusb_context **context)
2135 {
2136         struct libusb_device *dev, *next;
2137         size_t priv_size = usbi_backend.context_priv_size;
2138         struct libusb_context *ctx;
2139         static int first_init = 1;
2140         int r = 0;
2141
2142         usbi_mutex_static_lock(&default_context_lock);
2143
2144         if (!timestamp_origin.tv_sec) {
2145                 usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &timestamp_origin);
2146         }
2147
2148         if (!context && usbi_default_context) {
2149                 usbi_dbg("reusing default context");
2150                 default_context_refcnt++;
2151                 usbi_mutex_static_unlock(&default_context_lock);
2152                 return 0;
2153         }
2154
2155         ctx = calloc(1, sizeof(*ctx) + priv_size);
2156         if (!ctx) {
2157                 r = LIBUSB_ERROR_NO_MEM;
2158                 goto err_unlock;
2159         }
2160
2161 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2162         ctx->debug = get_env_debug_level();
2163         if (ctx->debug != LIBUSB_LOG_LEVEL_NONE)
2164                 ctx->debug_fixed = 1;
2165 #endif
2166
2167         /* default context should be initialized before calling usbi_dbg */
2168         if (!usbi_default_context) {
2169                 usbi_default_context = ctx;
2170                 default_context_refcnt++;
2171                 usbi_dbg("created default context");
2172         }
2173
2174         usbi_dbg("libusb v%u.%u.%u.%u%s", libusb_version_internal.major, libusb_version_internal.minor,
2175                 libusb_version_internal.micro, libusb_version_internal.nano, libusb_version_internal.rc);
2176
2177         usbi_mutex_init(&ctx->usb_devs_lock);
2178         usbi_mutex_init(&ctx->open_devs_lock);
2179         usbi_mutex_init(&ctx->hotplug_cbs_lock);
2180         list_init(&ctx->usb_devs);
2181         list_init(&ctx->open_devs);
2182         list_init(&ctx->hotplug_cbs);
2183         ctx->next_hotplug_cb_handle = 1;
2184
2185         usbi_mutex_static_lock(&active_contexts_lock);
2186         if (first_init) {
2187                 first_init = 0;
2188                 list_init (&active_contexts_list);
2189         }
2190         list_add (&ctx->list, &active_contexts_list);
2191         usbi_mutex_static_unlock(&active_contexts_lock);
2192
2193         if (usbi_backend.init) {
2194                 r = usbi_backend.init(ctx);
2195                 if (r)
2196                         goto err_free_ctx;
2197         }
2198
2199         r = usbi_io_init(ctx);
2200         if (r < 0)
2201                 goto err_backend_exit;
2202
2203         usbi_mutex_static_unlock(&default_context_lock);
2204
2205         if (context)
2206                 *context = ctx;
2207
2208         return 0;
2209
2210 err_backend_exit:
2211         if (usbi_backend.exit)
2212                 usbi_backend.exit(ctx);
2213 err_free_ctx:
2214         if (ctx == usbi_default_context) {
2215                 usbi_default_context = NULL;
2216                 default_context_refcnt--;
2217         }
2218
2219         usbi_mutex_static_lock(&active_contexts_lock);
2220         list_del (&ctx->list);
2221         usbi_mutex_static_unlock(&active_contexts_lock);
2222
2223         usbi_mutex_lock(&ctx->usb_devs_lock);
2224         list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
2225                 list_del(&dev->list);
2226                 libusb_unref_device(dev);
2227         }
2228         usbi_mutex_unlock(&ctx->usb_devs_lock);
2229
2230         usbi_mutex_destroy(&ctx->open_devs_lock);
2231         usbi_mutex_destroy(&ctx->usb_devs_lock);
2232         usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2233
2234         free(ctx);
2235 err_unlock:
2236         usbi_mutex_static_unlock(&default_context_lock);
2237         return r;
2238 }
2239
2240 /** \ingroup libusb_lib
2241  * Deinitialize libusb. Should be called after closing all open devices and
2242  * before your application terminates.
2243  * \param ctx the context to deinitialize, or NULL for the default context
2244  */
2245 void API_EXPORTED libusb_exit(struct libusb_context *ctx)
2246 {
2247         struct libusb_device *dev, *next;
2248         struct timeval tv = { 0, 0 };
2249
2250         usbi_dbg("");
2251         USBI_GET_CONTEXT(ctx);
2252
2253         /* if working with default context, only actually do the deinitialization
2254          * if we're the last user */
2255         usbi_mutex_static_lock(&default_context_lock);
2256         if (ctx == usbi_default_context) {
2257                 if (--default_context_refcnt > 0) {
2258                         usbi_dbg("not destroying default context");
2259                         usbi_mutex_static_unlock(&default_context_lock);
2260                         return;
2261                 }
2262                 usbi_dbg("destroying default context");
2263                 usbi_default_context = NULL;
2264         }
2265         usbi_mutex_static_unlock(&default_context_lock);
2266
2267         usbi_mutex_static_lock(&active_contexts_lock);
2268         list_del (&ctx->list);
2269         usbi_mutex_static_unlock(&active_contexts_lock);
2270
2271         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
2272                 usbi_hotplug_deregister(ctx, 1);
2273
2274                 /*
2275                  * Ensure any pending unplug events are read from the hotplug
2276                  * pipe. The usb_device-s hold in the events are no longer part
2277                  * of usb_devs, but the events still hold a reference!
2278                  *
2279                  * Note we don't do this if the application has left devices
2280                  * open (which implies a buggy app) to avoid packet completion
2281                  * handlers running when the app does not expect them to run.
2282                  */
2283                 if (list_empty(&ctx->open_devs))
2284                         libusb_handle_events_timeout(ctx, &tv);
2285
2286                 usbi_mutex_lock(&ctx->usb_devs_lock);
2287                 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
2288                         list_del(&dev->list);
2289                         libusb_unref_device(dev);
2290                 }
2291                 usbi_mutex_unlock(&ctx->usb_devs_lock);
2292         }
2293
2294         /* a few sanity checks. don't bother with locking because unless
2295          * there is an application bug, nobody will be accessing these. */
2296         if (!list_empty(&ctx->usb_devs))
2297                 usbi_warn(ctx, "some libusb_devices were leaked");
2298         if (!list_empty(&ctx->open_devs))
2299                 usbi_warn(ctx, "application left some devices open");
2300
2301         usbi_io_exit(ctx);
2302         if (usbi_backend.exit)
2303                 usbi_backend.exit(ctx);
2304
2305         usbi_mutex_destroy(&ctx->open_devs_lock);
2306         usbi_mutex_destroy(&ctx->usb_devs_lock);
2307         usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2308         free(ctx);
2309 }
2310
2311 /** \ingroup libusb_misc
2312  * Check at runtime if the loaded library has a given capability.
2313  * This call should be performed after \ref libusb_init(), to ensure the
2314  * backend has updated its capability set.
2315  *
2316  * \param capability the \ref libusb_capability to check for
2317  * \returns nonzero if the running library has the capability, 0 otherwise
2318  */
2319 int API_EXPORTED libusb_has_capability(uint32_t capability)
2320 {
2321         switch (capability) {
2322         case LIBUSB_CAP_HAS_CAPABILITY:
2323                 return 1;
2324         case LIBUSB_CAP_HAS_HOTPLUG:
2325                 return !(usbi_backend.get_device_list);
2326         case LIBUSB_CAP_HAS_HID_ACCESS:
2327                 return (usbi_backend.caps & USBI_CAP_HAS_HID_ACCESS);
2328         case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
2329                 return (usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
2330         }
2331         return 0;
2332 }
2333
2334 #ifdef ENABLE_LOGGING
2335
2336 /* this is defined in libusbi.h if needed */
2337 #ifdef LIBUSB_PRINTF_WIN32
2338 /*
2339  * Prior to VS2015, Microsoft did not provide the snprintf() function and
2340  * provided a vsnprintf() that did not guarantee NULL-terminated output.
2341  * Microsoft did provide a _snprintf() function, but again it did not
2342  * guarantee NULL-terminated output.
2343  *
2344  * The below implementations guarantee NULL-terminated output and are
2345  * C99 compliant.
2346  */
2347
2348 int usbi_snprintf(char *str, size_t size, const char *format, ...)
2349 {
2350         va_list ap;
2351         int ret;
2352
2353         va_start(ap, format);
2354         ret = usbi_vsnprintf(str, size, format, ap);
2355         va_end(ap);
2356
2357         return ret;
2358 }
2359
2360 int usbi_vsnprintf(char *str, size_t size, const char *format, va_list ap)
2361 {
2362         int ret;
2363
2364         ret = _vsnprintf(str, size, format, ap);
2365         if (ret < 0 || ret == (int)size) {
2366                 /* Output is truncated, ensure buffer is NULL-terminated and
2367                  * determine how many characters would have been written. */
2368                 str[size - 1] = '\0';
2369                 if (ret < 0)
2370                         ret = _vsnprintf(NULL, 0, format, ap);
2371         }
2372
2373         return ret;
2374 }
2375 #endif /* LIBUSB_PRINTF_WIN32 */
2376
2377 static void usbi_log_str(enum libusb_log_level level, const char *str)
2378 {
2379 #if defined(USE_SYSTEM_LOGGING_FACILITY)
2380 #if defined(OS_WINDOWS)
2381         OutputDebugString(str);
2382 #elif defined(OS_WINCE)
2383         /* Windows CE only supports the Unicode version of OutputDebugString. */
2384         WCHAR wbuf[USBI_MAX_LOG_LEN];
2385         MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
2386         OutputDebugStringW(wbuf);
2387 #elif defined(__ANDROID__)
2388         int priority = ANDROID_LOG_UNKNOWN;
2389         switch (level) {
2390         case LIBUSB_LOG_LEVEL_NONE: return;
2391         case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
2392         case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
2393         case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
2394         case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
2395         }
2396         __android_log_write(priority, "libusb", str);
2397 #elif defined(HAVE_SYSLOG_FUNC)
2398         int syslog_level = LOG_INFO;
2399         switch (level) {
2400         case LIBUSB_LOG_LEVEL_NONE: return;
2401         case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
2402         case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
2403         case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
2404         case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
2405         }
2406         syslog(syslog_level, "%s", str);
2407 #else /* All of gcc, Clang, XCode seem to use #warning */
2408 #warning System logging is not supported on this platform. Logging to stderr will be used instead.
2409         fputs(str, stderr);
2410 #endif
2411 #else
2412         fputs(str, stderr);
2413 #endif /* USE_SYSTEM_LOGGING_FACILITY */
2414         UNUSED(level);
2415 }
2416
2417 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
2418         const char *function, const char *format, va_list args)
2419 {
2420         const char *prefix;
2421         char buf[USBI_MAX_LOG_LEN];
2422         struct timespec now;
2423         int global_debug, header_len, text_len;
2424         static int has_debug_header_been_displayed = 0;
2425
2426 #ifdef ENABLE_DEBUG_LOGGING
2427         global_debug = 1;
2428         UNUSED(ctx);
2429 #else
2430         enum libusb_log_level ctx_level = LIBUSB_LOG_LEVEL_NONE;
2431
2432         USBI_GET_CONTEXT(ctx);
2433         if (ctx)
2434                 ctx_level = ctx->debug;
2435         else
2436                 ctx_level = get_env_debug_level();
2437
2438         if (ctx_level == LIBUSB_LOG_LEVEL_NONE)
2439                 return;
2440         if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING)
2441                 return;
2442         if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO)
2443                 return;
2444         if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG)
2445                 return;
2446
2447         global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
2448 #endif
2449
2450         usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &now);
2451         if ((global_debug) && (!has_debug_header_been_displayed)) {
2452                 has_debug_header_been_displayed = 1;
2453                 usbi_log_str(LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>" USBI_LOG_LINE_END);
2454                 usbi_log_str(LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END);
2455         }
2456         if (now.tv_nsec < timestamp_origin.tv_nsec) {
2457                 now.tv_sec--;
2458                 now.tv_nsec += 1000000000L;
2459         }
2460         now.tv_sec -= timestamp_origin.tv_sec;
2461         now.tv_nsec -= timestamp_origin.tv_nsec;
2462
2463         switch (level) {
2464         case LIBUSB_LOG_LEVEL_NONE:
2465                 return;
2466         case LIBUSB_LOG_LEVEL_ERROR:
2467                 prefix = "error";
2468                 break;
2469         case LIBUSB_LOG_LEVEL_WARNING:
2470                 prefix = "warning";
2471                 break;
2472         case LIBUSB_LOG_LEVEL_INFO:
2473                 prefix = "info";
2474                 break;
2475         case LIBUSB_LOG_LEVEL_DEBUG:
2476                 prefix = "debug";
2477                 break;
2478         default:
2479                 prefix = "unknown";
2480                 break;
2481         }
2482
2483         if (global_debug) {
2484                 header_len = snprintf(buf, sizeof(buf),
2485                         "[%2d.%06d] [%08x] libusb: %s [%s] ",
2486                         (int)now.tv_sec, (int)(now.tv_nsec / 1000L), usbi_get_tid(), prefix, function);
2487         } else {
2488                 header_len = snprintf(buf, sizeof(buf),
2489                         "libusb: %s [%s] ", prefix, function);
2490         }
2491
2492         if (header_len < 0 || header_len >= (int)sizeof(buf)) {
2493                 /* Somehow snprintf failed to write to the buffer,
2494                  * remove the header so something useful is output. */
2495                 header_len = 0;
2496         }
2497         /* Make sure buffer is NUL terminated */
2498         buf[header_len] = '\0';
2499         text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
2500                 format, args);
2501         if (text_len < 0 || text_len + header_len >= (int)sizeof(buf)) {
2502                 /* Truncated log output. On some platforms a -1 return value means
2503                  * that the output was truncated. */
2504                 text_len = sizeof(buf) - header_len;
2505         }
2506         if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
2507                 /* Need to truncate the text slightly to fit on the terminator. */
2508                 text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
2509         }
2510         strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
2511
2512         usbi_log_str(level, buf);
2513 }
2514
2515 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
2516         const char *function, const char *format, ...)
2517 {
2518         va_list args;
2519
2520         va_start (args, format);
2521         usbi_log_v(ctx, level, function, format, args);
2522         va_end (args);
2523 }
2524
2525 #endif /* ENABLE_LOGGING */
2526
2527 /** \ingroup libusb_misc
2528  * Returns a constant NULL-terminated string with the ASCII name of a libusb
2529  * error or transfer status code. The caller must not free() the returned
2530  * string.
2531  *
2532  * \param error_code The \ref libusb_error or libusb_transfer_status code to
2533  * return the name of.
2534  * \returns The error name, or the string **UNKNOWN** if the value of
2535  * error_code is not a known error / status code.
2536  */
2537 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
2538 {
2539         switch (error_code) {
2540         case LIBUSB_ERROR_IO:
2541                 return "LIBUSB_ERROR_IO";
2542         case LIBUSB_ERROR_INVALID_PARAM:
2543                 return "LIBUSB_ERROR_INVALID_PARAM";
2544         case LIBUSB_ERROR_ACCESS:
2545                 return "LIBUSB_ERROR_ACCESS";
2546         case LIBUSB_ERROR_NO_DEVICE:
2547                 return "LIBUSB_ERROR_NO_DEVICE";
2548         case LIBUSB_ERROR_NOT_FOUND:
2549                 return "LIBUSB_ERROR_NOT_FOUND";
2550         case LIBUSB_ERROR_BUSY:
2551                 return "LIBUSB_ERROR_BUSY";
2552         case LIBUSB_ERROR_TIMEOUT:
2553                 return "LIBUSB_ERROR_TIMEOUT";
2554         case LIBUSB_ERROR_OVERFLOW:
2555                 return "LIBUSB_ERROR_OVERFLOW";
2556         case LIBUSB_ERROR_PIPE:
2557                 return "LIBUSB_ERROR_PIPE";
2558         case LIBUSB_ERROR_INTERRUPTED:
2559                 return "LIBUSB_ERROR_INTERRUPTED";
2560         case LIBUSB_ERROR_NO_MEM:
2561                 return "LIBUSB_ERROR_NO_MEM";
2562         case LIBUSB_ERROR_NOT_SUPPORTED:
2563                 return "LIBUSB_ERROR_NOT_SUPPORTED";
2564         case LIBUSB_ERROR_OTHER:
2565                 return "LIBUSB_ERROR_OTHER";
2566
2567         case LIBUSB_TRANSFER_ERROR:
2568                 return "LIBUSB_TRANSFER_ERROR";
2569         case LIBUSB_TRANSFER_TIMED_OUT:
2570                 return "LIBUSB_TRANSFER_TIMED_OUT";
2571         case LIBUSB_TRANSFER_CANCELLED:
2572                 return "LIBUSB_TRANSFER_CANCELLED";
2573         case LIBUSB_TRANSFER_STALL:
2574                 return "LIBUSB_TRANSFER_STALL";
2575         case LIBUSB_TRANSFER_NO_DEVICE:
2576                 return "LIBUSB_TRANSFER_NO_DEVICE";
2577         case LIBUSB_TRANSFER_OVERFLOW:
2578                 return "LIBUSB_TRANSFER_OVERFLOW";
2579
2580         case 0:
2581                 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
2582         default:
2583                 return "**UNKNOWN**";
2584         }
2585 }
2586
2587 /** \ingroup libusb_misc
2588  * Returns a pointer to const struct libusb_version with the version
2589  * (major, minor, micro, nano and rc) of the running library.
2590  */
2591 DEFAULT_VISIBILITY
2592 const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
2593 {
2594         return &libusb_version_internal;
2595 }