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