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