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