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