libusb_get_device_list() can return negative error code
[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 static struct list_head usb_devs;
41 static pthread_mutex_t usb_devs_lock = PTHREAD_MUTEX_INITIALIZER;
42
43 struct list_head usbi_open_devs;
44 pthread_mutex_t usbi_open_devs_lock = PTHREAD_MUTEX_INITIALIZER;
45
46 /**
47  * \mainpage libusb-1.0 API Reference
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  * To begin reading the API documentation, start with the Modules page which
66  * links to the different categories of libusb's functionality.
67  *
68  * libusb does have imperfections. The \ref caveats "caveats" page attempts
69  * to document these.
70  */
71
72 /**
73  * \page caveats Caveats
74  *
75  * \section devresets Device resets
76  *
77  * The libusb_reset_device() function allows you to reset a device. If your
78  * program has to call such a function, it should obviously be aware that
79  * the reset will cause device state to change (e.g. register values may be
80  * reset).
81  *
82  * The problem is that any other program could reset the device your program
83  * is working with, at any time. libusb does not offer a mechanism to inform
84  * you when this has happened, so it will not be clear to your own program
85  * why the device state has changed.
86  *
87  * Ultimately, this is a limitation of writing drivers in userspace.
88  * Separation from the USB stack in the underlying kernel makes it difficult
89  * for the operating system to deliver such notifications to your program.
90  * The Linux kernel USB stack allows such reset notifications to be delivered
91  * to in-kernel USB drivers, but it is not clear how such notifications could
92  * be delivered to second-class drivers that live in userspace.
93  *
94  * \section blockonly Blocking-only functionality
95  *
96  * The functionality listed below is only available through synchronous,
97  * blocking functions. There are no asynchronous/non-blocking alternatives,
98  * and no clear ways of implementing these.
99  *
100  * - Configuration activation (libusb_set_configuration())
101  * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
102  * - Clearing of halt/stall condition (libusb_clear_halt())
103  * - Device resets (libusb_reset_device())
104  */
105
106 /**
107  * @defgroup lib Library initialization/deinitialization
108  * This page details how to initialize and deinitialize libusb. Initialization
109  * must be performed before using any libusb functionality, and similarly you
110  * must not call any libusb functions after deinitialization.
111  */
112
113 /**
114  * @defgroup dev Device handling and enumeration
115  * The functionality documented below is designed to help with the following
116  * operations:
117  * - Enumerating the USB devices currently attached to the system
118  * - Choosing a device to operate from your software
119  * - Opening and closing the chosen device
120  *
121  * \section nutshell In a nutshell...
122  *
123  * The description below really makes things sound more complicated than they
124  * actually are. The following sequence of function calls will be suitable
125  * for almost all scenarios and does not require you to have such a deep
126  * understanding of the resource management issues:
127  * \code
128 // discover devices
129 libusb_device **list;
130 libusb_device *found = NULL;
131 size_t cnt = libusb_get_device_list(&list);
132 size_t i = 0;
133 if (cnt < 0)
134         error();
135
136 for (i = 0; i < cnt; i++) {
137         libusb_device *device = list[i];
138         if (is_interesting(device)) {
139                 found = device;
140                 break;
141         }
142 }
143
144 if (found) {
145         libusb_device_handle *handle = libusb_open(found);
146         // etc
147 }
148
149 libusb_free_device_list(list, 1);
150 \endcode
151  *
152  * The two important points:
153  * - You asked libusb_free_device_list() to unreference the devices (2nd
154  *   parameter)
155  * - You opened the device before freeing the list and unreferencing the
156  *   devices
157  *
158  * If you ended up with a handle, you can now proceed to perform I/O on the
159  * device.
160  *
161  * \section devshandles Devices and device handles
162  * libusb has a concept of a USB device, represented by the
163  * \ref libusb_device opaque type. A device represents a USB device that
164  * is currently or was previously connected to the system. Using a reference
165  * to a device, you can determine certain information about the device (e.g.
166  * you can read the descriptor data).
167  *
168  * The libusb_get_device_list() function can be used to obtain a list of
169  * devices currently connected to the system. This is known as device
170  * discovery.
171  *
172  * Just because you have a reference to a device does not mean it is
173  * necessarily usable. The device may have been unplugged, you may not have
174  * permission to operate such device, or another program or driver may be
175  * using the device.
176  *
177  * When you've found a device that you'd like to operate, you must ask
178  * libusb to open the device using the libusb_open() function. Assuming
179  * success, libusb then returns you a <em>device handle</em>
180  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
181  * operate on the handle rather than the original device pointer.
182  *
183  * \section devref Device discovery and reference counting
184  *
185  * Device discovery (i.e. calling libusb_get_device_list()) returns a
186  * freshly-allocated list of devices. The list itself must be freed when
187  * you are done with it. libusb also needs to know when it is OK to free
188  * the contents of the list - the devices themselves.
189  *
190  * To handle these issues, libusb provides you with two separate items:
191  * - A function to free the list itself
192  * - A reference counting system for the devices inside
193  *
194  * New devices presented by the libusb_get_device_list() function all have a
195  * reference count of 1. You can increase and decrease reference count using
196  * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
197  * it's reference count reaches 0.
198  *
199  * With the above information in mind, the process of opening a device can
200  * be viewed as follows:
201  * -# Discover devices using libusb_get_device_list().
202  * -# Choose the device that you want to operate, and call libusb_open().
203  * -# Unref all devices in the discovered device list.
204  * -# Free the discovered device list.
205  *
206  * The order is important - you must not unreference the device before
207  * attempting to open it, because unreferencing it may destroy the device.
208  *
209  * For convenience, the libusb_free_device_list() function includes a
210  * parameter to optionally unreference all the devices in the list before
211  * freeing the list itself. This combines steps 3 and 4 above.
212  *
213  * As an implementation detail, libusb_open() actually adds a reference to
214  * the device in question. This is because the device remains available
215  * through the handle via libusb_get_device(). The reference is deleted during
216  * libusb_close().
217  */
218
219 /**
220  * @defgroup misc Miscellaneous structures and constants
221  * This page documents structures and constants that don't belong anywhere
222  * else
223  */
224
225 /* we traverse usbfs without knowing how many devices we are going to find.
226  * so we create this discovered_devs model which is similar to a linked-list
227  * which grows when required. it can be freed once discovery has completed,
228  * eliminating the need for a list node in the libusb_device structure
229  * itself. */
230 #define DISCOVERED_DEVICES_SIZE_STEP 8
231
232 static struct discovered_devs *discovered_devs_alloc(void)
233 {
234         struct discovered_devs *ret =
235                 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
236
237         if (ret) {
238                 ret->len = 0;
239                 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
240         }
241         return ret;
242 }
243
244 /* append a device to the discovered devices collection. may realloc itself,
245  * returning new discdevs. returns NULL on realloc failure. */
246 struct discovered_devs *discovered_devs_append(
247         struct discovered_devs *discdevs, struct libusb_device *dev)
248 {
249         size_t len = discdevs->len;
250         size_t capacity;
251
252         /* if there is space, just append the device */
253         if (len < discdevs->capacity) {
254                 discdevs->devices[len] = libusb_ref_device(dev);
255                 discdevs->len++;
256                 return discdevs;
257         }
258
259         /* exceeded capacity, need to grow */
260         usbi_dbg("need to increase capacity");
261         capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
262         discdevs = realloc(discdevs,
263                 sizeof(*discdevs) + (sizeof(void *) * capacity));
264         if (discdevs) {
265                 discdevs->capacity = capacity;
266                 discdevs->devices[len] = libusb_ref_device(dev);
267                 discdevs->len++;
268         }
269
270         return discdevs;
271 }
272
273 static void discovered_devs_free(struct discovered_devs *discdevs)
274 {
275         size_t i;
276
277         for (i = 0; i < discdevs->len; i++)
278                 libusb_unref_device(discdevs->devices[i]);
279
280         free(discdevs);
281 }
282
283 /* allocate a new device with reference count 1 */
284 struct libusb_device *usbi_alloc_device(unsigned long session_id)
285 {
286         size_t priv_size = usbi_backend->device_priv_size;
287         struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
288         int r;
289
290         if (!dev)
291                 return NULL;
292
293         r = pthread_mutex_init(&dev->lock, NULL);
294         if (r)
295                 return NULL;
296
297         dev->refcnt = 1;
298         dev->session_data = session_id;
299         memset(&dev->os_priv, 0, priv_size);
300
301         pthread_mutex_lock(&usb_devs_lock);
302         list_add(&dev->list, &usb_devs);
303         pthread_mutex_unlock(&usb_devs_lock);
304         return dev;
305 }
306
307 /* call the OS discovery routines to populate descriptors etc */
308 int usbi_discover_device(struct libusb_device *dev)
309 {
310         int r;
311         int i;
312         void *user_data;
313         unsigned char raw_desc[DEVICE_DESC_LENGTH];
314         size_t alloc_size;
315
316         dev->config = NULL;
317
318         r = usbi_backend->begin_discovery(dev, &user_data);
319         if (r < 0)
320                 return r;
321         
322         r = usbi_backend->get_device_descriptor(dev, raw_desc, user_data);
323         if (r < 0)
324                 goto err;
325
326         usbi_parse_descriptor(raw_desc, "bbWbbbbWWWbbbb", &dev->desc);
327
328         if (dev->desc.bNumConfigurations > USB_MAXCONFIG) {
329                 usbi_err("too many configurations");
330                 r = LIBUSB_ERROR_IO;
331                 goto err;
332         }
333
334         if (dev->desc.bNumConfigurations < 1) {
335                 usbi_dbg("no configurations?");
336                 r = LIBUSB_ERROR_IO;
337                 goto err;
338         }
339
340         alloc_size = dev->desc.bNumConfigurations
341                 * sizeof(struct libusb_config_descriptor);
342         dev->config = malloc(alloc_size);
343         if (!dev->config) {
344                 r = LIBUSB_ERROR_NO_MEM;
345                 goto err;
346         }
347
348         memset(dev->config, 0, alloc_size);
349         for (i = 0; i < dev->desc.bNumConfigurations; i++) {
350                 unsigned char tmp[8];
351                 unsigned char *bigbuffer;
352                 struct libusb_config_descriptor config;
353
354                 r = usbi_backend->get_config_descriptor(dev, i, tmp, sizeof(tmp),
355                         user_data);
356                 if (r < 0)
357                         goto err;
358
359                 usbi_parse_descriptor(tmp, "bbw", &config);
360
361                 bigbuffer = malloc(config.wTotalLength);
362                 if (!bigbuffer) {
363                         r = LIBUSB_ERROR_NO_MEM;
364                         goto err;
365                 }
366
367                 r = usbi_backend->get_config_descriptor(dev, i, bigbuffer,
368                         config.wTotalLength, user_data);
369                 if (r < 0) {
370                         free(bigbuffer);
371                         goto err;
372                 }
373
374                 r = usbi_parse_configuration(&dev->config[i], bigbuffer);
375                 free(bigbuffer);
376                 if (r < 0) {
377                         usbi_err("parse_configuration failed with code %d", r);
378                         goto err;
379                 } else if (r > 0) {
380                         usbi_warn("descriptor data still left\n");
381                 }
382         }
383
384         usbi_backend->end_discovery(dev, user_data);
385         return 0;
386
387 err:
388         if (dev->config) {
389                 usbi_clear_configurations(dev);
390                 free(dev->config);
391                 dev->config = NULL;
392         }
393
394         usbi_backend->end_discovery(dev, user_data);
395         return r;
396 }
397
398 struct libusb_device *usbi_get_device_by_session_id(unsigned long session_id)
399 {
400         struct libusb_device *dev;
401         struct libusb_device *ret = NULL;
402
403         pthread_mutex_lock(&usb_devs_lock);
404         list_for_each_entry(dev, &usb_devs, list)
405                 if (dev->session_data == session_id) {
406                         ret = dev;
407                         break;
408                 }
409         pthread_mutex_unlock(&usb_devs_lock);
410
411         return ret;
412 }
413
414 /** @ingroup dev
415  * Returns a list of USB devices currently attached to the system. This is
416  * your entry point into finding a USB device to operate.
417  *
418  * You are expected to unreference all the devices when you are done with
419  * them, and then free the list with libusb_free_device_list(). Note that
420  * libusb_free_device_list() can unref all the devices for you. Be careful
421  * not to unreference a device you are about to open until after you have
422  * opened it.
423  *
424  * This return value of this function indicates the number of devices in
425  * the resultant list. The list is actually one element larger, as it is
426  * NULL-terminated.
427  *
428  * \param list output location for a list of devices. Must be later freed with
429  * libusb_free_device_list().
430  * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
431  * on memory allocation failure.
432  */
433 API_EXPORTED ssize_t libusb_get_device_list(libusb_device ***list)
434 {
435         struct discovered_devs *discdevs = discovered_devs_alloc();
436         struct libusb_device **ret;
437         int r = 0;
438         size_t i;
439         ssize_t len;
440         usbi_dbg("");
441
442         if (!discdevs)
443                 return LIBUSB_ERROR_NO_MEM;
444
445         r = usbi_backend->get_device_list(&discdevs);
446         if (r < 0) {
447                 len = r;
448                 goto out;
449         }
450
451         /* convert discovered_devs into a list */
452         len = discdevs->len;
453         ret = malloc(sizeof(void *) * (len + 1));
454         if (!ret) {
455                 len = LIBUSB_ERROR_NO_MEM;
456                 goto out;
457         }
458
459         ret[len] = NULL;
460         for (i = 0; i < len; i++) {
461                 struct libusb_device *dev = discdevs->devices[i];
462                 ret[i] = libusb_ref_device(dev);
463         }
464         *list = ret;
465
466 out:
467         discovered_devs_free(discdevs);
468         return len;
469 }
470
471 /** \ingroup dev
472  * Frees a list of devices previously discovered using
473  * libusb_get_device_list(). If the unref_devices parameter is set, the
474  * reference count of each device in the list is decremented by 1.
475  * \param list the list to free
476  * \param unref_devices whether to unref the devices in the list
477  */
478 API_EXPORTED void libusb_free_device_list(libusb_device **list,
479         int unref_devices)
480 {
481         if (!list)
482                 return;
483
484         if (unref_devices) {
485                 int i = 0;
486                 struct libusb_device *dev;
487
488                 while ((dev = list[i++]) != NULL)
489                         libusb_unref_device(dev);
490         }
491         free(list);
492 }
493
494 /** \ingroup dev
495  * Get the number of the bus that a device is connected to.
496  * \param dev a device
497  * \returns the bus number
498  */
499 API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev)
500 {
501         return dev->bus_number;
502 }
503
504 /** \ingroup dev
505  * Get the address of the device on the bus it is connected to.
506  * \param dev a device
507  * \returns the device address
508  */
509 API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev)
510 {
511         return dev->device_address;
512 }
513
514 /** \ingroup dev
515  * Convenience function to retrieve the wMaxPacketSize value for a particular
516  * endpoint. This is useful for setting up isochronous transfers.
517  *
518  * \param dev a device
519  * \param endpoint address of the endpoint in question
520  * \returns the wMaxPacketSize value, or LIBUSB_ERROR_NOT_FOUND if the endpoint
521  * does not exist.
522  */
523 API_EXPORTED int libusb_get_max_packet_size(libusb_device *dev,
524         unsigned char endpoint)
525 {
526         int iface_idx;
527         /* FIXME: active config considerations? */
528         struct libusb_config_descriptor *config = dev->config;
529
530         for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
531                 const struct libusb_interface *iface = &config->interface[iface_idx];
532                 int altsetting_idx;
533
534                 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
535                                 altsetting_idx++) {
536                         const struct libusb_interface_descriptor *altsetting
537                                 = &iface->altsetting[altsetting_idx];
538                         int ep_idx;
539
540                         for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
541                                 const struct libusb_endpoint_descriptor *ep =
542                                         &altsetting->endpoint[ep_idx];
543                                 if (ep->bEndpointAddress == endpoint)
544                                         return ep->wMaxPacketSize;
545                         }
546                 }
547         }
548
549         return LIBUSB_ERROR_NOT_FOUND;
550 }
551
552 /** \ingroup dev
553  * Increment the reference count of a device.
554  * \param dev the device to reference
555  * \returns the same device
556  */
557 API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev)
558 {
559         pthread_mutex_lock(&dev->lock);
560         dev->refcnt++;
561         pthread_mutex_unlock(&dev->lock);
562         return dev;
563 }
564
565 /** \ingroup dev
566  * Decrement the reference count of a device. If the decrement operation
567  * causes the reference count to reach zero, the device shall be destroyed.
568  * \param dev the device to unreference
569  */
570 API_EXPORTED void libusb_unref_device(libusb_device *dev)
571 {
572         int refcnt;
573
574         if (!dev)
575                 return;
576
577         pthread_mutex_lock(&dev->lock);
578         refcnt = --dev->refcnt;
579         pthread_mutex_unlock(&dev->lock);
580
581         if (refcnt == 0) {
582                 usbi_dbg("destroy device %04x:%04x", dev->desc.idVendor,
583                         dev->desc.idProduct);
584
585                 if (usbi_backend->destroy_device)
586                         usbi_backend->destroy_device(dev);
587
588                 pthread_mutex_lock(&usb_devs_lock);
589                 list_del(&dev->list);
590                 pthread_mutex_unlock(&usb_devs_lock);
591
592                 if (dev->config) {
593                         usbi_clear_configurations(dev);
594                         free(dev->config);
595                 }
596                 free(dev);
597         }
598 }
599
600 /** \ingroup dev
601  * Open a device and obtain a device handle. A handle allows you to perform
602  * I/O on the device in question.
603  *
604  * Internally, this function adds a reference to the device and makes it
605  * available to you through libusb_get_device(). This reference is removed
606  * during libusb_close().
607  *
608  * This is a non-blocking function; no requests are sent over the bus.
609  *
610  * \param dev the device to open
611  * \returns a handle for the device, or NULL on error
612  */
613 API_EXPORTED libusb_device_handle *libusb_open(libusb_device *dev)
614 {
615         struct libusb_device_handle *handle;
616         size_t priv_size = usbi_backend->device_handle_priv_size;
617         int r;
618         usbi_dbg("open %04x:%04x", dev->desc.idVendor, dev->desc.idProduct);
619
620         handle = malloc(sizeof(*handle) + priv_size);
621         if (!handle)
622                 return NULL;
623
624         r = pthread_mutex_init(&handle->lock, NULL);
625         if (r)
626                 return NULL;
627
628         handle->dev = libusb_ref_device(dev);
629         handle->claimed_interfaces = 0;
630         memset(&handle->os_priv, 0, priv_size);
631
632         r = usbi_backend->open(handle);
633         if (r < 0) {
634                 libusb_unref_device(dev);
635                 free(handle);
636                 return NULL;
637         }
638
639         pthread_mutex_lock(&usbi_open_devs_lock);
640         list_add(&handle->list, &usbi_open_devs);
641         pthread_mutex_unlock(&usbi_open_devs_lock);
642         return handle;
643 }
644
645 /** \ingroup dev
646  * Convenience function for finding a device with a particular
647  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
648  * for those scenarios where you are using libusb to knock up a quick test
649  * application - it allows you to avoid calling libusb_get_device_list() and
650  * worrying about traversing/freeing the list.
651  *
652  * This function has limitations and is hence not intended for use in real
653  * applications: if multiple devices have the same IDs it will only
654  * give you the first one, etc.
655  *
656  * \param vendor_id the idVendor value to search for
657  * \param product_id the idProduct value to search for
658  * \returns a handle for the first found device, or NULL on error or if the
659  * device could not be found. */
660 API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid(
661         uint16_t vendor_id, uint16_t product_id)
662 {
663         struct libusb_device **devs;
664         struct libusb_device *found = NULL;
665         struct libusb_device *dev;
666         struct libusb_device_handle *handle = NULL;
667         size_t i = 0;
668
669         if (libusb_get_device_list(&devs) < 0)
670                 return NULL;
671
672         while ((dev = devs[i++]) != NULL) {
673                 const struct libusb_device_descriptor *desc =
674                         libusb_get_device_descriptor(dev);
675                 if (desc->idVendor == vendor_id && desc->idProduct == product_id) {
676                         found = dev;
677                         break;
678                 }
679         }
680
681         if (found)
682                 handle = libusb_open(found);
683
684         libusb_free_device_list(devs, 1);
685         return handle;
686 }
687
688 static void do_close(struct libusb_device_handle *dev_handle)
689 {
690         usbi_backend->close(dev_handle);
691         libusb_unref_device(dev_handle->dev);
692 }
693
694 /** \ingroup dev
695  * Close a device handle. Should be called on all open handles before your
696  * application exits.
697  *
698  * Internally, this function destroys the reference that was added by
699  * libusb_open() on the given device.
700  *
701  * This is a non-blocking function; no requests are sent over the bus.
702  *
703  * \param dev_handle the handle to close
704  */
705 API_EXPORTED void libusb_close(libusb_device_handle *dev_handle)
706 {
707         if (!dev_handle)
708                 return;
709         usbi_dbg("");
710
711         pthread_mutex_lock(&usbi_open_devs_lock);
712         list_del(&dev_handle->list);
713         pthread_mutex_unlock(&usbi_open_devs_lock);
714
715         do_close(dev_handle);
716         free(dev_handle);
717 }
718
719 /** \ingroup dev
720  * Get the underlying device for a handle. This function does not modify
721  * the reference count of the returned device, so do not feel compelled to
722  * unreference it when you are done.
723  * \param dev_handle a device handle
724  * \returns the underlying device
725  */
726 API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle)
727 {
728         return dev_handle->dev;
729 }
730
731 /** \ingroup dev
732  * Set the active configuration for a device. The operating system may have
733  * already set an active configuration on the device, but for portability
734  * reasons you should use this function to select the configuration you want
735  * before claiming any interfaces.
736  *
737  * If you wish to change to another configuration at some later time, you
738  * must release all claimed interfaces using libusb_release_interface() before
739  * setting a new active configuration.
740  *
741  * You should always use this function rather than formulating your own
742  * SET_CONFIGURATION control request. This is because the underlying operating
743  * system needs to know when such changes happen.
744  *
745  * This is a blocking function.
746  *
747  * \param dev a device handle
748  * \param configuration the bConfigurationValue of the configuration you
749  * wish to activate
750  * \returns 0 on success
751  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
752  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
753  * \returns another LIBUSB_ERROR code on other failure
754  */
755 API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev,
756         int configuration)
757 {
758         usbi_dbg("configuration %d", configuration);
759         return usbi_backend->set_configuration(dev, configuration);
760 }
761
762 /** \ingroup dev
763  * Claim an interface on a given device handle. You must claim the interface
764  * you wish to use before you can perform I/O on any of its endpoints.
765  *
766  * It is legal to attempt to claim an already-claimed interface, in which
767  * case libusb just returns 0 without doing anything.
768  *
769  * Claiming of interfaces is a purely logical operation; it does not cause
770  * any requests to be sent over the bus. Interface claiming is used to
771  * instruct the underlying operating system that your application wishes
772  * to take ownership of the interface.
773  *
774  * This is a non-blocking function.
775  *
776  * \param dev a device handle
777  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
778  * wish to claim
779  * \returns 0 on success
780  * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
781  * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
782  * interface
783  * \returns a LIBUSB_ERROR code on other failure
784  */
785 API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev,
786         int interface_number)
787 {
788         int r = 0;
789
790         usbi_dbg("interface %d", interface_number);
791         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
792                 return LIBUSB_ERROR_INVALID_PARAM;
793
794         pthread_mutex_lock(&dev->lock);
795         if (dev->claimed_interfaces & (1 << interface_number))
796                 goto out;
797
798         r = usbi_backend->claim_interface(dev, interface_number);
799         if (r == 0)
800                 dev->claimed_interfaces |= 1 << interface_number;
801
802 out:
803         pthread_mutex_unlock(&dev->lock);
804         return r;
805 }
806
807 /** \ingroup dev
808  * Release an interface previously claimed with libusb_claim_interface(). You
809  * should release all claimed interfaces before closing a device handle.
810  *
811  * This is a non-blocking function which does not generate any bus requests.
812  *
813  * \param dev a device handle
814  * \param interface_number the <tt>bInterfaceNumber</tt> of the
815  * previously-claimed interface
816  * \returns 0 on success, or a LIBUSB_ERROR code on failure.
817  * LIBUSB_ERROR_NOT_FOUND indicates that the interface was not claimed.
818  */
819 API_EXPORTED int libusb_release_interface(libusb_device_handle *dev,
820         int interface_number)
821 {
822         int r;
823
824         usbi_dbg("interface %d", interface_number);
825         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
826                 return LIBUSB_ERROR_INVALID_PARAM;
827
828         pthread_mutex_lock(&dev->lock);
829         if (!(dev->claimed_interfaces & (1 << interface_number))) {
830                 r = LIBUSB_ERROR_NOT_FOUND;
831                 goto out;
832         }
833
834         r = usbi_backend->release_interface(dev, interface_number);
835         if (r == 0)
836                 dev->claimed_interfaces &= ~(1 << interface_number);
837
838 out:
839         pthread_mutex_unlock(&dev->lock);
840         return r;
841 }
842
843 /** \ingroup dev
844  * Activate an alternate setting for an interface. The interface must have
845  * been previously claimed with libusb_claim_interface().
846  *
847  * You should always use this function rather than formulating your own
848  * SET_INTERFACE control request. This is because the underlying operating
849  * system needs to know when such changes happen.
850  *
851  * This is a blocking function.
852  *
853  * \param dev a device handle
854  * \param interface_number the <tt>bInterfaceNumber</tt> of the
855  * previously-claimed interface
856  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
857  * setting to activate
858  * \returns 0 on success
859  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
860  * requested alternate setting does not exist
861  * \returns another LIBUSB_ERROR code on other failure
862  */
863 API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev,
864         int interface_number, int alternate_setting)
865 {
866         usbi_dbg("interface %d altsetting %d", interface_number, alternate_setting);
867         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
868                 return LIBUSB_ERROR_INVALID_PARAM;
869
870         pthread_mutex_lock(&dev->lock);
871         if (!(dev->claimed_interfaces & (1 << interface_number))) {
872                 pthread_mutex_unlock(&dev->lock);       
873                 return LIBUSB_ERROR_NOT_FOUND;
874         }
875         pthread_mutex_unlock(&dev->lock);
876
877         return usbi_backend->set_interface_altsetting(dev, interface_number,
878                 alternate_setting);
879 }
880
881 /** \ingroup dev
882  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
883  * are unable to receive or transmit data until the halt condition is stalled.
884  *
885  * You should cancel all pending transfers before attempting to clear the halt
886  * condition.
887  *
888  * This is a blocking function.
889  *
890  * \param dev a device handle
891  * \param endpoint the endpoint to clear halt status
892  * \returns 0 on success
893  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
894  * \returns another LIBUSB_ERROR code on other failure
895  */
896 API_EXPORTED int libusb_clear_halt(libusb_device_handle *dev,
897         unsigned char endpoint)
898 {
899         usbi_dbg("endpoint %x", endpoint);
900         return usbi_backend->clear_halt(dev, endpoint);
901 }
902
903 /** \ingroup dev
904  * Perform a USB port reset to reinitialize a device. The system will attempt
905  * to restore the previous configuration and alternate settings after the
906  * reset has completed.
907  *
908  * If the reset fails, the descriptors change, or the previous state cannot be
909  * restored, the device will appear to be disconnected and reconnected. This
910  * means that the device handle is no longer valid (you should close it) and
911  * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
912  * when this is the case.
913  *
914  * This is a blocking function which usually incurs a noticeable delay.
915  *
916  * \param dev a handle of the device to reset
917  * \returns 0 on success
918  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required
919  * \returns another LIBUSB_ERROR code on other failure
920  */
921 API_EXPORTED int libusb_reset_device(libusb_device_handle *dev)
922 {
923         usbi_dbg("");
924         return usbi_backend->reset_device(dev);
925 }
926
927 /** \ingroup dev
928  * Determine if a kernel driver is active on an interface. If a kernel driver
929  * is active, you cannot claim the interface, and libusb will be unable to
930  * perform I/O.
931  *
932  * \param dev a device handle
933  * \param interface the interface to check
934  * \returns 0 if no kernel driver is active
935  * \returns 1 if a kernel driver is active
936  * \returns LIBUSB_ERROR code on failure
937  * \see libusb_detach_kernel_driver()
938  */
939 API_EXPORTED int libusb_kernel_driver_active(libusb_device_handle *dev,
940         int interface)
941 {
942         usbi_dbg("interface %d", interface);
943         if (usbi_backend->kernel_driver_active)
944                 return usbi_backend->kernel_driver_active(dev, interface);
945         else
946                 return LIBUSB_ERROR_NOT_SUPPORTED;
947 }
948
949 /** \ingroup dev
950  * Detach a kernel driver from an interface. If successful, you will then be
951  * able to claim the interface and perform I/O.
952  *
953  * \param dev a device handle
954  * \param interface the interface to detach the driver from
955  * \returns 0 on success
956  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
957  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
958  * \returns another LIBUSB_ERROR code on other failure
959  * \see libusb_kernel_driver_active()
960  */
961 API_EXPORTED int libusb_detach_kernel_driver(libusb_device_handle *dev,
962         int interface)
963 {
964         usbi_dbg("interface %d", interface);
965         if (usbi_backend->detach_kernel_driver)
966                 return usbi_backend->detach_kernel_driver(dev, interface);
967         else
968                 return LIBUSB_ERROR_NOT_SUPPORTED;
969 }
970
971 /** \ingroup lib
972  * Initialize libusb. This function must be called before calling any other
973  * libusb function.
974  * \returns 0 on success, or a LIBUSB_ERROR code on failure
975  */
976 API_EXPORTED int libusb_init(void)
977 {
978         usbi_dbg("");
979
980         if (usbi_backend->init) {
981                 int r = usbi_backend->init();
982                 if (r)
983                         return r;
984         }
985
986         list_init(&usb_devs);
987         list_init(&usbi_open_devs);
988         usbi_io_init();
989         return 0;
990 }
991
992 /** \ingroup lib
993  * Deinitialize libusb. Should be called after closing all open devices and
994  * before your application terminates.
995  */
996 API_EXPORTED void libusb_exit(void)
997 {
998         usbi_dbg("");
999
1000         pthread_mutex_lock(&usbi_open_devs_lock);
1001         if (!list_empty(&usbi_open_devs)) {
1002                 struct libusb_device_handle *devh;
1003                 struct libusb_device_handle *tmp;
1004
1005                 usbi_dbg("naughty app left some devices open!");
1006                 list_for_each_entry_safe(devh, tmp, &usbi_open_devs, list) {
1007                         list_del(&devh->list);
1008                         do_close(devh);
1009                         free(devh);
1010                 }
1011         }
1012         pthread_mutex_unlock(&usbi_open_devs_lock);
1013
1014         if (usbi_backend->exit)
1015                 usbi_backend->exit();
1016 }
1017
1018 void usbi_log(enum usbi_log_level level, const char *function,
1019         const char *format, ...)
1020 {
1021         va_list args;
1022         FILE *stream = stdout;
1023         const char *prefix;
1024
1025         switch (level) {
1026         case LOG_LEVEL_INFO:
1027                 prefix = "info";
1028                 break;
1029         case LOG_LEVEL_WARNING:
1030                 stream = stderr;
1031                 prefix = "warning";
1032                 break;
1033         case LOG_LEVEL_ERROR:
1034                 stream = stderr;
1035                 prefix = "error";
1036                 break;
1037         case LOG_LEVEL_DEBUG:
1038                 stream = stderr;
1039                 prefix = "debug";
1040                 break;
1041         default:
1042                 stream = stderr;
1043                 prefix = "unknown";
1044                 break;
1045         }
1046
1047         fprintf(stream, "libusb:%s [%s] ", prefix, function);
1048
1049         va_start (args, format);
1050         vfprintf(stream, format, args);
1051         va_end (args);
1052
1053         fprintf(stream, "\n");
1054 }
1055