Temporary workaround for event handling serialization issue
[platform/upstream/libusb.git] / libusb / io.c
1 /*
2  * I/O 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 #include <errno.h>
23 #include <poll.h>
24 #include <pthread.h>
25 #include <signal.h>
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/time.h>
30 #include <time.h>
31 #include <unistd.h>
32
33 #include "libusbi.h"
34
35 /* this is a list of in-flight transfer handles, sorted by timeout expiration.
36  * URBs to timeout the soonest are placed at the beginning of the list, URBs
37  * that will time out later are placed after, and urbs with infinite timeout
38  * are always placed at the very end. */
39 static struct list_head flying_transfers;
40 static pthread_mutex_t flying_transfers_lock = PTHREAD_MUTEX_INITIALIZER;
41
42 /* list of poll fd's */
43 static struct list_head pollfds;
44 static pthread_mutex_t pollfds_lock = PTHREAD_MUTEX_INITIALIZER;
45
46 /* user callbacks for pollfd changes */
47 static libusb_pollfd_added_cb fd_added_cb = NULL;
48 static libusb_pollfd_removed_cb fd_removed_cb = NULL;
49
50 /* this lock ensures that only one thread is handling events at any one time */
51 static pthread_mutex_t events_lock = PTHREAD_MUTEX_INITIALIZER;
52
53 /* used to see if there is an active thread doing event handling */
54 static int event_handler_active = 0;
55
56 /* used to wait for event completion in threads other than the one that is
57  * event handling */
58 static pthread_mutex_t event_waiters_lock = PTHREAD_MUTEX_INITIALIZER;
59 static pthread_cond_t event_waiters_cond = PTHREAD_COND_INITIALIZER;
60
61 /**
62  * \page io Synchronous and asynchronous device I/O
63  *
64  * \section intro Introduction
65  *
66  * If you're using libusb in your application, you're probably wanting to
67  * perform I/O with devices - you want to perform USB data transfers.
68  *
69  * libusb offers two separate interfaces for device I/O. This page aims to
70  * introduce the two in order to help you decide which one is more suitable
71  * for your application. You can also choose to use both interfaces in your
72  * application by considering each transfer on a case-by-case basis.
73  *
74  * Once you have read through the following discussion, you should consult the
75  * detailed API documentation pages for the details:
76  * - \ref syncio
77  * - \ref asyncio
78  *
79  * \section theory Transfers at a logical level
80  *
81  * At a logical level, USB transfers typically happen in two parts. For
82  * example, when reading data from a endpoint:
83  * -# A request for data is sent to the device
84  * -# Some time later, the incoming data is received by the host
85  *
86  * or when writing data to an endpoint:
87  *
88  * -# The data is sent to the device
89  * -# Some time later, the host receives acknowledgement from the device that
90  *    the data has been transferred.
91  *
92  * There may be an indefinite delay between the two steps. Consider a
93  * fictional USB input device with a button that the user can press. In order
94  * to determine when the button is pressed, you would likely submit a request
95  * to read data on a bulk or interrupt endpoint and wait for data to arrive.
96  * Data will arrive when the button is pressed by the user, which is
97  * potentially hours later.
98  *
99  * libusb offers both a synchronous and an asynchronous interface to performing
100  * USB transfers. The main difference is that the synchronous interface
101  * combines both steps indicated above into a single function call, whereas
102  * the asynchronous interface separates them.
103  *
104  * \section sync The synchronous interface
105  *
106  * The synchronous I/O interface allows you to perform a USB transfer with
107  * a single function call. When the function call returns, the transfer has
108  * completed and you can parse the results.
109  *
110  * If you have used the libusb-0.1 before, this I/O style will seem familar to
111  * you. libusb-0.1 only offered a synchronous interface.
112  *
113  * In our input device example, to read button presses you might write code
114  * in the following style:
115 \code
116 unsigned char data[4];
117 int actual_length,
118 int r = libusb_bulk_transfer(handle, EP_IN, data, sizeof(data), &actual_length, 0);
119 if (r == 0 && actual_length == sizeof(data)) {
120         // results of the transaction can now be found in the data buffer
121         // parse them here and report button press
122 } else {
123         error();
124 }
125 \endcode
126  *
127  * The main advantage of this model is simplicity: you did everything with
128  * a single simple function call.
129  *
130  * However, this interface has its limitations. Your application will sleep
131  * inside libusb_bulk_transfer() until the transaction has completed. If it
132  * takes the user 3 hours to press the button, your application will be
133  * sleeping for that long. Execution will be tied up inside the library -
134  * the entire thread will be useless for that duration.
135  *
136  * Another issue is that by tieing up the thread with that single transaction
137  * there is no possibility of performing I/O with multiple endpoints and/or
138  * multiple devices simultaneously, unless you resort to creating one thread
139  * per transaction.
140  *
141  * Additionally, there is no opportunity to cancel the transfer after the
142  * request has been submitted.
143  *
144  * For details on how to use the synchronous API, see the
145  * \ref syncio "synchronous I/O API documentation" pages.
146  * 
147  * \section async The asynchronous interface
148  *
149  * Asynchronous I/O is the most significant new feature in libusb-1.0.
150  * Although it is a more complex interface, it solves all the issues detailed
151  * above.
152  *
153  * Instead of providing which functions that block until the I/O has complete,
154  * libusb's asynchronous interface presents non-blocking functions which
155  * begin a transfer and then return immediately. Your application passes a
156  * callback function pointer to this non-blocking function, which libusb will
157  * call with the results of the transaction when it has completed.
158  *
159  * Transfers which have been submitted through the non-blocking functions
160  * can be cancelled with a separate function call.
161  *
162  * The non-blocking nature of this interface allows you to be simultaneously
163  * performing I/O to multiple endpoints on multiple devices, without having
164  * to use threads.
165  *
166  * This added flexibility does come with some complications though:
167  * - In the interest of being a lightweight library, libusb does not create
168  * threads and can only operate when your application is calling into it. Your
169  * application must call into libusb from it's main loop when events are ready
170  * to be handled, or you must use some other scheme to allow libusb to
171  * undertake whatever work needs to be done.
172  * - libusb also needs to be called into at certain fixed points in time in
173  * order to accurately handle transfer timeouts.
174  * - Memory handling becomes more complex. You cannot use stack memory unless
175  * the function with that stack is guaranteed not to return until the transfer
176  * callback has finished executing.
177  * - You generally lose some linearity from your code flow because submitting
178  * the transfer request is done in a separate function from where the transfer
179  * results are handled. This becomes particularly obvious when you want to
180  * submit a second transfer based on the results of an earlier transfer.
181  *
182  * Internally, libusb's synchronous interface is expressed in terms of function
183  * calls to the asynchronous interface.
184  *
185  * For details on how to use the asynchronous API, see the
186  * \ref asyncio "asynchronous I/O API" documentation pages.
187  */
188
189 /**
190  * @defgroup asyncio Asynchronous device I/O
191  *
192  * This page details libusb's asynchronous (non-blocking) API for USB device
193  * I/O. This interface is very powerful but is also quite complex - you will
194  * need to read this page carefully to understand the necessary considerations
195  * and issues surrounding use of this interface. Simplistic applications
196  * may wish to consider the \ref syncio "synchronous I/O API" instead.
197  *
198  * The asynchronous interface is built around the idea of separating transfer
199  * submission and handling of transfer completion (the synchronous model
200  * combines both of these into one). There may be a long delay between
201  * submission and completion, however the asynchronous submission function
202  * is non-blocking so will return control to your application during that
203  * potentially long delay.
204  *
205  * \section asyncabstraction Transfer abstraction
206  *
207  * For the asynchronous I/O, libusb implements the concept of a generic
208  * transfer entity for all types of I/O (control, bulk, interrupt,
209  * isochronous). The generic transfer object must be treated slightly
210  * differently depending on which type of I/O you are performing with it.
211  *
212  * This is represented by the public libusb_transfer structure type.
213  *
214  * \section asynctrf Asynchronous transfers
215  *
216  * We can view asynchronous I/O as a 5 step process:
217  * -# Allocation
218  * -# Filling
219  * -# Submission
220  * -# Completion handling
221  * -# Deallocation
222  *
223  * \subsection asyncalloc Allocation
224  *
225  * This step involves allocating memory for a USB transfer. This is the
226  * generic transfer object mentioned above. At this stage, the transfer
227  * is "blank" with no details about what type of I/O it will be used for.
228  *
229  * Allocation is done with the libusb_alloc_transfer() function. You must use
230  * this function rather than allocating your own transfers.
231  *
232  * \subsection asyncfill Filling
233  *
234  * This step is where you take a previously allocated transfer and fill it
235  * with information to determine the message type and direction, data buffer,
236  * callback function, etc.
237  *
238  * You can either fill the required fields yourself or you can use the
239  * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer()
240  * and libusb_fill_interrupt_transfer().
241  *
242  * \subsection asyncsubmit Submission
243  *
244  * When you have allocated a transfer and filled it, you can submit it using
245  * libusb_submit_transfer(). This function returns immediately but can be
246  * regarded as firing off the I/O request in the background.
247  *
248  * \subsection asynccomplete Completion handling
249  *
250  * After a transfer has been submitted, one of four things can happen to it:
251  *
252  * - The transfer completes (i.e. some data was transferred)
253  * - The transfer has a timeout and the timeout expires before all data is
254  * transferred
255  * - The transfer fails due to an error
256  * - The transfer is cancelled
257  *
258  * Each of these will cause the user-specified transfer callback function to
259  * be invoked. It is up to the callback function to determine which of the
260  * above actually happened and to act accordingly.
261  *
262  * \subsection Deallocation
263  *
264  * When a transfer has completed (i.e. the callback function has been invoked),
265  * you are advised to free the transfer (unless you wish to resubmit it, see
266  * below). Transfers are deallocated with libusb_free_transfer().
267  *
268  * It is undefined behaviour to free a transfer which has not completed.
269  *
270  * \section asyncresubmit Resubmission
271  *
272  * You may be wondering why allocation, filling, and submission are all
273  * separated above where they could reasonably be combined into a single
274  * operation.
275  *
276  * The reason for separation is to allow you to resubmit transfers without
277  * having to allocate new ones every time. This is especially useful for
278  * common situations dealing with interrupt endpoints - you allocate one
279  * transfer, fill and submit it, and when it returns with results you just
280  * resubmit it for the next interrupt.
281  *
282  * \section asynccancel Cancellation
283  *
284  * Another advantage of using the asynchronous interface is that you have
285  * the ability to cancel transfers which have not yet completed. This is
286  * done by calling the libusb_cancel_transfer() function.
287  *
288  * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the
289  * cancellation actually completes, the transfer's callback function will
290  * be invoked, and the callback function should check the transfer status to
291  * determine that it was cancelled.
292  *
293  * Freeing the transfer after it has been cancelled but before cancellation
294  * has completed will result in undefined behaviour.
295  *
296  * \section asyncctrl Considerations for control transfers
297  *
298  * The <tt>libusb_transfer</tt> structure is generic and hence does not
299  * include specific fields for the control-specific setup packet structure.
300  *
301  * In order to perform a control transfer, you must place the 8-byte setup
302  * packet at the start of the data buffer. To simplify this, you could
303  * cast the buffer pointer to type struct libusb_control_setup, or you can
304  * use the helper function libusb_fill_control_setup().
305  *
306  * The wLength field placed in the setup packet must be the length you would
307  * expect to be sent in the setup packet: the length of the payload that
308  * follows (or the expected maximum number of bytes to receive). However,
309  * the length field of the libusb_transfer object must be the length of
310  * the data buffer - i.e. it should be wLength <em>plus</em> the size of
311  * the setup packet (LIBUSB_CONTROL_SETUP_SIZE).
312  *
313  * If you use the helper functions, this is simplified for you:
314  * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the
315  * data you are sending/requesting.
316  * -# Call libusb_fill_control_setup() on the data buffer, using the transfer
317  * request size as the wLength value (i.e. do not include the extra space you
318  * allocated for the control setup).
319  * -# If this is a host-to-device transfer, place the data to be transferred
320  * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE.
321  * -# Call libusb_fill_control_transfer() to associate the data buffer with
322  * the transfer (and to set the remaining details such as callback and timeout).
323  *   - Note that there is no parameter to set the length field of the transfer.
324  *     The length is automatically inferred from the wLength field of the setup
325  *     packet.
326  * -# Submit the transfer.
327  *
328  * The multi-byte control setup fields (wValue, wIndex and wLength) must
329  * be given in little-endian byte order (the endianness of the USB bus).
330  * Endianness conversion is transparently handled by
331  * libusb_fill_control_setup() which is documented to accept host-endian
332  * values.
333  *
334  * Further considerations are needed when handling transfer completion in
335  * your callback function:
336  * - As you might expect, the setup packet will still be sitting at the start
337  * of the data buffer.
338  * - If this was a device-to-host transfer, the received data will be sitting
339  * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer.
340  * - The actual_length field of the transfer structure is relative to the
341  * wLength of the setup packet, rather than the size of the data buffer. So,
342  * if your wLength was 4, your transfer's <tt>length</tt> was 12, then you
343  * should expect an <tt>actual_length</tt> of 4 to indicate that the data was
344  * transferred in entirity.
345  *
346  * To simplify parsing of setup packets and obtaining the data from the
347  * correct offset, you may wish to use the libusb_control_transfer_get_data()
348  * and libusb_control_transfer_get_setup() functions within your transfer
349  * callback.
350  *
351  * Even though control endpoints do not halt, a completed control transfer
352  * may have a LIBUSB_TRANSFER_STALL status code. This indicates the control
353  * request was not supported.
354  *
355  * \section asyncintr Considerations for interrupt transfers
356  * 
357  * All interrupt transfers are performed using the polling interval presented
358  * by the bInterval value of the endpoint descriptor.
359  *
360  * \section asynciso Considerations for isochronous transfers
361  *
362  * Isochronous transfers are more complicated than transfers to
363  * non-isochronous endpoints.
364  *
365  * To perform I/O to an isochronous endpoint, allocate the transfer by calling
366  * libusb_alloc_transfer() with an appropriate number of isochronous packets.
367  *
368  * During filling, set \ref libusb_transfer::type "type" to
369  * \ref libusb_transfer_type::LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
370  * "LIBUSB_TRANSFER_TYPE_ISOCHRONOUS", and set
371  * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than
372  * or equal to the number of packets you requested during allocation.
373  * libusb_alloc_transfer() does not set either of these fields for you, given
374  * that you might not even use the transfer on an isochronous endpoint.
375  *
376  * Next, populate the length field for the first num_iso_packets entries in
377  * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section
378  * 5.6.3 of the USB2 specifications describe how the maximum isochronous
379  * packet length is determined by wMaxPacketSize field in the endpoint
380  * descriptor. Two functions can help you here:
381  *
382  * - libusb_get_max_packet_size() is an easy way to determine the max
383  *   packet size for an endpoint.
384  * - libusb_set_iso_packet_lengths() assigns the same length to all packets
385  *   within a transfer, which is usually what you want.
386  *
387  * For outgoing transfers, you'll obviously fill the buffer and populate the
388  * packet descriptors in hope that all the data gets transferred. For incoming
389  * transfers, you must ensure the buffer has sufficient capacity for
390  * the situation where all packets transfer the full amount of requested data.
391  *
392  * Completion handling requires some extra consideration. The
393  * \ref libusb_transfer::actual_length "actual_length" field of the transfer
394  * is meaningless and should not be examined; instead you must refer to the
395  * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of
396  * each individual packet.
397  *
398  * The \ref libusb_transfer::status "status" field of the transfer is also a
399  * little misleading:
400  *  - If the packets were submitted and the isochronous data microframes
401  *    completed normally, status will have value
402  *    \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED
403  *    "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred
404  *    delays are not counted as transfer errors; the transfer.status field may
405  *    indicate COMPLETED even if some or all of the packets failed. Refer to
406  *    the \ref libusb_iso_packet_descriptor::status "status" field of each
407  *    individual packet to determine packet failures.
408  *  - The status field will have value
409  *    \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR
410  *    "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered.
411  *  - Other transfer status codes occur with normal behaviour.
412  *
413  * The data for each packet will be found at an offset into the buffer that
414  * can be calculated as if each prior packet completed in full. The
415  * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple()
416  * functions may help you here.
417  *
418  * \section asyncmem Memory caveats
419  *
420  * In most circumstances, it is not safe to use stack memory for transfer
421  * buffers. This is because the function that fired off the asynchronous
422  * transfer may return before libusb has finished using the buffer, and when
423  * the function returns it's stack gets destroyed. This is true for both
424  * host-to-device and device-to-host transfers.
425  *
426  * The only case in which it is safe to use stack memory is where you can
427  * guarantee that the function owning the stack space for the buffer does not
428  * return until after the transfer's callback function has completed. In every
429  * other case, you need to use heap memory instead.
430  *
431  * \section asyncflags Fine control
432  *
433  * Through using this asynchronous interface, you may find yourself repeating
434  * a few simple operations many times. You can apply a bitwise OR of certain
435  * flags to a transfer to simplify certain things:
436  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK
437  *   "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred
438  *   less than the requested amount of data being marked with status
439  *   \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR"
440  *   (they would normally be regarded as COMPLETED)
441  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
442  *   "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer
443  *   buffer when freeing the transfer.
444  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER
445  *   "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the
446  *   transfer after the transfer callback returns.
447  *
448  * \section asyncevent Event handling
449  *
450  * In accordance of the aim of being a lightweight library, libusb does not
451  * create threads internally. This means that libusb code does not execute
452  * at any time other than when your application is calling a libusb function.
453  * However, an asynchronous model requires that libusb perform work at various
454  * points in time - namely processing the results of previously-submitted
455  * transfers and invoking the user-supplied callback function.
456  *
457  * This gives rise to the libusb_handle_events() function which your
458  * application must call into when libusb has work do to. This gives libusb
459  * the opportunity to reap pending transfers, invoke callbacks, etc.
460  *
461  * The first issue to discuss here is how your application can figure out
462  * when libusb has work to do. In fact, there are two naive options which
463  * do not actually require your application to know this:
464  * -# Periodically call libusb_handle_events() in non-blocking mode at fixed
465  *    short intervals from your main loop
466  * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated
467  *    thread.
468  *
469  * The first option is plainly not very nice, and will cause unnecessary 
470  * CPU wakeups leading to increased power usage and decreased battery life.
471  * The second option is not very nice either, but may be the nicest option
472  * available to you if the "proper" approach can not be applied to your
473  * application (read on...).
474  * 
475  * The recommended option is to integrate libusb with your application main
476  * event loop. libusb exposes a set of file descriptors which allow you to do
477  * this. Your main loop is probably already calling poll() or select() or a
478  * variant on a set of file descriptors for other event sources (e.g. keyboard
479  * button presses, mouse movements, network sockets, etc). You then add
480  * libusb's file descriptors to your poll()/select() calls, and when activity
481  * is detected on such descriptors you know it is time to call
482  * libusb_handle_events().
483  *
484  * There is one final event handling complication. libusb supports
485  * asynchronous transfers which time out after a specified time period, and
486  * this requires that libusb is called into at or after the timeout so that
487  * the timeout can be handled. So, in addition to considering libusb's file
488  * descriptors in your main event loop, you must also consider that libusb
489  * sometimes needs to be called into at fixed points in time even when there
490  * is no file descriptor activity.
491  *
492  * For the details on retrieving the set of file descriptors and determining
493  * the next timeout, see the \ref poll "polling and timing" API documentation.
494  */
495
496 /**
497  * @defgroup poll Polling and timing
498  *
499  * This page documents libusb's functions for polling events and timing.
500  * These functions are only necessary for users of the
501  * \ref asyncio "asynchronous API". If you are only using the simpler
502  * \ref syncio "synchronous API" then you do not need to ever call these
503  * functions.
504  *
505  * The justification for the functionality described here has already been
506  * discussed in the \ref asyncevent "event handling" section of the
507  * asynchronous API documentation. In summary, libusb does not create internal
508  * threads for event processing and hence relies on your application calling
509  * into libusb at certain points in time so that pending events can be handled.
510  * In order to know precisely when libusb needs to be called into, libusb
511  * offers you a set of pollable file descriptors and information about when
512  * the next timeout expires.
513  *
514  * If you are using the asynchronous I/O API, you must take one of the two
515  * following options, otherwise your I/O will not complete.
516  *
517  * \section pollsimple The simple option
518  *
519  * If your application revolves solely around libusb and does not need to
520  * handle other event sources, you can have a program structure as follows:
521 \code
522 // initialize libusb
523 // find and open device
524 // maybe fire off some initial async I/O
525
526 while (user_has_not_requested_exit)
527         libusb_handle_events();
528
529 // clean up and exit
530 \endcode
531  *
532  * With such a simple main loop, you do not have to worry about managing
533  * sets of file descriptors or handling timeouts. libusb_handle_events() will
534  * handle those details internally.
535  *
536  * \section pollmain The more advanced option
537  *
538  * In more advanced applications, you will already have a main loop which
539  * is monitoring other event sources: network sockets, X11 events, mouse
540  * movements, etc. Through exposing a set of file descriptors, libusb is
541  * designed to cleanly integrate into such main loops.
542  *
543  * In addition to polling file descriptors for the other event sources, you
544  * take a set of file descriptors from libusb and monitor those too. When you
545  * detect activity on libusb's file descriptors, you call
546  * libusb_handle_events_timeout() in non-blocking mode.
547  *
548  * You must also consider the fact that libusb sometimes has to handle events
549  * at certain known times which do not generate activity on file descriptors.
550  * Your main loop must also consider these times, modify it's poll()/select()
551  * timeout accordingly, and track time so that libusb_handle_events_timeout()
552  * is called in non-blocking mode when timeouts expire.
553  *
554  * In pseudo-code, you want something that looks like:
555 \code
556 // initialise libusb
557
558 libusb_get_pollfds()
559 while (user has not requested application exit) {
560         libusb_get_next_timeout();
561         select(on libusb file descriptors plus any other event sources of interest,
562                 using a timeout no larger than the value libusb just suggested)
563         if (select() indicated activity on libusb file descriptors)
564                 libusb_handle_events_timeout(0);
565         if (time has elapsed to or beyond the libusb timeout)
566                 libusb_handle_events_timeout(0);
567 }
568
569 // clean up and exit
570 \endcode
571  *
572  * The set of file descriptors that libusb uses as event sources may change
573  * during the life of your application. Rather than having to repeatedly
574  * call libusb_get_pollfds(), you can set up notification functions for when
575  * the file descriptor set changes using libusb_set_pollfd_notifiers().
576  *
577  * \section mtissues Multi-threaded considerations
578  *
579  * Unfortunately, the situation is complicated further when multiple threads
580  * come into play. If two threads are monitoring the same file descriptors,
581  * the fact that only one thread will be woken up when an event occurs causes
582  * some headaches.
583  *
584  * The events lock, event waiters lock, and libusb_handle_events_locked()
585  * entities are added to solve these problems. You do not need to be concerned
586  * with these entities otherwise.
587  *
588  * See the extra documentation: \ref mtasync
589  */
590
591 /** \page mtasync Multi-threaded applications and asynchronous I/O
592  *
593  * libusb is a thread-safe library, but extra considerations must be applied
594  * to applications which interact with libusb from multiple threads.
595  *
596  * The underlying issue that must be addressed is that all libusb I/O
597  * revolves around monitoring file descriptors through the poll()/select()
598  * system calls. This is directly exposed at the
599  * \ref asyncio "asynchronous interface" but it is important to note that the
600  * \ref syncio "synchronous interface" is implemented on top of the
601  * asynchonrous interface, therefore the same considerations apply.
602  *
603  * The issue is that if two or more threads are concurrently calling poll()
604  * or select() on libusb's file descriptors then only one of those threads
605  * will be woken up when an event arrives. The others will be completely
606  * oblivious that anything has happened.
607  *
608  * Consider the following pseudo-code, which submits an asynchronous transfer
609  * then waits for its completion. This style is one way you could implement a
610  * synchronous interface on top of the asynchronous interface (and libusb
611  * does something similar, albeit more advanced due to the complications
612  * explained on this page).
613  *
614 \code
615 void cb(struct libusb_transfer *transfer)
616 {
617         int *completed = transfer->user_data;
618         *completed = 1;
619 }
620
621 void myfunc() {
622         const struct timeval timeout = { 120, 0 };
623         struct libusb_transfer *transfer;
624         unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE];
625         int completed = 0;
626
627         transfer = libusb_alloc_transfer(0);
628         libusb_fill_control_setup(buffer,
629                 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x04, 0x01, 0, 0);
630         libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000);
631         libusb_submit_transfer(transfer);
632
633         while (!completed) {
634                 poll(libusb file descriptors, 120*1000);
635                 if (poll indicates activity)
636                         libusb_handle_events_timeout(0);
637         }
638         printf("completed!");
639         // other code here
640 }
641 \endcode
642  *
643  * Here we are <em>serializing</em> completion of an asynchronous event
644  * against a condition - the condition being completion of a specific transfer.
645  * The poll() loop has a long timeout to minimize CPU usage during situations
646  * when nothing is happening (it could reasonably be unlimited).
647  *
648  * If this is the only thread that is polling libusb's file descriptors, there
649  * is no problem: there is no danger that another thread will swallow up the
650  * event that we are interested in. On the other hand, if there is another
651  * thread polling the same descriptors, there is a chance that it will receive
652  * the event that we were interested in. In this situation, <tt>myfunc()</tt>
653  * will only realise that the transfer has completed on the next iteration of
654  * the loop, <em>up to 120 seconds later.</em> Clearly a two-minute delay is
655  * undesirable, and don't even think about using short timeouts to circumvent
656  * this issue!
657  * 
658  * The solution here is to ensure that no two threads are ever polling the
659  * file descriptors at the same time. A naive implementation of this would
660  * impact the capabilities of the library, so libusb offers the scheme
661  * documented below to ensure no loss of functionality.
662  *
663  * Before we go any further, it is worth mentioning that all libusb-wrapped
664  * event handling procedures fully adhere to the scheme documented below.
665  * This includes libusb_handle_events() and all the synchronous I/O functions - 
666  * libusb hides this headache from you. You do not need to worry about any
667  * of these issues if you stick to that level.
668  *
669  * The problem is when we consider the fact that libusb exposes file
670  * descriptors to allow for you to integrate asynchronous USB I/O into
671  * existing main loops, effectively allowing you to do some work behind
672  * libusb's back. If you do take libusb's file descriptors and pass them to
673  * poll()/select() yourself, you need to be aware of the associated issues.
674  *
675  * \section eventlock The events lock
676  *
677  * The first concept to be introduced is the events lock. The events lock
678  * is used to serialize threads that want to handle events, such that only
679  * one thread is handling events at any one time.
680  *
681  * You must take the events lock before polling libusb file descriptors,
682  * using libusb_lock_events(). You must release the lock as soon as you have
683  * aborted your poll()/select() loop, using libusb_unlock_events().
684  *
685  * \section threadwait Letting other threads do the work for you
686  *
687  * Although the events lock is a critical part of the solution, it is not
688  * enough on it's own. You might wonder if the following is sufficient...
689 \code
690         libusb_lock_events();
691         while (!completed) {
692                 poll(libusb file descriptors, 120*1000);
693                 if (poll indicates activity)
694                         libusb_handle_events_timeout(0);
695         }
696         libusb_lock_events();
697 \endcode
698  * ...and the answer is that it is not. This is because the transfer in the
699  * code shown above may take a long time (say 30 seconds) to complete, and
700  * the lock is not released until the transfer is completed.
701  *
702  * Another thread with similar code that wants to do event handling may be
703  * working with a transfer that completes after a few milliseconds. Despite
704  * having such a quick completion time, the other thread cannot check that
705  * status of its transfer until the code above has finished (30 seconds later)
706  * due to contention on the lock.
707  *
708  * To solve this, libusb offers you a mechanism to determine when another
709  * thread is handling events. It also offers a mechanism to block your thread
710  * until the event handling thread has completed an event (and this mechanism
711  * does not involve polling of file descriptors).
712  *
713  * After determining that another thread is currently handling events, you
714  * obtain the <em>event waiters</em> lock using libusb_lock_event_waiters().
715  * You then re-check that some other thread is still handling events, and if
716  * so, you call libusb_wait_for_event().
717  *
718  * libusb_wait_for_event() puts your application to sleep until an event
719  * occurs, or until a thread releases the events lock. When either of these
720  * things happen, your thread is woken up, and should re-check the condition
721  * it was waiting on. It should also re-check that another thread is handling
722  * events, and if not, it should start handling events itself.
723  *
724  * This looks like the following, as pseudo-code:
725 \code
726 retry:
727 if (libusb_try_lock_events() == 0) {
728         // we obtained the event lock: do our own event handling
729         libusb_lock_events();
730         while (!completed) {
731                 poll(libusb file descriptors, 120*1000);
732                 if (poll indicates activity)
733                         libusb_handle_events_locked(0);
734         }
735         libusb_unlock_events();
736 } else {
737         // another thread is doing event handling. wait for it to signal us that
738         // an event has completed
739         libusb_lock_event_waiters();
740
741         while (!completed) {
742                 // now that we have the event waiters lock, double check that another
743                 // thread is still handling events for us. (it may have ceased handling
744                 // events in the time it took us to reach this point)
745                 if (!libusb_event_handler_active()) {
746                         // whoever was handling events is no longer doing so, try again
747                         libusb_unlock_event_waiters();
748                         goto retry;
749                 }
750         
751                 libusb_wait_for_event();
752         }
753         libusb_unlock_event_waiters();
754 }
755 printf("completed!\n");
756 \endcode
757  *
758  * We have now implemented code which can dynamically handle situations where
759  * nobody is handling events (so we should do it ourselves), and it can also
760  * handle situations where another thread is doing event handling (so we can
761  * piggyback onto them). It is also equipped to handle a combination of
762  * the two, for example, another thread is doing event handling, but for
763  * whatever reason it stops doing so before our condition is met, so we take
764  * over the event handling.
765  *
766  * Three functions were introduced in the above pseudo-code. Their importance
767  * should be apparent from the code shown above.
768  * -# libusb_try_lock_events() is a non-blocking function which attempts
769  *    to acquire the events lock but returns a failure code if it is contended.
770  * -# libusb_handle_events_locked() is a variant of
771  *    libusb_handle_events_timeout() that you can call while holding the
772  *    events lock. libusb_handle_events_timeout() itself implements similar
773  *    logic to the above, so be sure not to call it when you are
774  *    "working behind libusb's back", as is the case here.
775  * -# libusb_event_handler_active() determines if someone is currently
776  *    holding the events lock
777  *
778  * You might be wondering why there is no function to wake up all threads
779  * blocked on libusb_wait_for_event(). This is because libusb can do this
780  * internally: it will wake up all such threads when someone calls
781  * libusb_unlock_events() or when a transfer completes (at the point after its
782  * callback has returned).
783  *
784  * \subsection concl Closing remarks
785  *
786  * The above may seem a little complicated, but hopefully I have made it clear
787  * why such complications are necessary. Also, do not forget that this only
788  * applies to applications that take libusb's file descriptors and integrate
789  * them into their own polling loops.
790  *
791  * You may decide that it is OK for your multi-threaded application to ignore
792  * some of the rules and locks detailed above, because you don't think that
793  * two threads can ever be polling the descriptors at the same time. If that
794  * is the case, then that's good news for you because you don't have to worry.
795  * But be careful here; remember that the synchronous I/O functions do event
796  * handling internally. If you have one thread doing event handling in a loop
797  * (without implementing the rules and locking semantics documented above)
798  * and another trying to send a synchronous USB transfer, you will end up with
799  * two threads monitoring the same descriptors, and the above-described
800  * undesirable behaviour occuring. The solution is for your polling thread to
801  * play by the rules; the synchronous I/O functions do so, and this will result
802  * in them getting along in perfect harmony.
803  *
804  * If you do have a dedicated thread doing event handling, it is perfectly
805  * legal for it to take the event handling lock and never release it. Any
806  * synchronous I/O functions you call from other threads will transparently
807  * fall back to the "event waiters" mechanism detailed above.
808  */
809
810 void usbi_io_init()
811 {
812         list_init(&flying_transfers);
813         list_init(&pollfds);
814         fd_added_cb = NULL;
815         fd_removed_cb = NULL;
816 }
817
818 static int calculate_timeout(struct usbi_transfer *transfer)
819 {
820         int r;
821         struct timespec current_time;
822         unsigned int timeout =
823                 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout;
824
825         if (!timeout)
826                 return 0;
827
828         r = clock_gettime(CLOCK_MONOTONIC, &current_time);
829         if (r < 0) {
830                 usbi_err("failed to read monotonic clock, errno=%d", errno);
831                 return r;
832         }
833
834         current_time.tv_sec += timeout / 1000;
835         current_time.tv_nsec += (timeout % 1000) * 1000000;
836
837         if (current_time.tv_nsec > 1000000000) {
838                 current_time.tv_nsec -= 1000000000;
839                 current_time.tv_sec++;
840         }
841
842         TIMESPEC_TO_TIMEVAL(&transfer->timeout, &current_time);
843         return 0;
844 }
845
846 static void add_to_flying_list(struct usbi_transfer *transfer)
847 {
848         struct usbi_transfer *cur;
849         struct timeval *timeout = &transfer->timeout;
850         
851         pthread_mutex_lock(&flying_transfers_lock);
852
853         /* if we have no other flying transfers, start the list with this one */
854         if (list_empty(&flying_transfers)) {
855                 list_add(&transfer->list, &flying_transfers);
856                 goto out;
857         }
858
859         /* if we have infinite timeout, append to end of list */
860         if (!timerisset(timeout)) {
861                 list_add_tail(&transfer->list, &flying_transfers);
862                 goto out;
863         }
864
865         /* otherwise, find appropriate place in list */
866         list_for_each_entry(cur, &flying_transfers, list) {
867                 /* find first timeout that occurs after the transfer in question */
868                 struct timeval *cur_tv = &cur->timeout;
869
870                 if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
871                                 (cur_tv->tv_sec == timeout->tv_sec &&
872                                         cur_tv->tv_usec > timeout->tv_usec)) {
873                         list_add_tail(&transfer->list, &cur->list);
874                         goto out;
875                 }
876         }
877
878         /* otherwise we need to be inserted at the end */
879         list_add_tail(&transfer->list, &flying_transfers);
880 out:
881         pthread_mutex_unlock(&flying_transfers_lock);
882 }
883
884 /** \ingroup asyncio
885  * Allocate a libusb transfer with a specified number of isochronous packet
886  * descriptors. The returned transfer is pre-initialized for you. When the new
887  * transfer is no longer needed, it should be freed with
888  * libusb_free_transfer().
889  *
890  * Transfers intended for non-isochronous endpoints (e.g. control, bulk,
891  * interrupt) should specify an iso_packets count of zero.
892  *
893  * For transfers intended for isochronous endpoints, specify an appropriate
894  * number of packet descriptors to be allocated as part of the transfer.
895  * The returned transfer is not specially initialized for isochronous I/O;
896  * you are still required to set the
897  * \ref libusb_transfer::num_iso_packets "num_iso_packets" and
898  * \ref libusb_transfer::type "type" fields accordingly.
899  *
900  * It is safe to allocate a transfer with some isochronous packets and then
901  * use it on a non-isochronous endpoint. If you do this, ensure that at time
902  * of submission, num_iso_packets is 0 and that type is set appropriately.
903  *
904  * \param iso_packets number of isochronous packet descriptors to allocate
905  * \returns a newly allocated transfer, or NULL on error
906  */
907 API_EXPORTED struct libusb_transfer *libusb_alloc_transfer(int iso_packets)
908 {
909         size_t os_alloc_size = usbi_backend->transfer_priv_size
910                 + (usbi_backend->add_iso_packet_size * iso_packets);
911         int alloc_size = sizeof(struct usbi_transfer)
912                 + sizeof(struct libusb_transfer)
913                 + (sizeof(struct libusb_iso_packet_descriptor) * iso_packets)
914                 + os_alloc_size;
915         struct usbi_transfer *itransfer = malloc(alloc_size);
916         if (!itransfer)
917                 return NULL;
918
919         memset(itransfer, 0, alloc_size);
920         itransfer->num_iso_packets = iso_packets;
921         return __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
922 }
923
924 /** \ingroup asyncio
925  * Free a transfer structure. This should be called for all transfers
926  * allocated with libusb_alloc_transfer().
927  *
928  * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
929  * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is
930  * non-NULL, this function will also free the transfer buffer using the
931  * standard system memory allocator (e.g. free()).
932  *
933  * It is legal to call this function with a NULL transfer. In this case,
934  * the function will simply return safely.
935  *
936  * \param transfer the transfer to free
937  */
938 API_EXPORTED void libusb_free_transfer(struct libusb_transfer *transfer)
939 {
940         struct usbi_transfer *itransfer;
941         if (!transfer)
942                 return;
943
944         if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)
945                 free(transfer->buffer);
946
947         itransfer = __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
948         free(itransfer);
949 }
950
951 /** \ingroup asyncio
952  * Submit a transfer. This function will fire off the USB transfer and then
953  * return immediately.
954  *
955  * It is undefined behaviour to submit a transfer that has already been
956  * submitted but has not yet completed.
957  *
958  * \param transfer the transfer to submit
959  * \returns 0 on success
960  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
961  * \returns another LIBUSB_ERROR code on other failure
962  */
963 API_EXPORTED int libusb_submit_transfer(struct libusb_transfer *transfer)
964 {
965         struct usbi_transfer *itransfer =
966                 __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
967         int r;
968
969         itransfer->transferred = 0;
970         r = calculate_timeout(itransfer);
971         if (r < 0)
972                 return LIBUSB_ERROR_OTHER;
973
974         add_to_flying_list(itransfer);
975         r = usbi_backend->submit_transfer(itransfer);
976         if (r) {
977                 pthread_mutex_lock(&flying_transfers_lock);
978                 list_del(&itransfer->list);
979                 pthread_mutex_unlock(&flying_transfers_lock);
980         }
981
982         return r;
983 }
984
985 /** \ingroup asyncio
986  * Asynchronously cancel a previously submitted transfer.
987  * It is undefined behaviour to call this function on a transfer that is
988  * already being cancelled or has already completed.
989  * This function returns immediately, but this does not indicate cancellation
990  * is complete. Your callback function will be invoked at some later time
991  * with a transfer status of
992  * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED
993  * "LIBUSB_TRANSFER_CANCELLED."
994  *
995  * \param transfer the transfer to cancel
996  * \returns 0 on success
997  * \returns a LIBUSB_ERROR code on failure
998  */
999 API_EXPORTED int libusb_cancel_transfer(struct libusb_transfer *transfer)
1000 {
1001         struct usbi_transfer *itransfer =
1002                 __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1003         int r;
1004
1005         usbi_dbg("");
1006         r = usbi_backend->cancel_transfer(itransfer);
1007         if (r < 0)
1008                 usbi_err("cancel transfer failed error %d", r);
1009         return r;
1010 }
1011
1012 /* Handle completion of a transfer (completion might be an error condition).
1013  * This will invoke the user-supplied callback function, which may end up
1014  * freeing the transfer. Therefore you cannot use the transfer structure
1015  * after calling this function, and you should free all backend-specific
1016  * data before calling it. */
1017 void usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
1018         enum libusb_transfer_status status)
1019 {
1020         struct libusb_transfer *transfer =
1021                 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1022         uint8_t flags;
1023
1024         pthread_mutex_lock(&flying_transfers_lock);
1025         list_del(&itransfer->list);
1026         pthread_mutex_unlock(&flying_transfers_lock);
1027
1028         if (status == LIBUSB_TRANSFER_COMPLETED
1029                         && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1030                 int rqlen = transfer->length;
1031                 if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL)
1032                         rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
1033                 if (rqlen != itransfer->transferred) {
1034                         usbi_dbg("interpreting short transfer as error");
1035                         status = LIBUSB_TRANSFER_ERROR;
1036                 }
1037         }
1038
1039         flags = transfer->flags;
1040         transfer->status = status;
1041         transfer->actual_length = itransfer->transferred;
1042         if (transfer->callback)
1043                 transfer->callback(transfer);
1044         /* transfer might have been freed by the above call, do not use from
1045          * this point. */
1046         if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
1047                 libusb_free_transfer(transfer);
1048         pthread_mutex_lock(&event_waiters_lock);
1049         pthread_cond_broadcast(&event_waiters_cond);
1050         pthread_mutex_unlock(&event_waiters_lock);
1051 }
1052
1053 /* Similar to usbi_handle_transfer_completion() but exclusively for transfers
1054  * that were asynchronously cancelled. The same concerns w.r.t. freeing of
1055  * transfers exist here.
1056  */
1057 void usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
1058 {
1059         /* if the URB was cancelled due to timeout, report timeout to the user */
1060         if (transfer->flags & USBI_TRANSFER_TIMED_OUT) {
1061                 usbi_dbg("detected timeout cancellation");
1062                 usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT);
1063                 return;
1064         }
1065
1066         /* otherwise its a normal async cancel */
1067         usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
1068 }
1069
1070 /** \ingroup poll
1071  * Attempt to acquire the event handling lock. This lock is used to ensure that
1072  * only one thread is monitoring libusb event sources at any one time.
1073  *
1074  * You only need to use this lock if you are developing an application
1075  * which calls poll() or select() on libusb's file descriptors directly.
1076  * If you stick to libusb's event handling loop functions (e.g.
1077  * libusb_handle_events()) then you do not need to be concerned with this
1078  * locking.
1079  *
1080  * While holding this lock, you are trusted to actually be handling events.
1081  * If you are no longer handling events, you must call libusb_unlock_events()
1082  * as soon as possible.
1083  *
1084  * \returns 0 if the lock was obtained successfully
1085  * \returns 1 if the lock was not obtained (i.e. another thread holds the lock)
1086  * \see \ref mtasync
1087  */
1088 API_EXPORTED int libusb_try_lock_events(void)
1089 {
1090         int r = pthread_mutex_trylock(&events_lock);
1091         if (r)
1092                 return 1;
1093
1094         event_handler_active = 1;       
1095         return 0;
1096 }
1097
1098 /** \ingroup poll
1099  * Acquire the event handling lock, blocking until successful acquisition if
1100  * it is contended. This lock is used to ensure that only one thread is
1101  * monitoring libusb event sources at any one time.
1102  *
1103  * You only need to use this lock if you are developing an application
1104  * which calls poll() or select() on libusb's file descriptors directly.
1105  * If you stick to libusb's event handling loop functions (e.g.
1106  * libusb_handle_events()) then you do not need to be concerned with this
1107  * locking.
1108  *
1109  * While holding this lock, you are trusted to actually be handling events.
1110  * If you are no longer handling events, you must call libusb_unlock_events()
1111  * as soon as possible.
1112  *
1113  * \see \ref mtasync
1114  */
1115 API_EXPORTED void libusb_lock_events(void)
1116 {
1117         pthread_mutex_lock(&events_lock);
1118         event_handler_active = 1;
1119 }
1120
1121 /** \ingroup poll
1122  * Release the lock previously acquired with libusb_try_lock_events() or
1123  * libusb_lock_events(). Releasing this lock will wake up any threads blocked
1124  * on libusb_wait_for_event().
1125  *
1126  * \see \ref mtasync
1127  */
1128 API_EXPORTED void libusb_unlock_events(void)
1129 {
1130         event_handler_active = 0;
1131         pthread_mutex_unlock(&events_lock);
1132
1133         pthread_mutex_lock(&event_waiters_lock);
1134         pthread_cond_broadcast(&event_waiters_cond);
1135         pthread_mutex_unlock(&event_waiters_lock);
1136 }
1137
1138 /** \ingroup poll
1139  * Determine if an active thread is handling events (i.e. if anyone is holding
1140  * the event handling lock).
1141  *
1142  * \returns 1 if a thread is handling events
1143  * \returns 0 if there are no threads currently handling events
1144  * \see \ref mtasync
1145  */
1146 API_EXPORTED int libusb_event_handler_active(void)
1147 {
1148         int r;
1149
1150         if (!event_handler_active)
1151                 return 0;
1152
1153         /* FIXME: temporary hack to ensure thread didn't quit (e.g. due to signal)
1154          * without libusb_unlock_events being triggered */
1155         r = pthread_mutex_trylock(&events_lock);
1156         if (r == 0) {
1157                 event_handler_active = 0;
1158                 pthread_mutex_unlock(&events_lock);
1159                 return 0;
1160         }
1161
1162         return 1;
1163 }
1164
1165 /** \ingroup poll
1166  * Acquire the event waiters lock. This lock is designed to be obtained under
1167  * the situation where you want to be aware when events are completed, but
1168  * some other thread is event handling so calling libusb_handle_events() is not
1169  * allowed.
1170  *
1171  * You then obtain this lock, re-check that another thread is still handling
1172  * events, then call libusb_wait_for_event().
1173  *
1174  * You only need to use this lock if you are developing an application
1175  * which calls poll() or select() on libusb's file descriptors directly,
1176  * <b>and</b> may potentially be handling events from 2 threads simultaenously.
1177  * If you stick to libusb's event handling loop functions (e.g.
1178  * libusb_handle_events()) then you do not need to be concerned with this
1179  * locking.
1180  *
1181  * \see \ref mtasync
1182  */
1183 API_EXPORTED void libusb_lock_event_waiters(void)
1184 {
1185         pthread_mutex_lock(&event_waiters_lock);
1186 }
1187
1188 /** \ingroup poll
1189  * Release the event waiters lock.
1190  * \see \ref mtasync
1191  */
1192 API_EXPORTED void libusb_unlock_event_waiters(void)
1193 {
1194         pthread_mutex_unlock(&event_waiters_lock);
1195 }
1196
1197 /** \ingroup poll
1198  * Wait for another thread to signal completion of an event. Must be called
1199  * with the event waiters lock held, see libusb_lock_event_waiters().
1200  *
1201  * This function will block until any of the following conditions are met:
1202  * -# The timeout expires
1203  * -# A transfer completes
1204  * -# A thread releases the event handling lock through libusb_unlock_events()
1205  *
1206  * Condition 1 is obvious. Condition 2 unblocks your thread <em>after</em>
1207  * the callback for the transfer has completed. Condition 3 is important
1208  * because it means that the thread that was previously handling events is no
1209  * longer doing so, so if any events are to complete, another thread needs to
1210  * step up and start event handling.
1211  *
1212  * This function releases the event waiters lock before putting your thread
1213  * to sleep, and reacquires the lock as it is being woken up.
1214  *
1215  * \param tv maximum timeout for this blocking function. A NULL value
1216  * indicates unlimited timeout.
1217  * \returns 0 after a transfer completes or another thread stops event handling
1218  * \returns 1 if the timeout expired
1219  * \see \ref mtasync
1220  */
1221 API_EXPORTED int libusb_wait_for_event(struct timeval *tv)
1222 {
1223         struct timespec timeout;
1224         int r;
1225
1226         if (tv == NULL) {
1227                 pthread_cond_wait(&event_waiters_cond, &event_waiters_lock);
1228                 return 0;
1229         }
1230
1231         r = clock_gettime(CLOCK_REALTIME, &timeout);
1232         if (r < 0) {
1233                 usbi_err("failed to read realtime clock, error %d", errno);
1234                 return LIBUSB_ERROR_OTHER;
1235         }
1236
1237         timeout.tv_sec += tv->tv_sec;
1238         timeout.tv_nsec += tv->tv_usec * 1000;
1239         if (timeout.tv_nsec > 1000000000) {
1240                 timeout.tv_nsec -= 1000000000;
1241                 timeout.tv_sec++;
1242         }
1243
1244         r = pthread_cond_timedwait(&event_waiters_cond, &event_waiters_lock,
1245                 &timeout);
1246         return (r == ETIMEDOUT);
1247 }
1248
1249 static void handle_timeout(struct usbi_transfer *itransfer)
1250 {
1251         struct libusb_transfer *transfer =
1252                 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1253         int r;
1254
1255         itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1256         r = libusb_cancel_transfer(transfer);
1257         if (r < 0)
1258                 usbi_warn("async cancel failed %d errno=%d", r, errno);
1259 }
1260
1261 static int handle_timeouts(void)
1262 {
1263         struct timespec systime_ts;
1264         struct timeval systime;
1265         struct usbi_transfer *transfer;
1266         int r = 0;
1267
1268         pthread_mutex_lock(&flying_transfers_lock);
1269         if (list_empty(&flying_transfers))
1270                 goto out;
1271
1272         /* get current time */
1273         r = clock_gettime(CLOCK_MONOTONIC, &systime_ts);
1274         if (r < 0)
1275                 goto out;
1276
1277         TIMESPEC_TO_TIMEVAL(&systime, &systime_ts);
1278
1279         /* iterate through flying transfers list, finding all transfers that
1280          * have expired timeouts */
1281         list_for_each_entry(transfer, &flying_transfers, list) {
1282                 struct timeval *cur_tv = &transfer->timeout;
1283
1284                 /* if we've reached transfers of infinite timeout, we're all done */
1285                 if (!timerisset(cur_tv))
1286                         goto out;
1287
1288                 /* ignore timeouts we've already handled */
1289                 if (transfer->flags & USBI_TRANSFER_TIMED_OUT)
1290                         continue;
1291
1292                 /* if transfer has non-expired timeout, nothing more to do */
1293                 if ((cur_tv->tv_sec > systime.tv_sec) ||
1294                                 (cur_tv->tv_sec == systime.tv_sec &&
1295                                         cur_tv->tv_usec > systime.tv_usec))
1296                         goto out;
1297         
1298                 /* otherwise, we've got an expired timeout to handle */
1299                 handle_timeout(transfer);
1300         }
1301
1302 out:
1303         pthread_mutex_unlock(&flying_transfers_lock);
1304         return r;
1305 }
1306
1307 /* do the actual event handling. assumes that no other thread is concurrently
1308  * doing the same thing. */
1309 static int handle_events(struct timeval *tv)
1310 {
1311         int r;
1312         struct usbi_pollfd *ipollfd;
1313         nfds_t nfds = 0;
1314         struct pollfd *fds;
1315         int i = -1;
1316         int timeout_ms;
1317
1318         pthread_mutex_lock(&pollfds_lock);
1319         list_for_each_entry(ipollfd, &pollfds, list)
1320                 nfds++;
1321
1322         /* TODO: malloc when number of fd's changes, not on every poll */
1323         fds = malloc(sizeof(*fds) * nfds);
1324         if (!fds)
1325                 return LIBUSB_ERROR_NO_MEM;
1326
1327         list_for_each_entry(ipollfd, &pollfds, list) {
1328                 struct libusb_pollfd *pollfd = &ipollfd->pollfd;
1329                 int fd = pollfd->fd;
1330                 i++;
1331                 fds[i].fd = fd;
1332                 fds[i].events = pollfd->events;
1333                 fds[i].revents = 0;
1334         }
1335         pthread_mutex_unlock(&pollfds_lock);
1336
1337         timeout_ms = (tv->tv_sec * 1000) + (tv->tv_usec / 1000);
1338         usbi_dbg("poll() %d fds with timeout in %dms", nfds, timeout_ms);
1339         r = poll(fds, nfds, timeout_ms);
1340         usbi_dbg("poll() returned %d", r);
1341         if (r == 0) {
1342                 free(fds);
1343                 return handle_timeouts();
1344         } else if (r == -1 && errno == EINTR) {
1345                 free(fds);
1346                 return LIBUSB_ERROR_INTERRUPTED;
1347         } else if (r < 0) {
1348                 free(fds);
1349                 usbi_err("poll failed %d err=%d\n", r, errno);
1350                 return LIBUSB_ERROR_IO;
1351         }
1352
1353         r = usbi_backend->handle_events(fds, nfds, r);
1354         if (r)
1355                 usbi_err("backend handle_events failed with error %d", r);
1356
1357         free(fds);
1358         return r;
1359 }
1360
1361 /* returns the smallest of:
1362  *  1. timeout of next URB
1363  *  2. user-supplied timeout
1364  * returns 1 if there is an already-expired timeout, otherwise returns 0
1365  * and populates out
1366  */
1367 static int get_next_timeout(struct timeval *tv, struct timeval *out)
1368 {
1369         struct timeval timeout;
1370         int r = libusb_get_next_timeout(&timeout);
1371         if (r) {
1372                 /* timeout already expired? */
1373                 if (!timerisset(&timeout))
1374                         return 1;
1375
1376                 /* choose the smallest of next URB timeout or user specified timeout */
1377                 if (timercmp(&timeout, tv, <))
1378                         *out = timeout;
1379                 else
1380                         *out = *tv;
1381         } else {
1382                 *out = *tv;
1383         }
1384         return 0;
1385 }
1386
1387 /** \ingroup poll
1388  * Handle any pending events.
1389  *
1390  * libusb determines "pending events" by checking if any timeouts have expired
1391  * and by checking the set of file descriptors for activity.
1392  *
1393  * If a zero timeval is passed, this function will handle any already-pending
1394  * events and then immediately return in non-blocking style.
1395  *
1396  * If a non-zero timeval is passed and no events are currently pending, this
1397  * function will block waiting for events to handle up until the specified
1398  * timeout. If an event arrives or a signal is raised, this function will
1399  * return early.
1400  *
1401  * \param tv the maximum time to block waiting for events, or zero for
1402  * non-blocking mode
1403  * \returns 0 on success, or a LIBUSB_ERROR code on failure
1404  */
1405 API_EXPORTED int libusb_handle_events_timeout(struct timeval *tv)
1406 {
1407         int r;
1408         struct timeval poll_timeout;
1409
1410         r = get_next_timeout(tv, &poll_timeout);
1411         if (r) {
1412                 /* timeout already expired */
1413                 return handle_timeouts();
1414         }
1415
1416 retry:
1417         if (libusb_try_lock_events() == 0) {
1418                 /* we obtained the event lock: do our own event handling */
1419                 r = handle_events(&poll_timeout);
1420                 libusb_unlock_events();
1421                 return r;
1422         }
1423
1424         /* another thread is doing event handling. wait for pthread events that
1425          * notify event completion. */
1426         libusb_lock_event_waiters();
1427
1428         if (!libusb_event_handler_active()) {
1429                 /* we hit a race: whoever was event handling earlier finished in the
1430                  * time it took us to reach this point. try the cycle again. */
1431                 libusb_unlock_event_waiters();
1432                 usbi_dbg("event handler was active but went away, retrying");
1433                 goto retry;
1434         }
1435
1436         usbi_dbg("another thread is doing event handling");
1437         r = libusb_wait_for_event(&poll_timeout);
1438         libusb_unlock_event_waiters();
1439
1440         if (r < 0)
1441                 return r;
1442         else if (r == 1)
1443                 return handle_timeouts();
1444         else
1445                 return 0;
1446 }
1447
1448 /** \ingroup poll
1449  * Handle any pending events in blocking mode with a sensible timeout. This
1450  * timeout is currently hardcoded at 2 seconds but we may change this if we
1451  * decide other values are more sensible. For finer control over whether this
1452  * function is blocking or non-blocking, or the maximum timeout, use
1453  * libusb_handle_events_timeout() instead.
1454  *
1455  * \returns 0 on success, or a LIBUSB_ERROR code on failure
1456  */
1457 API_EXPORTED int libusb_handle_events(void)
1458 {
1459         struct timeval tv;
1460         tv.tv_sec = 2;
1461         tv.tv_usec = 0;
1462         return libusb_handle_events_timeout(&tv);
1463 }
1464
1465 /** \ingroup poll
1466  * Handle any pending events by polling file descriptors, without checking if
1467  * any other threads are already doing so. Must be called with the event lock
1468  * held, see libusb_lock_events().
1469  *
1470  * This function is designed to be called under the situation where you have
1471  * taken the event lock and are calling poll()/select() directly on libusb's
1472  * file descriptors (as opposed to using libusb_handle_events() or similar).
1473  * You detect events on libusb's descriptors, so you then call this function
1474  * with a zero timeout value (while still holding the event lock).
1475  *
1476  * \param tv the maximum time to block waiting for events, or zero for
1477  * non-blocking mode
1478  * \returns 0 on success, or a LIBUSB_ERROR code on failure
1479  * \see \ref mtasync
1480  */
1481 API_EXPORTED int libusb_handle_events_locked(struct timeval *tv)
1482 {
1483         int r;
1484         struct timeval poll_timeout;
1485
1486         r = get_next_timeout(tv, &poll_timeout);
1487         if (r) {
1488                 /* timeout already expired */
1489                 return handle_timeouts();
1490         }
1491
1492         return handle_events(&poll_timeout);
1493 }
1494
1495 /** \ingroup poll
1496  * Determine the next internal timeout that libusb needs to handle. You only
1497  * need to use this function if you are calling poll() or select() or similar
1498  * on libusb's file descriptors yourself - you do not need to use it if you
1499  * are calling libusb_handle_events() or a variant directly.
1500  * 
1501  * You should call this function in your main loop in order to determine how
1502  * long to wait for select() or poll() to return results. libusb needs to be
1503  * called into at this timeout, so you should use it as an upper bound on
1504  * your select() or poll() call.
1505  *
1506  * When the timeout has expired, call into libusb_handle_events_timeout()
1507  * (perhaps in non-blocking mode) so that libusb can handle the timeout.
1508  *
1509  * This function may return 1 (success) and an all-zero timeval. If this is
1510  * the case, it indicates that libusb has a timeout that has already expired
1511  * so you should call libusb_handle_events_timeout() or similar immediately.
1512  * A return code of 0 indicates that there are no pending timeouts.
1513  *
1514  * \param tv output location for a relative time against the current
1515  * clock in which libusb must be called into in order to process timeout events
1516  * \returns 0 if there are no pending timeouts, 1 if a timeout was returned,
1517  * or LIBUSB_ERROR_OTHER on failure
1518  */
1519 API_EXPORTED int libusb_get_next_timeout(struct timeval *tv)
1520 {
1521         struct usbi_transfer *transfer;
1522         struct timespec cur_ts;
1523         struct timeval cur_tv;
1524         struct timeval *next_timeout;
1525         int r;
1526         int found = 0;
1527
1528         pthread_mutex_lock(&flying_transfers_lock);
1529         if (list_empty(&flying_transfers)) {
1530                 pthread_mutex_unlock(&flying_transfers_lock);
1531                 usbi_dbg("no URBs, no timeout!");
1532                 return 0;
1533         }
1534
1535         /* find next transfer which hasn't already been processed as timed out */
1536         list_for_each_entry(transfer, &flying_transfers, list) {
1537                 if (!(transfer->flags & USBI_TRANSFER_TIMED_OUT)) {
1538                         found = 1;
1539                         break;
1540                 }
1541         }
1542         pthread_mutex_unlock(&flying_transfers_lock);
1543
1544         if (!found) {
1545                 usbi_dbg("all URBs have already been processed for timeouts");
1546                 return 0;
1547         }
1548
1549         next_timeout = &transfer->timeout;
1550
1551         /* no timeout for next transfer */
1552         if (!timerisset(next_timeout)) {
1553                 usbi_dbg("no URBs with timeouts, no timeout!");
1554                 return 0;
1555         }
1556
1557         r = clock_gettime(CLOCK_MONOTONIC, &cur_ts);
1558         if (r < 0) {
1559                 usbi_err("failed to read monotonic clock, errno=%d", errno);
1560                 return LIBUSB_ERROR_OTHER;
1561         }
1562         TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts);
1563
1564         if (timercmp(&cur_tv, next_timeout, >=)) {
1565                 usbi_dbg("first timeout already expired");
1566                 timerclear(tv);
1567         } else {
1568                 timersub(next_timeout, &cur_tv, tv);
1569                 usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec);
1570         }
1571
1572         return 1;
1573 }
1574
1575 /** \ingroup poll
1576  * Register notification functions for file descriptor additions/removals.
1577  * These functions will be invoked for every new or removed file descriptor
1578  * that libusb uses as an event source.
1579  *
1580  * To remove notifiers, pass NULL values for the function pointers.
1581  *
1582  * \param added_cb pointer to function for addition notifications
1583  * \param removed_cb pointer to function for removal notifications
1584  */
1585 API_EXPORTED void libusb_set_pollfd_notifiers(libusb_pollfd_added_cb added_cb,
1586         libusb_pollfd_removed_cb removed_cb)
1587 {
1588         fd_added_cb = added_cb;
1589         fd_removed_cb = removed_cb;
1590 }
1591
1592 /* Add a file descriptor to the list of file descriptors to be monitored.
1593  * events should be specified as a bitmask of events passed to poll(), e.g.
1594  * POLLIN and/or POLLOUT. */
1595 int usbi_add_pollfd(int fd, short events)
1596 {
1597         struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
1598         if (!ipollfd)
1599                 return LIBUSB_ERROR_NO_MEM;
1600
1601         usbi_dbg("add fd %d events %d", fd, events);
1602         ipollfd->pollfd.fd = fd;
1603         ipollfd->pollfd.events = events;
1604         pthread_mutex_lock(&pollfds_lock);
1605         list_add(&ipollfd->list, &pollfds);
1606         pthread_mutex_unlock(&pollfds_lock);
1607
1608         if (fd_added_cb)
1609                 fd_added_cb(fd, events);
1610         return 0;
1611 }
1612
1613 /* Remove a file descriptor from the list of file descriptors to be polled. */
1614 void usbi_remove_pollfd(int fd)
1615 {
1616         struct usbi_pollfd *ipollfd;
1617         int found = 0;
1618
1619         usbi_dbg("remove fd %d", fd);
1620         pthread_mutex_lock(&pollfds_lock);
1621         list_for_each_entry(ipollfd, &pollfds, list)
1622                 if (ipollfd->pollfd.fd == fd) {
1623                         found = 1;
1624                         break;
1625                 }
1626
1627         if (!found) {
1628                 usbi_dbg("couldn't find fd %d to remove", fd);
1629                 pthread_mutex_unlock(&pollfds_lock);
1630                 return;
1631         }
1632
1633         list_del(&ipollfd->list);
1634         pthread_mutex_unlock(&pollfds_lock);
1635         free(ipollfd);
1636         if (fd_removed_cb)
1637                 fd_removed_cb(fd);
1638 }
1639
1640 /** \ingroup poll
1641  * Retrieve a list of file descriptors that should be polled by your main loop
1642  * as libusb event sources.
1643  *
1644  * The returned list is NULL-terminated and should be freed with free() when
1645  * done. The actual list contents must not be touched.
1646  *
1647  * \returns a NULL-terminated list of libusb_pollfd structures, or NULL on
1648  * error
1649  */
1650 API_EXPORTED const struct libusb_pollfd **libusb_get_pollfds(void)
1651 {
1652         struct libusb_pollfd **ret = NULL;
1653         struct usbi_pollfd *ipollfd;
1654         size_t i = 0;
1655         size_t cnt = 0;
1656
1657         pthread_mutex_lock(&pollfds_lock);
1658         list_for_each_entry(ipollfd, &pollfds, list)
1659                 cnt++;
1660
1661         ret = calloc(cnt + 1, sizeof(struct libusb_pollfd *));
1662         if (!ret)
1663                 goto out;
1664
1665         list_for_each_entry(ipollfd, &pollfds, list)
1666                 ret[i++] = (struct libusb_pollfd *) ipollfd;
1667         ret[cnt] = NULL;
1668
1669 out:
1670         pthread_mutex_unlock(&pollfds_lock);
1671         return (const struct libusb_pollfd **) ret;
1672 }
1673
1674 /* Backends call this from handle_events to report disconnection of a device.
1675  * The transfers get cancelled appropriately.
1676  */
1677 void usbi_handle_disconnect(struct libusb_device_handle *handle)
1678 {
1679         struct usbi_transfer *cur;
1680         struct usbi_transfer *to_cancel;
1681
1682         usbi_dbg("device %d.%d",
1683                 handle->dev->bus_number, handle->dev->device_address);
1684
1685         /* terminate all pending transfers with the LIBUSB_TRANSFER_NO_DEVICE
1686          * status code.
1687          * 
1688          * this is a bit tricky because:
1689          * 1. we can't do transfer completion while holding flying_transfers_lock
1690          * 2. the transfers list can change underneath us - if we were to build a
1691          *    list of transfers to complete (while holding look), the situation
1692          *    might be different by the time we come to free them
1693          *
1694          * so we resort to a loop-based approach as below
1695          * FIXME: is this still potentially racy?
1696          */
1697
1698         while (1) {
1699                 pthread_mutex_lock(&flying_transfers_lock);
1700                 to_cancel = NULL;
1701                 list_for_each_entry(cur, &flying_transfers, list)
1702                         if (__USBI_TRANSFER_TO_LIBUSB_TRANSFER(cur)->dev_handle == handle) {
1703                                 to_cancel = cur;
1704                                 break;
1705                         }
1706                 pthread_mutex_unlock(&flying_transfers_lock);
1707
1708                 if (!to_cancel)
1709                         break;
1710
1711                 usbi_backend->clear_transfer_priv(to_cancel);
1712                 usbi_handle_transfer_completion(to_cancel, LIBUSB_TRANSFER_NO_DEVICE);
1713         }
1714
1715 }
1716