mutex protection for device and handle lists
[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;
83 int cnt = libusb_get_device_list(&list);
84 int 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  * <tt>libusb_device</tt> 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 <tt>libusb_device_handle</tt> 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_device_ref() and libusb_device_unref(). 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 is available later
167  * through libusb_get_device(). The reference is deleted during libusb_close().
168  */
169
170 /**
171  * @defgroup misc Miscellaneous structures and constants
172  * This page documents structures and constants that don't belong anywhere
173  * else
174  */
175
176 /* we traverse usbfs without knowing how many devices we are going to find.
177  * so we create this discovered_devs model which is similar to a linked-list
178  * which grows when required. it can be freed once discovery has completed,
179  * eliminating the need for a list node in the libusb_device structure
180  * itself. */
181 #define DISCOVERED_DEVICES_SIZE_STEP 8
182
183 static struct discovered_devs *discovered_devs_alloc(void)
184 {
185         struct discovered_devs *ret =
186                 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
187
188         if (ret) {
189                 ret->len = 0;
190                 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
191         }
192         return ret;
193 }
194
195 /* append a device to the discovered devices collection. may realloc itself,
196  * returning new discdevs. returns NULL on realloc failure. */
197 struct discovered_devs *discovered_devs_append(
198         struct discovered_devs *discdevs, struct libusb_device *dev)
199 {
200         size_t len = discdevs->len;
201         size_t capacity;
202
203         /* if there is space, just append the device */
204         if (len < discdevs->capacity) {
205                 discdevs->devices[len] = libusb_device_ref(dev);
206                 discdevs->len++;
207                 return discdevs;
208         }
209
210         /* exceeded capacity, need to grow */
211         usbi_dbg("need to increase capacity");
212         capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
213         discdevs = realloc(discdevs,
214                 sizeof(*discdevs) + (sizeof(void *) * capacity));
215         if (discdevs) {
216                 discdevs->capacity = capacity;
217                 discdevs->devices[len] = libusb_device_ref(dev);
218                 discdevs->len++;
219         }
220
221         return discdevs;
222 }
223
224 static void discovered_devs_free(struct discovered_devs *discdevs)
225 {
226         size_t i;
227
228         for (i = 0; i < discdevs->len; i++)
229                 libusb_device_unref(discdevs->devices[i]);
230
231         free(discdevs);
232 }
233
234 struct libusb_device *usbi_alloc_device(unsigned long session_id)
235 {
236         size_t priv_size = usbi_backend->device_priv_size;
237         struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
238         if (!dev)
239                 return NULL;
240
241         dev->refcnt = 1;
242         dev->session_data = session_id;
243         memset(&dev->os_priv, 0, priv_size);
244
245         pthread_mutex_lock(&usb_devs_lock);
246         list_add(&dev->list, &usb_devs);
247         pthread_mutex_unlock(&usb_devs_lock);
248         return dev;
249 }
250
251 struct libusb_device *usbi_get_device_by_session_id(unsigned long session_id)
252 {
253         struct libusb_device *dev;
254         struct libusb_device *ret = NULL;
255
256         pthread_mutex_lock(&usb_devs_lock);
257         list_for_each_entry(dev, &usb_devs, list)
258                 if (dev->session_data == session_id) {
259                         ret = dev;
260                         break;
261                 }
262         pthread_mutex_unlock(&usb_devs_lock);
263
264         return ret;
265 }
266
267 /** @ingroup dev
268  * Returns a list of USB devices currently attached to the system. This is
269  * your entry point into finding a USB device to operate.
270  *
271  * You are expected to unreference all the devices when you are done with
272  * them, and then free the list with libusb_free_device_list(). Note that
273  * libusb_free_device_list() can unref all the devices for you. Be careful
274  * not to unreference a device you are about to open until after you have
275  * opened it.
276  *
277  * \param list output location for a list of devices. Must be later freed with
278  * libusb_free_device_list().
279  * \returns the number of devices in the outputted list, or negative on error
280  */
281 API_EXPORTED int libusb_get_device_list(struct libusb_device ***list)
282 {
283         struct discovered_devs *discdevs = discovered_devs_alloc();
284         struct libusb_device **ret;
285         int r = 0;
286         size_t i;
287         size_t len;
288         usbi_dbg("");
289
290         if (!discdevs)
291                 return -ENOMEM;
292
293         r = usbi_backend->get_device_list(&discdevs);
294         if (r < 0)
295                 goto out;
296
297         /* convert discovered_devs into a list */
298         len = discdevs->len;
299         ret = malloc(sizeof(void *) * (len + 1));
300         if (!ret) {
301                 r = -ENOMEM;
302                 goto out;
303         }
304
305         ret[len] = NULL;
306         for (i = 0; i < len; i++) {
307                 struct libusb_device *dev = discdevs->devices[i];
308                 ret[i] = libusb_device_ref(dev);
309         }
310         *list = ret;
311
312 out:
313         discovered_devs_free(discdevs);
314         return r;
315 }
316
317 /** \ingroup dev
318  * Frees a list of devices previously discovered using
319  * libusb_get_device_list(). If the unref_devices parameter is set, the
320  * reference count of each device in the list is decremented by 1.
321  * \param list the list to free
322  * \param unref_devices whether to unref the devices in the list
323  */
324 API_EXPORTED void libusb_free_device_list(struct libusb_device **list,
325         int unref_devices)
326 {
327         if (!list)
328                 return;
329
330         if (unref_devices) {
331                 int i = 0;
332                 struct libusb_device *dev;
333
334                 while ((dev = list[i++]) != NULL)
335                         libusb_device_unref(dev);
336         }
337         free(list);
338 }
339
340 /** \ingroup dev
341  * Increment the reference count of a device.
342  * \param dev the device to reference
343  * \returns the same device
344  */
345 API_EXPORTED struct libusb_device *libusb_device_ref(struct libusb_device *dev)
346 {
347         dev->refcnt++;
348         return dev;
349 }
350
351 /** \ingroup dev
352  * Decrement the reference count of a device. If the decrement operation
353  * causes the reference count to reach zero, the device shall be destroyed.
354  * \param dev the device to unreference
355  */
356 API_EXPORTED void libusb_device_unref(struct libusb_device *dev)
357 {
358         if (!dev)
359                 return;
360
361         if (--dev->refcnt == 0) {
362                 usbi_dbg("destroy device %04x:%04x", dev->desc.idVendor,
363                         dev->desc.idProduct);
364
365                 if (usbi_backend->destroy_device)
366                         usbi_backend->destroy_device(dev);
367
368                 pthread_mutex_lock(&usb_devs_lock);
369                 list_del(&dev->list);
370                 pthread_mutex_unlock(&usb_devs_lock);
371
372                 if (dev->config)
373                         free(dev->config);
374                 free(dev);
375         }
376 }
377
378 /** \ingroup dev
379  * Open a device and obtain a device handle. A handle allows you to perform
380  * I/O on the device in question.
381  *
382  * Internally, this function adds a reference to the device and makes it
383  * available to you through libusb_get_device(). This reference is removed
384  * during libusb_close().
385  *
386  * \param dev the device to open
387  * \returns a handle for the device, or NULL on error
388  */
389 API_EXPORTED struct libusb_device_handle *libusb_open(struct libusb_device *dev)
390 {
391         struct libusb_device_handle *handle;
392         size_t priv_size = usbi_backend->device_handle_priv_size;
393         int r;
394         usbi_dbg("open %04x:%04x", dev->desc.idVendor, dev->desc.idProduct);
395
396         handle = malloc(sizeof(*handle) + priv_size);
397         if (!handle)
398                 return NULL;
399
400         handle->dev = libusb_device_ref(dev);
401         memset(&handle->os_priv, 0, priv_size);
402         r = usbi_backend->open(handle);
403         if (r < 0) {
404                 libusb_device_unref(dev);
405                 free(handle);
406                 return NULL;
407         }
408
409         pthread_mutex_lock(&usbi_open_devs_lock);
410         list_add(&handle->list, &usbi_open_devs);
411         pthread_mutex_unlock(&usbi_open_devs_lock);
412         return handle;
413 }
414
415 /** \ingroup dev
416  * Convenience function for finding a device with a particular
417  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
418  * for those scenarios where you are using libusb to knock up a quick test
419  * application - it allows you to avoid calling libusb_get_device_list() and
420  * worrying about traversing/freeing the list.
421  *
422  * This function has limitations and is hence not intended for use in real
423  * applications: if multiple devices have the same IDs it will only
424  * give you the first one, etc.
425  *
426  * \param vendor_id the idVendor value to search for
427  * \param product_id the idProduct value to search for
428  * \returns a handle for the first found device, or NULL on error or if the
429  * device could not be found. */
430 API_EXPORTED struct libusb_device_handle *libusb_open_device_with_vid_pid(
431         uint16_t vendor_id, uint16_t product_id)
432 {
433         struct libusb_device **devs;
434         struct libusb_device *found = NULL;
435         struct libusb_device *dev;
436         struct libusb_device_handle *handle = NULL;
437         size_t i = 0;
438
439         if (libusb_get_device_list(&devs) < 0)
440                 return NULL;
441
442         while ((dev = devs[i++]) != NULL) {
443                 const struct libusb_device_descriptor *desc =
444                         libusb_get_device_descriptor(dev);
445                 if (desc->idVendor == vendor_id && desc->idProduct == product_id) {
446                         found = dev;
447                         break;
448                 }
449         }
450
451         if (found)
452                 handle = libusb_open(found);
453
454         libusb_free_device_list(devs, 1);
455         return handle;
456 }
457
458 static void do_close(struct libusb_device_handle *dev_handle)
459 {
460         usbi_backend->close(dev_handle);
461         libusb_device_unref(dev_handle->dev);
462 }
463
464 /** \ingroup dev
465  * Close a device handle. Should be called on all open handles before your
466  * application exits.
467  *
468  * Internally, this function destroys the reference that was added by
469  * libusb_open() on the given device.
470  *
471  * \param dev_handle the handle to close
472  */
473 API_EXPORTED void libusb_close(struct libusb_device_handle *dev_handle)
474 {
475         if (!dev_handle)
476                 return;
477         usbi_dbg("");
478
479         pthread_mutex_lock(&usbi_open_devs_lock);
480         list_del(&dev_handle->list);
481         pthread_mutex_unlock(&usbi_open_devs_lock);
482
483         do_close(dev_handle);
484         free(dev_handle);
485 }
486
487 /** \ingroup dev
488  * Get the underlying device for a handle. This function does not modify
489  * the reference count of the returned device, so do not feel compelled to
490  * unreference it when you are done.
491  * \param dev_handle a device handle
492  * \returns the underlying device
493  */
494 API_EXPORTED struct libusb_device *libusb_get_device(
495         struct libusb_device_handle *dev_handle)
496 {
497         return dev_handle->dev;
498 }
499
500 /* FIXME: what about claiming multiple interfaces? */
501 /** \ingroup dev
502  * Claim an interface on a given device handle. You must claim the interface
503  * you wish to use before you can perform I/O on any of the endpoints.
504  * \param iface the <tt>bInterfaceNumber</tt> of the interface you wish to claim
505  * \param dev a device handle
506  * \returns 0 on success, non-zero on error
507  */
508 API_EXPORTED int libusb_claim_interface(struct libusb_device_handle *dev,
509         int iface)
510 {
511         usbi_dbg("interface %d", iface);
512         return usbi_backend->claim_interface(dev, iface);
513 }
514
515 /** \ingroup dev
516  * Release an interface previously claimed with libusb_claim_interface(). You
517  * should release all claimed interfaces before closing a device handle.
518  * \param dev a device handle
519  * \param iface the <tt>bInterfaceNumber</tt> of the previously-claimed
520  * interface
521  * \returns 0 on success, non-zero on error
522  */
523 API_EXPORTED int libusb_release_interface(struct libusb_device_handle *dev,
524         int iface)
525 {
526         usbi_dbg("interface %d", iface);
527         return usbi_backend->release_interface(dev, iface);
528 }
529
530 /* FIXME docs */
531 API_EXPORTED int libusb_set_interface_altsetting(
532         struct libusb_device_handle *dev, int iface, int altsetting)
533 {
534         usbi_dbg("interface %d altsetting %d", iface, altsetting);
535         return usbi_backend->set_interface_altsetting(dev, iface, altsetting);
536 }
537
538 /** \ingroup lib
539  * Initialize libusb. This function must be called before calling any other
540  * libusb function.
541  * \returns 0 on success, non-zero on error
542  */
543 API_EXPORTED int libusb_init(void)
544 {
545         usbi_dbg("");
546
547         if (usbi_backend->init) {
548                 int r = usbi_backend->init();
549                 if (r < 0)
550                         return r;
551         }
552
553         list_init(&usb_devs);
554         list_init(&usbi_open_devs);
555         usbi_io_init();
556         return 0;
557 }
558
559 /** \ingroup lib
560  * Deinitialize libusb. Should be called after closing all open devices and
561  * before your application terminates.
562  */
563 API_EXPORTED void libusb_exit(void)
564 {
565         struct libusb_device_handle *devh;
566         usbi_dbg("");
567
568         pthread_mutex_lock(&usbi_open_devs_lock);
569         if (!list_empty(&usbi_open_devs)) {
570                 usbi_dbg("naughty app left some devices open!\n");
571                 list_for_each_entry(devh, &usbi_open_devs, list)
572                         do_close(devh);
573                 /* FIXME where do the open handles get freed? */
574         }
575         pthread_mutex_unlock(&usbi_open_devs_lock);
576
577         if (usbi_backend->exit)
578                 usbi_backend->exit();
579 }
580
581 void usbi_log(enum usbi_log_level level, const char *function,
582         const char *format, ...)
583 {
584         va_list args;
585         FILE *stream = stdout;
586         const char *prefix;
587
588         switch (level) {
589         case LOG_LEVEL_INFO:
590                 prefix = "info";
591                 break;
592         case LOG_LEVEL_WARNING:
593                 stream = stderr;
594                 prefix = "warning";
595                 break;
596         case LOG_LEVEL_ERROR:
597                 stream = stderr;
598                 prefix = "error";
599                 break;
600         case LOG_LEVEL_DEBUG:
601                 stream = stderr;
602                 prefix = "debug";
603                 break;
604         default:
605                 stream = stderr;
606                 prefix = "unknown";
607                 break;
608         }
609
610         fprintf(stream, "libusb:%s [%s] ", prefix, function);
611
612         va_start (args, format);
613         vfprintf(stream, format, args);
614         va_end (args);
615
616         fprintf(stream, "\n");
617 }
618