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