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