Document the logging style
[platform/upstream/libusb.git] / libusb / core.c
1 /*
2  * Core functions for libusb
3  * Copyright (C) 2007-2008 Daniel Drake <dsd@gentoo.org>
4  * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <config.h>
22
23 #include <errno.h>
24 #include <poll.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30
31 #include "libusb.h"
32 #include "libusbi.h"
33
34 #ifdef OS_LINUX
35 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
36 #else
37 #error "Unsupported OS"
38 #endif
39
40 struct libusb_context *usbi_default_context = NULL;
41 static pthread_mutex_t default_context_lock = PTHREAD_MUTEX_INITIALIZER;
42
43 /**
44  * \mainpage libusb-1.0 API Reference
45  *
46  * \section intro Introduction
47  *
48  * libusb is an open source library that allows you to communicate with USB
49  * devices from userspace. For more info, see the
50  * <a href="http://libusb.sourceforge.net">libusb homepage</a>.
51  *
52  * This documentation is aimed at application developers wishing to
53  * communicate with USB peripherals from their own software. After reviewing
54  * this documentation, feedback and questions can be sent to the
55  * <a href="http://sourceforge.net/mail/?group_id=1674">libusb-devel mailing
56  * list</a>.
57  *
58  * This documentation assumes knowledge of how to operate USB devices from
59  * a software standpoint (descriptors, configurations, interfaces, endpoints,
60  * control/bulk/interrupt/isochronous transfers, etc). Full information
61  * can be found in the <a href="http://www.usb.org/developers/docs/">USB 2.0
62  * Specification</a> which is available for free download. You can probably
63  * find less verbose introductions by searching the web.
64  *
65  * \section features Library features
66  *
67  * - All transfer types supported (control/bulk/interrupt/isochronous)
68  * - 2 transfer interfaces:
69  *    -# Synchronous (simple)
70  *    -# Asynchronous (more complicated, but more powerful)
71  * - Thread safe (although the asynchronous interface means that you
72  *   usually won't need to thread)
73  * - Lightweight with lean API
74  * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
75  *
76  * \section gettingstarted Getting Started
77  *
78  * To begin reading the API documentation, start with the Modules page which
79  * links to the different categories of libusb's functionality.
80  *
81  * One decision you will have to make is whether to use the synchronous
82  * or the asynchronous data transfer interface. The \ref io documentation
83  * provides some insight into this topic.
84  *
85  * Some example programs can be found in the libusb source distribution under
86  * the "examples" subdirectory. The libusb homepage includes a list of
87  * real-life project examples which use libusb.
88  *
89  * \section errorhandling Error handling
90  *
91  * libusb functions typically return 0 on success or a negative error code
92  * on failure. These negative error codes relate to LIBUSB_ERROR constants
93  * which are listed on the \ref misc "miscellaneous" documentation page.
94  *
95  * \section msglog Debug message logging
96  *
97  * libusb does not log any messages by default. Your application is therefore
98  * free to close stdout/stderr and those descriptors may be reused without
99  * worry.
100  *
101  * The libusb_set_debug() function can be used to enable stdout/stderr logging
102  * of certain messages. Under standard configuration, libusb doesn't really
103  * log much at all, so you are advised to use this function to enable all
104  * error/warning/informational messages. It will help you debug problems with
105  * your software.
106  *
107  * The logged messages are unstructured. There is no one-to-one correspondence
108  * between messages being logged and success or failure return codes from
109  * libusb functions. There is no format to the messages, so you should not
110  * try to capture or parse them. They are not and will not be localized.
111  * These messages are not suitable for being passed to your application user;
112  * instead, you should interpret the error codes returned from libusb functions
113  * and provide appropriate notification to the user. The messages are simply
114  * there to aid you as a programmer, and if you're confused because you're
115  * getting a strange error code from a libusb function, enabling message
116  * logging may give you a suitable explanation.
117  *
118  * The LIBUSB_DEBUG environment variable can be used to enable message logging
119  * at run-time. This environment variable should be set to a number, which is
120  * interpreted the same as the libusb_set_debug() parameter. When this
121  * environment variable is set, the message logging verbosity level is fixed
122  * and libusb_set_debug() effectively does nothing.
123  *
124  * libusb can be compiled without any logging functions, useful for embedded
125  * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
126  * variable have no effects.
127  *
128  * libusb can also be compiled with verbose debugging messages. When the
129  * library is compiled in this way, all messages of all verbosities are always
130  * logged.  libusb_set_debug() and the LIBUSB_DEBUG environment variable have
131  * no effects.
132  *
133  * \section remarks Other remarks
134  *
135  * libusb does have imperfections. The \ref caveats "caveats" page attempts
136  * to document these.
137  */
138
139 /**
140  * \page caveats Caveats
141  *
142  * \section devresets Device resets
143  *
144  * The libusb_reset_device() function allows you to reset a device. If your
145  * program has to call such a function, it should obviously be aware that
146  * the reset will cause device state to change (e.g. register values may be
147  * reset).
148  *
149  * The problem is that any other program could reset the device your program
150  * is working with, at any time. libusb does not offer a mechanism to inform
151  * you when this has happened, so if someone else resets your device it will
152  * not be clear to your own program why the device state has changed.
153  *
154  * Ultimately, this is a limitation of writing drivers in userspace.
155  * Separation from the USB stack in the underlying kernel makes it difficult
156  * for the operating system to deliver such notifications to your program.
157  * The Linux kernel USB stack allows such reset notifications to be delivered
158  * to in-kernel USB drivers, but it is not clear how such notifications could
159  * be delivered to second-class drivers that live in userspace.
160  *
161  * \section blockonly Blocking-only functionality
162  *
163  * The functionality listed below is only available through synchronous,
164  * blocking functions. There are no asynchronous/non-blocking alternatives,
165  * and no clear ways of implementing these.
166  *
167  * - Configuration activation (libusb_set_configuration())
168  * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
169  * - Releasing of interfaces (libusb_release_interface())
170  * - Clearing of halt/stall condition (libusb_clear_halt())
171  * - Device resets (libusb_reset_device())
172  *
173  * \section nohotplug No hotplugging
174  *
175  * libusb-1.0 lacks functionality for providing notifications of when devices
176  * are added or removed. This functionality is planned to be implemented
177  * for libusb-1.1.
178  *
179  * That said, there is basic disconnection handling for open device handles:
180  *  - If there are ongoing transfers, libusb's handle_events loop will detect
181  *    disconnections and complete ongoing transfers with the
182  *    LIBUSB_TRANSFER_NO_DEVICE status code.
183  *  - Many functions such as libusb_set_configuration() return the special
184  *    LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected.
185  *
186  * \section configsel Configuration selection and handling
187  *
188  * When libusb presents a device handle to an application, there is a chance
189  * that the corresponding device may be in unconfigured state. For devices
190  * with multiple configurations, there is also a chance that the configuration
191  * currently selected is not the one that the application wants to use.
192  *
193  * The obvious solution is to add a call to libusb_set_configuration() early
194  * on during your device initialization routines, but there are caveats to
195  * be aware of:
196  * -# If the device is already in the desired configuration, calling
197  *    libusb_set_configuration() using the same configuration value will cause
198  *    a lightweight device reset. This may not be desirable behaviour.
199  * -# libusb will be unable to change configuration if the device is in
200  *    another configuration and other programs or drivers have claimed
201  *    interfaces under that configuration.
202  * -# In the case where the desired configuration is already active, libusb
203  *    may not even be able to perform a lightweight device reset. For example,
204  *    take my USB keyboard with fingerprint reader: I'm interested in driving
205  *    the fingerprint reader interface through libusb, but the kernel's
206  *    USB-HID driver will almost always have claimed the keyboard interface.
207  *    Because the kernel has claimed an interface, it is not even possible to
208  *    perform the lightweight device reset, so libusb_set_configuration() will
209  *    fail. (Luckily the device in question only has a single configuration.)
210  *
211  * One solution to some of the above problems is to consider the currently
212  * active configuration. If the configuration we want is already active, then
213  * we don't have to select any configuration:
214 \code
215 cfg = libusb_get_configuration(dev);
216 if (cfg != desired)
217         libusb_set_configuration(dev, desired);
218 \endcode
219  *
220  * This is probably suitable for most scenarios, but is inherently racy:
221  * another application or driver may change the selected configuration
222  * <em>after</em> the libusb_get_configuration() call.
223  *
224  * Even in cases where libusb_set_configuration() succeeds, consider that other
225  * applications or drivers may change configuration after your application
226  * calls libusb_set_configuration().
227  *
228  * One possible way to lock your device into a specific configuration is as
229  * follows:
230  * -# Set the desired configuration (or use the logic above to realise that
231  *    it is already in the desired configuration)
232  * -# Claim the interface that you wish to use
233  * -# Check that the currently active configuration is the one that you want
234  *    to use.
235  *
236  * The above method works because once an interface is claimed, no application
237  * or driver is able to select another configuration.
238  */
239
240 /**
241  * \page contexts Contexts
242  *
243  * It is possible that libusb may be used simultaneously from two independent
244  * libraries linked into the same executable. For example, if your application
245  * has a plugin-like system which allows the user to dynamically load a range
246  * of modules into your program, it is feasible that two independently
247  * developed modules may both use libusb.
248  *
249  * libusb is written to allow for these multiple user scenarios. The two
250  * "instances" of libusb will not interfere: libusb_set_debug() calls
251  * from one user will not affect the same settings for other users, other
252  * users can continue using libusb after one of them calls libusb_exit(), etc.
253  *
254  * This is made possible through libusb's <em>context</em> concept. When you
255  * call libusb_init(), you are (optionally) given a context. You can then pass
256  * this context pointer back into future libusb functions.
257  *
258  * In order to keep things simple for more simplistic applications, it is
259  * legal to pass NULL to all functions requiring a context pointer (as long as
260  * you're sure no other code will attempt to use libusb from the same process).
261  * When you pass NULL, the default context will be used. The default context
262  * is created the first time a process calls libusb_init() when no other
263  * context is alive. Contexts are destroyed during libusb_exit().
264  *
265  * You may be wondering why only a subset of libusb functions require a
266  * context pointer in their function definition. Internally, libusb stores
267  * context pointers in other objects (e.g. libusb_device instances) and hence
268  * can infer the context from those objects.
269  */
270
271 /**
272  * @defgroup lib Library initialization/deinitialization
273  * This page details how to initialize and deinitialize libusb. Initialization
274  * must be performed before using any libusb functionality, and similarly you
275  * must not call any libusb functions after deinitialization.
276  */
277
278 /**
279  * @defgroup dev Device handling and enumeration
280  * The functionality documented below is designed to help with the following
281  * operations:
282  * - Enumerating the USB devices currently attached to the system
283  * - Choosing a device to operate from your software
284  * - Opening and closing the chosen device
285  *
286  * \section nutshell In a nutshell...
287  *
288  * The description below really makes things sound more complicated than they
289  * actually are. The following sequence of function calls will be suitable
290  * for almost all scenarios and does not require you to have such a deep
291  * understanding of the resource management issues:
292  * \code
293 // discover devices
294 libusb_device **list;
295 libusb_device *found = NULL;
296 size_t cnt = libusb_get_device_list(NULL, &list);
297 size_t i = 0;
298 int err = 0;
299 if (cnt < 0)
300         error();
301
302 for (i = 0; i < cnt; i++) {
303         libusb_device *device = list[i];
304         if (is_interesting(device)) {
305                 found = device;
306                 break;
307         }
308 }
309
310 if (found) {
311         libusb_device_handle *handle;
312
313         err = libusb_open(found, &handle);
314         if (err)
315                 error();
316         // etc
317 }
318
319 libusb_free_device_list(list, 1);
320 \endcode
321  *
322  * The two important points:
323  * - You asked libusb_free_device_list() to unreference the devices (2nd
324  *   parameter)
325  * - You opened the device before freeing the list and unreferencing the
326  *   devices
327  *
328  * If you ended up with a handle, you can now proceed to perform I/O on the
329  * device.
330  *
331  * \section devshandles Devices and device handles
332  * libusb has a concept of a USB device, represented by the
333  * \ref libusb_device opaque type. A device represents a USB device that
334  * is currently or was previously connected to the system. Using a reference
335  * to a device, you can determine certain information about the device (e.g.
336  * you can read the descriptor data).
337  *
338  * The libusb_get_device_list() function can be used to obtain a list of
339  * devices currently connected to the system. This is known as device
340  * discovery.
341  *
342  * Just because you have a reference to a device does not mean it is
343  * necessarily usable. The device may have been unplugged, you may not have
344  * permission to operate such device, or another program or driver may be
345  * using the device.
346  *
347  * When you've found a device that you'd like to operate, you must ask
348  * libusb to open the device using the libusb_open() function. Assuming
349  * success, libusb then returns you a <em>device handle</em>
350  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
351  * operate on the handle rather than the original device pointer.
352  *
353  * \section devref Device discovery and reference counting
354  *
355  * Device discovery (i.e. calling libusb_get_device_list()) returns a
356  * freshly-allocated list of devices. The list itself must be freed when
357  * you are done with it. libusb also needs to know when it is OK to free
358  * the contents of the list - the devices themselves.
359  *
360  * To handle these issues, libusb provides you with two separate items:
361  * - A function to free the list itself
362  * - A reference counting system for the devices inside
363  *
364  * New devices presented by the libusb_get_device_list() function all have a
365  * reference count of 1. You can increase and decrease reference count using
366  * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
367  * it's reference count reaches 0.
368  *
369  * With the above information in mind, the process of opening a device can
370  * be viewed as follows:
371  * -# Discover devices using libusb_get_device_list().
372  * -# Choose the device that you want to operate, and call libusb_open().
373  * -# Unref all devices in the discovered device list.
374  * -# Free the discovered device list.
375  *
376  * The order is important - you must not unreference the device before
377  * attempting to open it, because unreferencing it may destroy the device.
378  *
379  * For convenience, the libusb_free_device_list() function includes a
380  * parameter to optionally unreference all the devices in the list before
381  * freeing the list itself. This combines steps 3 and 4 above.
382  *
383  * As an implementation detail, libusb_open() actually adds a reference to
384  * the device in question. This is because the device remains available
385  * through the handle via libusb_get_device(). The reference is deleted during
386  * libusb_close().
387  */
388
389 /** @defgroup misc Miscellaneous */
390
391 /* we traverse usbfs without knowing how many devices we are going to find.
392  * so we create this discovered_devs model which is similar to a linked-list
393  * which grows when required. it can be freed once discovery has completed,
394  * eliminating the need for a list node in the libusb_device structure
395  * itself. */
396 #define DISCOVERED_DEVICES_SIZE_STEP 8
397
398 static struct discovered_devs *discovered_devs_alloc(void)
399 {
400         struct discovered_devs *ret =
401                 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
402
403         if (ret) {
404                 ret->len = 0;
405                 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
406         }
407         return ret;
408 }
409
410 /* append a device to the discovered devices collection. may realloc itself,
411  * returning new discdevs. returns NULL on realloc failure. */
412 struct discovered_devs *discovered_devs_append(
413         struct discovered_devs *discdevs, struct libusb_device *dev)
414 {
415         size_t len = discdevs->len;
416         size_t capacity;
417
418         /* if there is space, just append the device */
419         if (len < discdevs->capacity) {
420                 discdevs->devices[len] = libusb_ref_device(dev);
421                 discdevs->len++;
422                 return discdevs;
423         }
424
425         /* exceeded capacity, need to grow */
426         usbi_dbg("need to increase capacity");
427         capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
428         discdevs = realloc(discdevs,
429                 sizeof(*discdevs) + (sizeof(void *) * capacity));
430         if (discdevs) {
431                 discdevs->capacity = capacity;
432                 discdevs->devices[len] = libusb_ref_device(dev);
433                 discdevs->len++;
434         }
435
436         return discdevs;
437 }
438
439 static void discovered_devs_free(struct discovered_devs *discdevs)
440 {
441         size_t i;
442
443         for (i = 0; i < discdevs->len; i++)
444                 libusb_unref_device(discdevs->devices[i]);
445
446         free(discdevs);
447 }
448
449 /* Allocate a new device with a specific session ID. The returned device has
450  * a reference count of 1. */
451 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
452         unsigned long session_id)
453 {
454         size_t priv_size = usbi_backend->device_priv_size;
455         struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
456         int r;
457
458         if (!dev)
459                 return NULL;
460
461         r = pthread_mutex_init(&dev->lock, NULL);
462         if (r)
463                 return NULL;
464
465         dev->ctx = ctx;
466         dev->refcnt = 1;
467         dev->session_data = session_id;
468         memset(&dev->os_priv, 0, priv_size);
469
470         pthread_mutex_lock(&ctx->usb_devs_lock);
471         list_add(&dev->list, &ctx->usb_devs);
472         pthread_mutex_unlock(&ctx->usb_devs_lock);
473         return dev;
474 }
475
476 /* Perform some final sanity checks on a newly discovered device. If this
477  * function fails (negative return code), the device should not be added
478  * to the discovered device list. */
479 int usbi_sanitize_device(struct libusb_device *dev)
480 {
481         int r;
482         unsigned char raw_desc[DEVICE_DESC_LENGTH];
483         uint8_t num_configurations;
484         int host_endian;
485
486         r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
487         if (r < 0)
488                 return r;
489
490         num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
491         if (num_configurations > USB_MAXCONFIG) {
492                 usbi_err(DEVICE_CTX(dev), "too many configurations");
493                 return LIBUSB_ERROR_IO;
494         } else if (num_configurations < 1) {
495                 usbi_dbg("no configurations?");
496                 return LIBUSB_ERROR_IO;
497         }
498
499         dev->num_configurations = num_configurations;
500         return 0;
501 }
502
503 /* Examine libusb's internal list of known devices, looking for one with
504  * a specific session ID. Returns the matching device if it was found, and
505  * NULL otherwise. */
506 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
507         unsigned long session_id)
508 {
509         struct libusb_device *dev;
510         struct libusb_device *ret = NULL;
511
512         pthread_mutex_lock(&ctx->usb_devs_lock);
513         list_for_each_entry(dev, &ctx->usb_devs, list)
514                 if (dev->session_data == session_id) {
515                         ret = dev;
516                         break;
517                 }
518         pthread_mutex_unlock(&ctx->usb_devs_lock);
519
520         return ret;
521 }
522
523 /** @ingroup dev
524  * Returns a list of USB devices currently attached to the system. This is
525  * your entry point into finding a USB device to operate.
526  *
527  * You are expected to unreference all the devices when you are done with
528  * them, and then free the list with libusb_free_device_list(). Note that
529  * libusb_free_device_list() can unref all the devices for you. Be careful
530  * not to unreference a device you are about to open until after you have
531  * opened it.
532  *
533  * This return value of this function indicates the number of devices in
534  * the resultant list. The list is actually one element larger, as it is
535  * NULL-terminated.
536  *
537  * \param ctx the context to operate on, or NULL for the default context
538  * \param list output location for a list of devices. Must be later freed with
539  * libusb_free_device_list().
540  * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
541  * on memory allocation failure.
542  */
543 API_EXPORTED ssize_t libusb_get_device_list(libusb_context *ctx,
544         libusb_device ***list)
545 {
546         struct discovered_devs *discdevs = discovered_devs_alloc();
547         struct libusb_device **ret;
548         int r = 0;
549         size_t i;
550         ssize_t len;
551         USBI_GET_CONTEXT(ctx);
552         usbi_dbg("");
553
554         if (!discdevs)
555                 return LIBUSB_ERROR_NO_MEM;
556
557         r = usbi_backend->get_device_list(ctx, &discdevs);
558         if (r < 0) {
559                 len = r;
560                 goto out;
561         }
562
563         /* convert discovered_devs into a list */
564         len = discdevs->len;
565         ret = malloc(sizeof(void *) * (len + 1));
566         if (!ret) {
567                 len = LIBUSB_ERROR_NO_MEM;
568                 goto out;
569         }
570
571         ret[len] = NULL;
572         for (i = 0; i < len; i++) {
573                 struct libusb_device *dev = discdevs->devices[i];
574                 ret[i] = libusb_ref_device(dev);
575         }
576         *list = ret;
577
578 out:
579         discovered_devs_free(discdevs);
580         return len;
581 }
582
583 /** \ingroup dev
584  * Frees a list of devices previously discovered using
585  * libusb_get_device_list(). If the unref_devices parameter is set, the
586  * reference count of each device in the list is decremented by 1.
587  * \param list the list to free
588  * \param unref_devices whether to unref the devices in the list
589  */
590 API_EXPORTED void libusb_free_device_list(libusb_device **list,
591         int unref_devices)
592 {
593         if (!list)
594                 return;
595
596         if (unref_devices) {
597                 int i = 0;
598                 struct libusb_device *dev;
599
600                 while ((dev = list[i++]) != NULL)
601                         libusb_unref_device(dev);
602         }
603         free(list);
604 }
605
606 /** \ingroup dev
607  * Get the number of the bus that a device is connected to.
608  * \param dev a device
609  * \returns the bus number
610  */
611 API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev)
612 {
613         return dev->bus_number;
614 }
615
616 /** \ingroup dev
617  * Get the address of the device on the bus it is connected to.
618  * \param dev a device
619  * \returns the device address
620  */
621 API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev)
622 {
623         return dev->device_address;
624 }
625
626 /** \ingroup dev
627  * Convenience function to retrieve the wMaxPacketSize value for a particular
628  * endpoint in the active device configuration. This is useful for setting up
629  * isochronous transfers.
630  *
631  * \param dev a device
632  * \param endpoint address of the endpoint in question
633  * \returns the wMaxPacketSize value
634  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
635  * \returns LIBUSB_ERROR_OTHER on other failure
636  */
637 API_EXPORTED int libusb_get_max_packet_size(libusb_device *dev,
638         unsigned char endpoint)
639 {
640         int iface_idx;
641         struct libusb_config_descriptor *config;
642         int r;
643         
644         r = libusb_get_active_config_descriptor(dev, &config);
645         if (r < 0) {
646                 usbi_err(DEVICE_CTX(dev),
647                         "could not retrieve active config descriptor");
648                 return LIBUSB_ERROR_OTHER;
649         }
650
651         r = LIBUSB_ERROR_NOT_FOUND;
652         for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
653                 const struct libusb_interface *iface = &config->interface[iface_idx];
654                 int altsetting_idx;
655
656                 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
657                                 altsetting_idx++) {
658                         const struct libusb_interface_descriptor *altsetting
659                                 = &iface->altsetting[altsetting_idx];
660                         int ep_idx;
661
662                         for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
663                                 const struct libusb_endpoint_descriptor *ep =
664                                         &altsetting->endpoint[ep_idx];
665                                 if (ep->bEndpointAddress == endpoint) {
666                                         r = ep->wMaxPacketSize;
667                                         goto out;
668                                 }
669                         }
670                 }
671         }
672
673 out:
674         libusb_free_config_descriptor(config);
675         return r;
676 }
677
678 /** \ingroup dev
679  * Increment the reference count of a device.
680  * \param dev the device to reference
681  * \returns the same device
682  */
683 API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev)
684 {
685         pthread_mutex_lock(&dev->lock);
686         dev->refcnt++;
687         pthread_mutex_unlock(&dev->lock);
688         return dev;
689 }
690
691 /** \ingroup dev
692  * Decrement the reference count of a device. If the decrement operation
693  * causes the reference count to reach zero, the device shall be destroyed.
694  * \param dev the device to unreference
695  */
696 API_EXPORTED void libusb_unref_device(libusb_device *dev)
697 {
698         int refcnt;
699
700         if (!dev)
701                 return;
702
703         pthread_mutex_lock(&dev->lock);
704         refcnt = --dev->refcnt;
705         pthread_mutex_unlock(&dev->lock);
706
707         if (refcnt == 0) {
708                 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
709
710                 if (usbi_backend->destroy_device)
711                         usbi_backend->destroy_device(dev);
712
713                 pthread_mutex_lock(&dev->ctx->usb_devs_lock);
714                 list_del(&dev->list);
715                 pthread_mutex_unlock(&dev->ctx->usb_devs_lock);
716
717                 free(dev);
718         }
719 }
720
721 /** \ingroup dev
722  * Open a device and obtain a device handle. A handle allows you to perform
723  * I/O on the device in question.
724  *
725  * Internally, this function adds a reference to the device and makes it
726  * available to you through libusb_get_device(). This reference is removed
727  * during libusb_close().
728  *
729  * This is a non-blocking function; no requests are sent over the bus.
730  *
731  * \param dev the device to open
732  * \param handle output location for the returned device handle pointer. Only
733  * populated when the return code is 0.
734  * \returns 0 on success
735  * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
736  * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
737  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
738  * \returns another LIBUSB_ERROR code on other failure
739  */
740 API_EXPORTED int libusb_open(libusb_device *dev, libusb_device_handle **handle)
741 {
742         struct libusb_device_handle *_handle;
743         size_t priv_size = usbi_backend->device_handle_priv_size;
744         int r;
745         usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
746
747         _handle = malloc(sizeof(*_handle) + priv_size);
748         if (!_handle)
749                 return LIBUSB_ERROR_NO_MEM;
750
751         r = pthread_mutex_init(&_handle->lock, NULL);
752         if (r)
753                 return LIBUSB_ERROR_OTHER;
754
755         _handle->dev = libusb_ref_device(dev);
756         _handle->claimed_interfaces = 0;
757         memset(&_handle->os_priv, 0, priv_size);
758
759         r = usbi_backend->open(_handle);
760         if (r < 0) {
761                 libusb_unref_device(dev);
762                 free(_handle);
763                 return r;
764         }
765
766         pthread_mutex_lock(&dev->ctx->open_devs_lock);
767         list_add(&_handle->list, &dev->ctx->open_devs);
768         pthread_mutex_unlock(&dev->ctx->open_devs_lock);
769         *handle = _handle;
770         return 0;
771 }
772
773 /** \ingroup dev
774  * Convenience function for finding a device with a particular
775  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
776  * for those scenarios where you are using libusb to knock up a quick test
777  * application - it allows you to avoid calling libusb_get_device_list() and
778  * worrying about traversing/freeing the list.
779  *
780  * This function has limitations and is hence not intended for use in real
781  * applications: if multiple devices have the same IDs it will only
782  * give you the first one, etc.
783  *
784  * \param ctx the context to operate on, or NULL for the default context
785  * \param vendor_id the idVendor value to search for
786  * \param product_id the idProduct value to search for
787  * \returns a handle for the first found device, or NULL on error or if the
788  * device could not be found. */
789 API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid(
790         libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
791 {
792         struct libusb_device **devs;
793         struct libusb_device *found = NULL;
794         struct libusb_device *dev;
795         struct libusb_device_handle *handle = NULL;
796         size_t i = 0;
797         int r;
798
799         if (libusb_get_device_list(ctx, &devs) < 0)
800                 return NULL;
801
802         while ((dev = devs[i++]) != NULL) {
803                 struct libusb_device_descriptor desc;
804                 r = libusb_get_device_descriptor(dev, &desc);
805                 if (r < 0)
806                         goto out;
807                 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
808                         found = dev;
809                         break;
810                 }
811         }
812
813         if (found) {
814                 r = libusb_open(found, &handle);
815                 if (r < 0)
816                         handle = NULL;
817         }
818
819 out:
820         libusb_free_device_list(devs, 1);
821         return handle;
822 }
823
824 static void do_close(struct libusb_device_handle *dev_handle)
825 {
826         usbi_backend->close(dev_handle);
827         libusb_unref_device(dev_handle->dev);
828 }
829
830 /** \ingroup dev
831  * Close a device handle. Should be called on all open handles before your
832  * application exits.
833  *
834  * Internally, this function destroys the reference that was added by
835  * libusb_open() on the given device.
836  *
837  * This is a non-blocking function; no requests are sent over the bus.
838  *
839  * \param dev_handle the handle to close
840  */
841 API_EXPORTED void libusb_close(libusb_device_handle *dev_handle)
842 {
843         if (!dev_handle)
844                 return;
845         usbi_dbg("");
846
847         pthread_mutex_lock(&HANDLE_CTX(dev_handle)->open_devs_lock);
848         list_del(&dev_handle->list);
849         pthread_mutex_unlock(&HANDLE_CTX(dev_handle)->open_devs_lock);
850
851         do_close(dev_handle);
852         free(dev_handle);
853 }
854
855 /** \ingroup dev
856  * Get the underlying device for a handle. This function does not modify
857  * the reference count of the returned device, so do not feel compelled to
858  * unreference it when you are done.
859  * \param dev_handle a device handle
860  * \returns the underlying device
861  */
862 API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle)
863 {
864         return dev_handle->dev;
865 }
866
867 /** \ingroup dev
868  * Determine the bConfigurationValue of the currently active configuration.
869  *
870  * You could formulate your own control request to obtain this information,
871  * but this function has the advantage that it may be able to retrieve the
872  * information from operating system caches (no I/O involved).
873  *
874  * If the OS does not cache this information, then this function will block
875  * while a control transfer is submitted to retrieve the information.
876  *
877  * This function will return a value of 0 in the <tt>config</tt> output
878  * parameter if the device is in unconfigured state.
879  *
880  * \param dev a device handle
881  * \param config output location for the bConfigurationValue of the active
882  * configuration (only valid for return code 0)
883  * \returns 0 on success
884  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
885  * \returns another LIBUSB_ERROR code on other failure
886  */
887 API_EXPORTED int libusb_get_configuration(libusb_device_handle *dev,
888         int *config)
889 {
890         int r = LIBUSB_ERROR_NOT_SUPPORTED;
891
892         usbi_dbg("");
893         if (usbi_backend->get_configuration)
894                 r = usbi_backend->get_configuration(dev, config);
895
896         if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
897                 uint8_t tmp = 0;
898                 usbi_dbg("falling back to control message");
899                 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
900                         LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
901                 if (r == 0) {
902                         usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
903                         r = LIBUSB_ERROR_IO;
904                 } else if (r == 1) {
905                         r = 0;
906                         *config = tmp;
907                 } else {
908                         usbi_dbg("control failed, error %d", r);
909                 }
910         }
911
912         if (r == 0)
913                 usbi_dbg("active config %d", *config);
914
915         return r;
916 }
917
918 /** \ingroup dev
919  * Set the active configuration for a device.
920  *
921  * The operating system may or may not have already set an active
922  * configuration on the device. It is up to your application to ensure the
923  * correct configuration is selected before you attempt to claim interfaces
924  * and perform other operations.
925  * 
926  * If you call this function on a device already configured with the selected
927  * configuration, then this function will act as a lightweight device reset:
928  * it will issue a SET_CONFIGURATION request using the current configuration,
929  * causing most USB-related device state to be reset (altsetting reset to zero,
930  * endpoint halts cleared, toggles reset).
931  *
932  * You cannot change/reset configuration if your application has claimed
933  * interfaces - you should free them with libusb_release_interface() first.
934  * You cannot change/reset configuration if other applications or drivers have
935  * claimed interfaces.
936  *
937  * A configuration value of -1 will put the device in unconfigured state.
938  * The USB specifications state that a configuration value of 0 does this,
939  * however buggy devices exist which actually have a configuration 0.
940  *
941  * You should always use this function rather than formulating your own
942  * SET_CONFIGURATION control request. This is because the underlying operating
943  * system needs to know when such changes happen.
944  *
945  * This is a blocking function.
946  *
947  * \param dev a device handle
948  * \param configuration the bConfigurationValue of the configuration you
949  * wish to activate, or -1 if you wish to put the device in unconfigured state
950  * \returns 0 on success
951  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
952  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
953  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
954  * \returns another LIBUSB_ERROR code on other failure
955  */
956 API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev,
957         int configuration)
958 {
959         usbi_dbg("configuration %d", configuration);
960         return usbi_backend->set_configuration(dev, configuration);
961 }
962
963 /** \ingroup dev
964  * Claim an interface on a given device handle. You must claim the interface
965  * you wish to use before you can perform I/O on any of its endpoints.
966  *
967  * It is legal to attempt to claim an already-claimed interface, in which
968  * case libusb just returns 0 without doing anything.
969  *
970  * Claiming of interfaces is a purely logical operation; it does not cause
971  * any requests to be sent over the bus. Interface claiming is used to
972  * instruct the underlying operating system that your application wishes
973  * to take ownership of the interface.
974  *
975  * This is a non-blocking function.
976  *
977  * \param dev a device handle
978  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
979  * wish to claim
980  * \returns 0 on success
981  * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
982  * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
983  * interface
984  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
985  * \returns a LIBUSB_ERROR code on other failure
986  */
987 API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev,
988         int interface_number)
989 {
990         int r = 0;
991
992         usbi_dbg("interface %d", interface_number);
993         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
994                 return LIBUSB_ERROR_INVALID_PARAM;
995
996         pthread_mutex_lock(&dev->lock);
997         if (dev->claimed_interfaces & (1 << interface_number))
998                 goto out;
999
1000         r = usbi_backend->claim_interface(dev, interface_number);
1001         if (r == 0)
1002                 dev->claimed_interfaces |= 1 << interface_number;
1003
1004 out:
1005         pthread_mutex_unlock(&dev->lock);
1006         return r;
1007 }
1008
1009 /** \ingroup dev
1010  * Release an interface previously claimed with libusb_claim_interface(). You
1011  * should release all claimed interfaces before closing a device handle.
1012  *
1013  * This is a blocking function. A SET_INTERFACE control request will be sent
1014  * to the device, resetting interface state to the first alternate setting.
1015  *
1016  * \param dev a device handle
1017  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1018  * previously-claimed interface
1019  * \returns 0 on success
1020  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1021  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1022  * \returns another LIBUSB_ERROR code on other failure
1023  */
1024 API_EXPORTED int libusb_release_interface(libusb_device_handle *dev,
1025         int interface_number)
1026 {
1027         int r;
1028
1029         usbi_dbg("interface %d", interface_number);
1030         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1031                 return LIBUSB_ERROR_INVALID_PARAM;
1032
1033         pthread_mutex_lock(&dev->lock);
1034         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1035                 r = LIBUSB_ERROR_NOT_FOUND;
1036                 goto out;
1037         }
1038
1039         r = usbi_backend->release_interface(dev, interface_number);
1040         if (r == 0)
1041                 dev->claimed_interfaces &= ~(1 << interface_number);
1042
1043 out:
1044         pthread_mutex_unlock(&dev->lock);
1045         return r;
1046 }
1047
1048 /** \ingroup dev
1049  * Activate an alternate setting for an interface. The interface must have
1050  * been previously claimed with libusb_claim_interface().
1051  *
1052  * You should always use this function rather than formulating your own
1053  * SET_INTERFACE control request. This is because the underlying operating
1054  * system needs to know when such changes happen.
1055  *
1056  * This is a blocking function.
1057  *
1058  * \param dev a device handle
1059  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1060  * previously-claimed interface
1061  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1062  * setting to activate
1063  * \returns 0 on success
1064  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1065  * requested alternate setting does not exist
1066  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1067  * \returns another LIBUSB_ERROR code on other failure
1068  */
1069 API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev,
1070         int interface_number, int alternate_setting)
1071 {
1072         usbi_dbg("interface %d altsetting %d",
1073                 interface_number, alternate_setting);
1074         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1075                 return LIBUSB_ERROR_INVALID_PARAM;
1076
1077         pthread_mutex_lock(&dev->lock);
1078         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1079                 pthread_mutex_unlock(&dev->lock);       
1080                 return LIBUSB_ERROR_NOT_FOUND;
1081         }
1082         pthread_mutex_unlock(&dev->lock);
1083
1084         return usbi_backend->set_interface_altsetting(dev, interface_number,
1085                 alternate_setting);
1086 }
1087
1088 /** \ingroup dev
1089  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1090  * are unable to receive or transmit data until the halt condition is stalled.
1091  *
1092  * You should cancel all pending transfers before attempting to clear the halt
1093  * condition.
1094  *
1095  * This is a blocking function.
1096  *
1097  * \param dev a device handle
1098  * \param endpoint the endpoint to clear halt status
1099  * \returns 0 on success
1100  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1101  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1102  * \returns another LIBUSB_ERROR code on other failure
1103  */
1104 API_EXPORTED int libusb_clear_halt(libusb_device_handle *dev,
1105         unsigned char endpoint)
1106 {
1107         usbi_dbg("endpoint %x", endpoint);
1108         return usbi_backend->clear_halt(dev, endpoint);
1109 }
1110
1111 /** \ingroup dev
1112  * Perform a USB port reset to reinitialize a device. The system will attempt
1113  * to restore the previous configuration and alternate settings after the
1114  * reset has completed.
1115  *
1116  * If the reset fails, the descriptors change, or the previous state cannot be
1117  * restored, the device will appear to be disconnected and reconnected. This
1118  * means that the device handle is no longer valid (you should close it) and
1119  * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1120  * when this is the case.
1121  *
1122  * This is a blocking function which usually incurs a noticeable delay.
1123  *
1124  * \param dev a handle of the device to reset
1125  * \returns 0 on success
1126  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1127  * device has been disconnected
1128  * \returns another LIBUSB_ERROR code on other failure
1129  */
1130 API_EXPORTED int libusb_reset_device(libusb_device_handle *dev)
1131 {
1132         usbi_dbg("");
1133         return usbi_backend->reset_device(dev);
1134 }
1135
1136 /** \ingroup dev
1137  * Determine if a kernel driver is active on an interface. If a kernel driver
1138  * is active, you cannot claim the interface, and libusb will be unable to
1139  * perform I/O.
1140  *
1141  * \param dev a device handle
1142  * \param interface the interface to check
1143  * \returns 0 if no kernel driver is active
1144  * \returns 1 if a kernel driver is active
1145  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1146  * \returns another LIBUSB_ERROR code on other failure
1147  * \see libusb_detach_kernel_driver()
1148  */
1149 API_EXPORTED int libusb_kernel_driver_active(libusb_device_handle *dev,
1150         int interface)
1151 {
1152         usbi_dbg("interface %d", interface);
1153         if (usbi_backend->kernel_driver_active)
1154                 return usbi_backend->kernel_driver_active(dev, interface);
1155         else
1156                 return LIBUSB_ERROR_NOT_SUPPORTED;
1157 }
1158
1159 /** \ingroup dev
1160  * Detach a kernel driver from an interface. If successful, you will then be
1161  * able to claim the interface and perform I/O.
1162  *
1163  * \param dev a device handle
1164  * \param interface the interface to detach the driver from
1165  * \returns 0 on success
1166  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1167  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1168  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1169  * \returns another LIBUSB_ERROR code on other failure
1170  * \see libusb_kernel_driver_active()
1171  */
1172 API_EXPORTED int libusb_detach_kernel_driver(libusb_device_handle *dev,
1173         int interface)
1174 {
1175         usbi_dbg("interface %d", interface);
1176         if (usbi_backend->detach_kernel_driver)
1177                 return usbi_backend->detach_kernel_driver(dev, interface);
1178         else
1179                 return LIBUSB_ERROR_NOT_SUPPORTED;
1180 }
1181
1182 /** \ingroup lib
1183  * Set message verbosity.
1184  *  - Level 0: no messages ever printed by the library (default)
1185  *  - Level 1: error messages are printed to stderr
1186  *  - Level 2: warning and error messages are printed to stderr
1187  *  - Level 3: informational messages are printed to stdout, warning and error
1188  *    messages are printed to stderr
1189  *
1190  * The default level is 0, which means no messages are ever printed. If you
1191  * choose to increase the message verbosity level, ensure that your
1192  * application does not close the stdout/stderr file descriptors.
1193  *
1194  * You are advised to set level 3. libusb is conservative with it's message
1195  * logging and most of the time, will only log messages that explain error
1196  * conditions and other oddities. This will help you debug your software.
1197  *
1198  * If the LIBUSB_DEBUG environment variable was set when libusb was
1199  * initialized, this function does nothing: the message verbosity is fixed
1200  * to the value in the environment variable.
1201  *
1202  * If libusb was compiled without any message logging, this function does
1203  * nothing: you'll never get any messages.
1204  *
1205  * If libusb was compiled with verbose debug message logging, this function
1206  * does nothing: you'll always get messages from all levels.
1207  *
1208  * \param ctx the context to operate on, or NULL for the default context
1209  * \param level debug level to set
1210  */
1211 API_EXPORTED void libusb_set_debug(libusb_context *ctx, int level)
1212 {
1213         USBI_GET_CONTEXT(ctx);
1214         if (!ctx->debug_fixed)
1215                 ctx->debug = level;
1216 }
1217
1218 /** \ingroup lib
1219  * Initialize libusb. This function must be called before calling any other
1220  * libusb function.
1221  * \param context Optional output location for context pointer.
1222  * Only valid on return code 0.
1223  * \returns 0 on success, or a LIBUSB_ERROR code on failure
1224  */
1225 API_EXPORTED int libusb_init(libusb_context **context)
1226 {
1227         char *dbg = getenv("LIBUSB_DEBUG");
1228         struct libusb_context *ctx = malloc(sizeof(*ctx));
1229
1230         if (!ctx)
1231                 return LIBUSB_ERROR_NO_MEM;
1232         memset(ctx, 0, sizeof(*ctx));
1233
1234         if (dbg) {
1235                 ctx->debug = atoi(dbg);
1236                 if (ctx->debug)
1237                         ctx->debug_fixed = 1;
1238         }
1239
1240         usbi_dbg("");
1241         if (usbi_backend->init) {
1242                 int r = usbi_backend->init(ctx);
1243                 if (r) {
1244                         free(ctx);
1245                         return r;
1246                 }
1247         }
1248
1249         pthread_mutex_init(&ctx->usb_devs_lock, NULL);
1250         pthread_mutex_init(&ctx->open_devs_lock, NULL);
1251         list_init(&ctx->usb_devs);
1252         list_init(&ctx->open_devs);
1253         usbi_io_init(ctx);
1254
1255         pthread_mutex_lock(&default_context_lock);
1256         if (!usbi_default_context) {
1257                 usbi_dbg("created default context");
1258                 usbi_default_context = ctx;
1259         }
1260         pthread_mutex_unlock(&default_context_lock);
1261
1262         if (context)
1263                 *context = ctx;
1264         return 0;
1265 }
1266
1267 /** \ingroup lib
1268  * Deinitialize libusb. Should be called after closing all open devices and
1269  * before your application terminates.
1270  * \param ctx the context to deinitialize, or NULL for the default context
1271  */
1272 API_EXPORTED void libusb_exit(struct libusb_context *ctx)
1273 {
1274         USBI_GET_CONTEXT(ctx);
1275         usbi_dbg("");
1276
1277         pthread_mutex_lock(&ctx->open_devs_lock);
1278         if (!list_empty(&ctx->open_devs)) {
1279                 struct libusb_device_handle *devh;
1280                 struct libusb_device_handle *tmp;
1281
1282                 usbi_dbg("naughty app left some devices open!");
1283                 list_for_each_entry_safe(devh, tmp, &ctx->open_devs, list) {
1284                         list_del(&devh->list);
1285                         do_close(devh);
1286                         free(devh);
1287                 }
1288         }
1289         pthread_mutex_unlock(&ctx->open_devs_lock);
1290
1291         if (usbi_backend->exit)
1292                 usbi_backend->exit();
1293         
1294         pthread_mutex_lock(&default_context_lock);
1295         if (ctx == usbi_default_context) {
1296                 usbi_dbg("freeing default context");
1297                 usbi_default_context = NULL;
1298         }
1299         pthread_mutex_unlock(&default_context_lock);
1300
1301         free(ctx);
1302 }
1303
1304 void usbi_log(struct libusb_context *ctx, enum usbi_log_level level,
1305         const char *function, const char *format, ...)
1306 {
1307         va_list args;
1308         FILE *stream = stdout;
1309         const char *prefix;
1310
1311 #ifndef ENABLE_DEBUG_LOGGING
1312         USBI_GET_CONTEXT(ctx);
1313         if (!ctx->debug)
1314                 return;
1315         if (level == LOG_LEVEL_WARNING && ctx->debug < 2)
1316                 return;
1317         if (level == LOG_LEVEL_INFO && ctx->debug < 3)
1318                 return;
1319 #endif
1320
1321         switch (level) {
1322         case LOG_LEVEL_INFO:
1323                 prefix = "info";
1324                 break;
1325         case LOG_LEVEL_WARNING:
1326                 stream = stderr;
1327                 prefix = "warning";
1328                 break;
1329         case LOG_LEVEL_ERROR:
1330                 stream = stderr;
1331                 prefix = "error";
1332                 break;
1333         case LOG_LEVEL_DEBUG:
1334                 stream = stderr;
1335                 prefix = "debug";
1336                 break;
1337         default:
1338                 stream = stderr;
1339                 prefix = "unknown";
1340                 break;
1341         }
1342
1343         fprintf(stream, "libusb:%s [%s] ", prefix, function);
1344
1345         va_start (args, format);
1346         vfprintf(stream, format, args);
1347         va_end (args);
1348
1349         fprintf(stream, "\n");
1350 }
1351