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