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