core: Move parameter validation from backend to core
[platform/upstream/libusb.git] / libusb / io.c
1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2 /*
3  * I/O functions for libusb
4  * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
5  * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6  * Copyright © 2019 Nathan Hjelm <hjelmn@cs.umm.edu>
7  * Copyright © 2019 Google LLC. All rights reserved.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include "libusbi.h"
25 #include "hotplug.h"
26
27 #include <errno.h>
28 #ifdef HAVE_TIMERFD
29 #include <sys/timerfd.h>
30 #include <unistd.h>
31 #endif
32
33 /**
34  * \page libusb_io Synchronous and asynchronous device I/O
35  *
36  * \section io_intro Introduction
37  *
38  * If you're using libusb in your application, you're probably wanting to
39  * perform I/O with devices - you want to perform USB data transfers.
40  *
41  * libusb offers two separate interfaces for device I/O. This page aims to
42  * introduce the two in order to help you decide which one is more suitable
43  * for your application. You can also choose to use both interfaces in your
44  * application by considering each transfer on a case-by-case basis.
45  *
46  * Once you have read through the following discussion, you should consult the
47  * detailed API documentation pages for the details:
48  * - \ref libusb_syncio
49  * - \ref libusb_asyncio
50  *
51  * \section theory Transfers at a logical level
52  *
53  * At a logical level, USB transfers typically happen in two parts. For
54  * example, when reading data from a endpoint:
55  * -# A request for data is sent to the device
56  * -# Some time later, the incoming data is received by the host
57  *
58  * or when writing data to an endpoint:
59  *
60  * -# The data is sent to the device
61  * -# Some time later, the host receives acknowledgement from the device that
62  *    the data has been transferred.
63  *
64  * There may be an indefinite delay between the two steps. Consider a
65  * fictional USB input device with a button that the user can press. In order
66  * to determine when the button is pressed, you would likely submit a request
67  * to read data on a bulk or interrupt endpoint and wait for data to arrive.
68  * Data will arrive when the button is pressed by the user, which is
69  * potentially hours later.
70  *
71  * libusb offers both a synchronous and an asynchronous interface to performing
72  * USB transfers. The main difference is that the synchronous interface
73  * combines both steps indicated above into a single function call, whereas
74  * the asynchronous interface separates them.
75  *
76  * \section sync The synchronous interface
77  *
78  * The synchronous I/O interface allows you to perform a USB transfer with
79  * a single function call. When the function call returns, the transfer has
80  * completed and you can parse the results.
81  *
82  * If you have used the libusb-0.1 before, this I/O style will seem familar to
83  * you. libusb-0.1 only offered a synchronous interface.
84  *
85  * In our input device example, to read button presses you might write code
86  * in the following style:
87 \code
88 unsigned char data[4];
89 int actual_length;
90 int r = libusb_bulk_transfer(dev_handle, LIBUSB_ENDPOINT_IN, data, sizeof(data), &actual_length, 0);
91 if (r == 0 && actual_length == sizeof(data)) {
92         // results of the transaction can now be found in the data buffer
93         // parse them here and report button press
94 } else {
95         error();
96 }
97 \endcode
98  *
99  * The main advantage of this model is simplicity: you did everything with
100  * a single simple function call.
101  *
102  * However, this interface has its limitations. Your application will sleep
103  * inside libusb_bulk_transfer() until the transaction has completed. If it
104  * takes the user 3 hours to press the button, your application will be
105  * sleeping for that long. Execution will be tied up inside the library -
106  * the entire thread will be useless for that duration.
107  *
108  * Another issue is that by tieing up the thread with that single transaction
109  * there is no possibility of performing I/O with multiple endpoints and/or
110  * multiple devices simultaneously, unless you resort to creating one thread
111  * per transaction.
112  *
113  * Additionally, there is no opportunity to cancel the transfer after the
114  * request has been submitted.
115  *
116  * For details on how to use the synchronous API, see the
117  * \ref libusb_syncio "synchronous I/O API documentation" pages.
118  *
119  * \section async The asynchronous interface
120  *
121  * Asynchronous I/O is the most significant new feature in libusb-1.0.
122  * Although it is a more complex interface, it solves all the issues detailed
123  * above.
124  *
125  * Instead of providing which functions that block until the I/O has complete,
126  * libusb's asynchronous interface presents non-blocking functions which
127  * begin a transfer and then return immediately. Your application passes a
128  * callback function pointer to this non-blocking function, which libusb will
129  * call with the results of the transaction when it has completed.
130  *
131  * Transfers which have been submitted through the non-blocking functions
132  * can be cancelled with a separate function call.
133  *
134  * The non-blocking nature of this interface allows you to be simultaneously
135  * performing I/O to multiple endpoints on multiple devices, without having
136  * to use threads.
137  *
138  * This added flexibility does come with some complications though:
139  * - In the interest of being a lightweight library, libusb does not create
140  * threads and can only operate when your application is calling into it. Your
141  * application must call into libusb from it's main loop when events are ready
142  * to be handled, or you must use some other scheme to allow libusb to
143  * undertake whatever work needs to be done.
144  * - libusb also needs to be called into at certain fixed points in time in
145  * order to accurately handle transfer timeouts.
146  * - Memory handling becomes more complex. You cannot use stack memory unless
147  * the function with that stack is guaranteed not to return until the transfer
148  * callback has finished executing.
149  * - You generally lose some linearity from your code flow because submitting
150  * the transfer request is done in a separate function from where the transfer
151  * results are handled. This becomes particularly obvious when you want to
152  * submit a second transfer based on the results of an earlier transfer.
153  *
154  * Internally, libusb's synchronous interface is expressed in terms of function
155  * calls to the asynchronous interface.
156  *
157  * For details on how to use the asynchronous API, see the
158  * \ref libusb_asyncio "asynchronous I/O API" documentation pages.
159  */
160
161
162 /**
163  * \page libusb_packetoverflow Packets and overflows
164  *
165  * \section packets Packet abstraction
166  *
167  * The USB specifications describe how data is transmitted in packets, with
168  * constraints on packet size defined by endpoint descriptors. The host must
169  * not send data payloads larger than the endpoint's maximum packet size.
170  *
171  * libusb and the underlying OS abstract out the packet concept, allowing you
172  * to request transfers of any size. Internally, the request will be divided
173  * up into correctly-sized packets. You do not have to be concerned with
174  * packet sizes, but there is one exception when considering overflows.
175  *
176  * \section overflow Bulk/interrupt transfer overflows
177  *
178  * When requesting data on a bulk endpoint, libusb requires you to supply a
179  * buffer and the maximum number of bytes of data that libusb can put in that
180  * buffer. However, the size of the buffer is not communicated to the device -
181  * the device is just asked to send any amount of data.
182  *
183  * There is no problem if the device sends an amount of data that is less than
184  * or equal to the buffer size. libusb reports this condition to you through
185  * the \ref libusb_transfer::actual_length "libusb_transfer.actual_length"
186  * field.
187  *
188  * Problems may occur if the device attempts to send more data than can fit in
189  * the buffer. libusb reports LIBUSB_TRANSFER_OVERFLOW for this condition but
190  * other behaviour is largely undefined: actual_length may or may not be
191  * accurate, the chunk of data that can fit in the buffer (before overflow)
192  * may or may not have been transferred.
193  *
194  * Overflows are nasty, but can be avoided. Even though you were told to
195  * ignore packets above, think about the lower level details: each transfer is
196  * split into packets (typically small, with a maximum size of 512 bytes).
197  * Overflows can only happen if the final packet in an incoming data transfer
198  * is smaller than the actual packet that the device wants to transfer.
199  * Therefore, you will never see an overflow if your transfer buffer size is a
200  * multiple of the endpoint's packet size: the final packet will either
201  * fill up completely or will be only partially filled.
202  */
203
204 /**
205  * @defgroup libusb_asyncio Asynchronous device I/O
206  *
207  * This page details libusb's asynchronous (non-blocking) API for USB device
208  * I/O. This interface is very powerful but is also quite complex - you will
209  * need to read this page carefully to understand the necessary considerations
210  * and issues surrounding use of this interface. Simplistic applications
211  * may wish to consider the \ref libusb_syncio "synchronous I/O API" instead.
212  *
213  * The asynchronous interface is built around the idea of separating transfer
214  * submission and handling of transfer completion (the synchronous model
215  * combines both of these into one). There may be a long delay between
216  * submission and completion, however the asynchronous submission function
217  * is non-blocking so will return control to your application during that
218  * potentially long delay.
219  *
220  * \section asyncabstraction Transfer abstraction
221  *
222  * For the asynchronous I/O, libusb implements the concept of a generic
223  * transfer entity for all types of I/O (control, bulk, interrupt,
224  * isochronous). The generic transfer object must be treated slightly
225  * differently depending on which type of I/O you are performing with it.
226  *
227  * This is represented by the public libusb_transfer structure type.
228  *
229  * \section asynctrf Asynchronous transfers
230  *
231  * We can view asynchronous I/O as a 5 step process:
232  * -# <b>Allocation</b>: allocate a libusb_transfer
233  * -# <b>Filling</b>: populate the libusb_transfer instance with information
234  *    about the transfer you wish to perform
235  * -# <b>Submission</b>: ask libusb to submit the transfer
236  * -# <b>Completion handling</b>: examine transfer results in the
237  *    libusb_transfer structure
238  * -# <b>Deallocation</b>: clean up resources
239  *
240  *
241  * \subsection asyncalloc Allocation
242  *
243  * This step involves allocating memory for a USB transfer. This is the
244  * generic transfer object mentioned above. At this stage, the transfer
245  * is "blank" with no details about what type of I/O it will be used for.
246  *
247  * Allocation is done with the libusb_alloc_transfer() function. You must use
248  * this function rather than allocating your own transfers.
249  *
250  * \subsection asyncfill Filling
251  *
252  * This step is where you take a previously allocated transfer and fill it
253  * with information to determine the message type and direction, data buffer,
254  * callback function, etc.
255  *
256  * You can either fill the required fields yourself or you can use the
257  * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer()
258  * and libusb_fill_interrupt_transfer().
259  *
260  * \subsection asyncsubmit Submission
261  *
262  * When you have allocated a transfer and filled it, you can submit it using
263  * libusb_submit_transfer(). This function returns immediately but can be
264  * regarded as firing off the I/O request in the background.
265  *
266  * \subsection asynccomplete Completion handling
267  *
268  * After a transfer has been submitted, one of four things can happen to it:
269  *
270  * - The transfer completes (i.e. some data was transferred)
271  * - The transfer has a timeout and the timeout expires before all data is
272  * transferred
273  * - The transfer fails due to an error
274  * - The transfer is cancelled
275  *
276  * Each of these will cause the user-specified transfer callback function to
277  * be invoked. It is up to the callback function to determine which of the
278  * above actually happened and to act accordingly.
279  *
280  * The user-specified callback is passed a pointer to the libusb_transfer
281  * structure which was used to setup and submit the transfer. At completion
282  * time, libusb has populated this structure with results of the transfer:
283  * success or failure reason, number of bytes of data transferred, etc. See
284  * the libusb_transfer structure documentation for more information.
285  *
286  * <b>Important Note</b>: The user-specified callback is called from an event
287  * handling context. It is therefore important that no calls are made into
288  * libusb that will attempt to perform any event handling. Examples of such
289  * functions are any listed in the \ref libusb_syncio "synchronous API" and any of
290  * the blocking functions that retrieve \ref libusb_desc "USB descriptors".
291  *
292  * \subsection Deallocation
293  *
294  * When a transfer has completed (i.e. the callback function has been invoked),
295  * you are advised to free the transfer (unless you wish to resubmit it, see
296  * below). Transfers are deallocated with libusb_free_transfer().
297  *
298  * It is undefined behaviour to free a transfer which has not completed.
299  *
300  * \section asyncresubmit Resubmission
301  *
302  * You may be wondering why allocation, filling, and submission are all
303  * separated above where they could reasonably be combined into a single
304  * operation.
305  *
306  * The reason for separation is to allow you to resubmit transfers without
307  * having to allocate new ones every time. This is especially useful for
308  * common situations dealing with interrupt endpoints - you allocate one
309  * transfer, fill and submit it, and when it returns with results you just
310  * resubmit it for the next interrupt.
311  *
312  * \section asynccancel Cancellation
313  *
314  * Another advantage of using the asynchronous interface is that you have
315  * the ability to cancel transfers which have not yet completed. This is
316  * done by calling the libusb_cancel_transfer() function.
317  *
318  * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the
319  * cancellation actually completes, the transfer's callback function will
320  * be invoked, and the callback function should check the transfer status to
321  * determine that it was cancelled.
322  *
323  * Freeing the transfer after it has been cancelled but before cancellation
324  * has completed will result in undefined behaviour.
325  *
326  * When a transfer is cancelled, some of the data may have been transferred.
327  * libusb will communicate this to you in the transfer callback. Do not assume
328  * that no data was transferred.
329  *
330  * \section bulk_overflows Overflows on device-to-host bulk/interrupt endpoints
331  *
332  * If your device does not have predictable transfer sizes (or it misbehaves),
333  * your application may submit a request for data on an IN endpoint which is
334  * smaller than the data that the device wishes to send. In some circumstances
335  * this will cause an overflow, which is a nasty condition to deal with. See
336  * the \ref libusb_packetoverflow page for discussion.
337  *
338  * \section asyncctrl Considerations for control transfers
339  *
340  * The <tt>libusb_transfer</tt> structure is generic and hence does not
341  * include specific fields for the control-specific setup packet structure.
342  *
343  * In order to perform a control transfer, you must place the 8-byte setup
344  * packet at the start of the data buffer. To simplify this, you could
345  * cast the buffer pointer to type struct libusb_control_setup, or you can
346  * use the helper function libusb_fill_control_setup().
347  *
348  * The wLength field placed in the setup packet must be the length you would
349  * expect to be sent in the setup packet: the length of the payload that
350  * follows (or the expected maximum number of bytes to receive). However,
351  * the length field of the libusb_transfer object must be the length of
352  * the data buffer - i.e. it should be wLength <em>plus</em> the size of
353  * the setup packet (LIBUSB_CONTROL_SETUP_SIZE).
354  *
355  * If you use the helper functions, this is simplified for you:
356  * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the
357  * data you are sending/requesting.
358  * -# Call libusb_fill_control_setup() on the data buffer, using the transfer
359  * request size as the wLength value (i.e. do not include the extra space you
360  * allocated for the control setup).
361  * -# If this is a host-to-device transfer, place the data to be transferred
362  * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE.
363  * -# Call libusb_fill_control_transfer() to associate the data buffer with
364  * the transfer (and to set the remaining details such as callback and timeout).
365  *   - Note that there is no parameter to set the length field of the transfer.
366  *     The length is automatically inferred from the wLength field of the setup
367  *     packet.
368  * -# Submit the transfer.
369  *
370  * The multi-byte control setup fields (wValue, wIndex and wLength) must
371  * be given in little-endian byte order (the endianness of the USB bus).
372  * Endianness conversion is transparently handled by
373  * libusb_fill_control_setup() which is documented to accept host-endian
374  * values.
375  *
376  * Further considerations are needed when handling transfer completion in
377  * your callback function:
378  * - As you might expect, the setup packet will still be sitting at the start
379  * of the data buffer.
380  * - If this was a device-to-host transfer, the received data will be sitting
381  * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer.
382  * - The actual_length field of the transfer structure is relative to the
383  * wLength of the setup packet, rather than the size of the data buffer. So,
384  * if your wLength was 4, your transfer's <tt>length</tt> was 12, then you
385  * should expect an <tt>actual_length</tt> of 4 to indicate that the data was
386  * transferred in entirity.
387  *
388  * To simplify parsing of setup packets and obtaining the data from the
389  * correct offset, you may wish to use the libusb_control_transfer_get_data()
390  * and libusb_control_transfer_get_setup() functions within your transfer
391  * callback.
392  *
393  * Even though control endpoints do not halt, a completed control transfer
394  * may have a LIBUSB_TRANSFER_STALL status code. This indicates the control
395  * request was not supported.
396  *
397  * \section asyncintr Considerations for interrupt transfers
398  *
399  * All interrupt transfers are performed using the polling interval presented
400  * by the bInterval value of the endpoint descriptor.
401  *
402  * \section asynciso Considerations for isochronous transfers
403  *
404  * Isochronous transfers are more complicated than transfers to
405  * non-isochronous endpoints.
406  *
407  * To perform I/O to an isochronous endpoint, allocate the transfer by calling
408  * libusb_alloc_transfer() with an appropriate number of isochronous packets.
409  *
410  * During filling, set \ref libusb_transfer::type "type" to
411  * \ref libusb_transfer_type::LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
412  * "LIBUSB_TRANSFER_TYPE_ISOCHRONOUS", and set
413  * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than
414  * or equal to the number of packets you requested during allocation.
415  * libusb_alloc_transfer() does not set either of these fields for you, given
416  * that you might not even use the transfer on an isochronous endpoint.
417  *
418  * Next, populate the length field for the first num_iso_packets entries in
419  * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section
420  * 5.6.3 of the USB2 specifications describe how the maximum isochronous
421  * packet length is determined by the wMaxPacketSize field in the endpoint
422  * descriptor.
423  * Two functions can help you here:
424  *
425  * - libusb_get_max_iso_packet_size() is an easy way to determine the max
426  *   packet size for an isochronous endpoint. Note that the maximum packet
427  *   size is actually the maximum number of bytes that can be transmitted in
428  *   a single microframe, therefore this function multiplies the maximum number
429  *   of bytes per transaction by the number of transaction opportunities per
430  *   microframe.
431  * - libusb_set_iso_packet_lengths() assigns the same length to all packets
432  *   within a transfer, which is usually what you want.
433  *
434  * For outgoing transfers, you'll obviously fill the buffer and populate the
435  * packet descriptors in hope that all the data gets transferred. For incoming
436  * transfers, you must ensure the buffer has sufficient capacity for
437  * the situation where all packets transfer the full amount of requested data.
438  *
439  * Completion handling requires some extra consideration. The
440  * \ref libusb_transfer::actual_length "actual_length" field of the transfer
441  * is meaningless and should not be examined; instead you must refer to the
442  * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of
443  * each individual packet.
444  *
445  * The \ref libusb_transfer::status "status" field of the transfer is also a
446  * little misleading:
447  *  - If the packets were submitted and the isochronous data microframes
448  *    completed normally, status will have value
449  *    \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED
450  *    "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred
451  *    delays are not counted as transfer errors; the transfer.status field may
452  *    indicate COMPLETED even if some or all of the packets failed. Refer to
453  *    the \ref libusb_iso_packet_descriptor::status "status" field of each
454  *    individual packet to determine packet failures.
455  *  - The status field will have value
456  *    \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR
457  *    "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered.
458  *  - Other transfer status codes occur with normal behaviour.
459  *
460  * The data for each packet will be found at an offset into the buffer that
461  * can be calculated as if each prior packet completed in full. The
462  * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple()
463  * functions may help you here.
464  *
465  * <b>Note</b>: Some operating systems (e.g. Linux) may impose limits on the
466  * length of individual isochronous packets and/or the total length of the
467  * isochronous transfer. Such limits can be difficult for libusb to detect,
468  * so the library will simply try and submit the transfer as set up by you.
469  * If the transfer fails to submit because it is too large,
470  * libusb_submit_transfer() will return
471  * \ref libusb_error::LIBUSB_ERROR_INVALID_PARAM "LIBUSB_ERROR_INVALID_PARAM".
472  *
473  * \section asyncmem Memory caveats
474  *
475  * In most circumstances, it is not safe to use stack memory for transfer
476  * buffers. This is because the function that fired off the asynchronous
477  * transfer may return before libusb has finished using the buffer, and when
478  * the function returns it's stack gets destroyed. This is true for both
479  * host-to-device and device-to-host transfers.
480  *
481  * The only case in which it is safe to use stack memory is where you can
482  * guarantee that the function owning the stack space for the buffer does not
483  * return until after the transfer's callback function has completed. In every
484  * other case, you need to use heap memory instead.
485  *
486  * \section asyncflags Fine control
487  *
488  * Through using this asynchronous interface, you may find yourself repeating
489  * a few simple operations many times. You can apply a bitwise OR of certain
490  * flags to a transfer to simplify certain things:
491  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK
492  *   "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred
493  *   less than the requested amount of data being marked with status
494  *   \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR"
495  *   (they would normally be regarded as COMPLETED)
496  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
497  *   "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer
498  *   buffer when freeing the transfer.
499  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER
500  *   "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the
501  *   transfer after the transfer callback returns.
502  *
503  * \section asyncevent Event handling
504  *
505  * An asynchronous model requires that libusb perform work at various
506  * points in time - namely processing the results of previously-submitted
507  * transfers and invoking the user-supplied callback function.
508  *
509  * This gives rise to the libusb_handle_events() function which your
510  * application must call into when libusb has work do to. This gives libusb
511  * the opportunity to reap pending transfers, invoke callbacks, etc.
512  *
513  * There are 2 different approaches to dealing with libusb_handle_events:
514  *
515  * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated
516  *    thread.
517  * -# Integrate libusb with your application's main event loop. libusb
518  *    exposes a set of file descriptors which allow you to do this.
519  *
520  * The first approach has the big advantage that it will also work on Windows
521  * were libusb' poll API for select / poll integration is not available. So
522  * if you want to support Windows and use the async API, you must use this
523  * approach, see the \ref eventthread "Using an event handling thread" section
524  * below for details.
525  *
526  * If you prefer a single threaded approach with a single central event loop,
527  * see the \ref libusb_poll "polling and timing" section for how to integrate libusb
528  * into your application's main event loop.
529  *
530  * \section eventthread Using an event handling thread
531  *
532  * Lets begin with stating the obvious: If you're going to use a separate
533  * thread for libusb event handling, your callback functions MUST be
534  * threadsafe.
535  *
536  * Other then that doing event handling from a separate thread, is mostly
537  * simple. You can use an event thread function as follows:
538 \code
539 void *event_thread_func(void *ctx)
540 {
541     while (event_thread_run)
542         libusb_handle_events(ctx);
543
544     return NULL;
545 }
546 \endcode
547  *
548  * There is one caveat though, stopping this thread requires setting the
549  * event_thread_run variable to 0, and after that libusb_handle_events() needs
550  * to return control to event_thread_func. But unless some event happens,
551  * libusb_handle_events() will not return.
552  *
553  * There are 2 different ways of dealing with this, depending on if your
554  * application uses libusb' \ref libusb_hotplug "hotplug" support or not.
555  *
556  * Applications which do not use hotplug support, should not start the event
557  * thread until after their first call to libusb_open(), and should stop the
558  * thread when closing the last open device as follows:
559 \code
560 void my_close_handle(libusb_device_handle *dev_handle)
561 {
562     if (open_devs == 1)
563         event_thread_run = 0;
564
565     libusb_close(dev_handle); // This wakes up libusb_handle_events()
566
567     if (open_devs == 1)
568         pthread_join(event_thread);
569
570     open_devs--;
571 }
572 \endcode
573  *
574  * Applications using hotplug support should start the thread at program init,
575  * after having successfully called libusb_hotplug_register_callback(), and
576  * should stop the thread at program exit as follows:
577 \code
578 void my_libusb_exit(void)
579 {
580     event_thread_run = 0;
581     libusb_hotplug_deregister_callback(ctx, hotplug_cb_handle); // This wakes up libusb_handle_events()
582     pthread_join(event_thread);
583     libusb_exit(ctx);
584 }
585 \endcode
586  */
587
588 /**
589  * @defgroup libusb_poll Polling and timing
590  *
591  * This page documents libusb's functions for polling events and timing.
592  * These functions are only necessary for users of the
593  * \ref libusb_asyncio "asynchronous API". If you are only using the simpler
594  * \ref libusb_syncio "synchronous API" then you do not need to ever call these
595  * functions.
596  *
597  * The justification for the functionality described here has already been
598  * discussed in the \ref asyncevent "event handling" section of the
599  * asynchronous API documentation. In summary, libusb does not create internal
600  * threads for event processing and hence relies on your application calling
601  * into libusb at certain points in time so that pending events can be handled.
602  *
603  * Your main loop is probably already calling poll() or select() or a
604  * variant on a set of file descriptors for other event sources (e.g. keyboard
605  * button presses, mouse movements, network sockets, etc). You then add
606  * libusb's file descriptors to your poll()/select() calls, and when activity
607  * is detected on such descriptors you know it is time to call
608  * libusb_handle_events().
609  *
610  * There is one final event handling complication. libusb supports
611  * asynchronous transfers which time out after a specified time period.
612  *
613  * On some platforms a timerfd is used, so the timeout handling is just another
614  * fd, on other platforms this requires that libusb is called into at or after
615  * the timeout to handle it. So, in addition to considering libusb's file
616  * descriptors in your main event loop, you must also consider that libusb
617  * sometimes needs to be called into at fixed points in time even when there
618  * is no file descriptor activity, see \ref polltime details.
619  *
620  * In order to know precisely when libusb needs to be called into, libusb
621  * offers you a set of pollable file descriptors and information about when
622  * the next timeout expires.
623  *
624  * If you are using the asynchronous I/O API, you must take one of the two
625  * following options, otherwise your I/O will not complete.
626  *
627  * \section pollsimple The simple option
628  *
629  * If your application revolves solely around libusb and does not need to
630  * handle other event sources, you can have a program structure as follows:
631 \code
632 // initialize libusb
633 // find and open device
634 // maybe fire off some initial async I/O
635
636 while (user_has_not_requested_exit)
637         libusb_handle_events(ctx);
638
639 // clean up and exit
640 \endcode
641  *
642  * With such a simple main loop, you do not have to worry about managing
643  * sets of file descriptors or handling timeouts. libusb_handle_events() will
644  * handle those details internally.
645  *
646  * \section libusb_pollmain The more advanced option
647  *
648  * \note This functionality is currently only available on Unix-like platforms.
649  * On Windows, libusb_get_pollfds() simply returns NULL. Applications which
650  * want to support Windows are advised to use an \ref eventthread
651  * "event handling thread" instead.
652  *
653  * In more advanced applications, you will already have a main loop which
654  * is monitoring other event sources: network sockets, X11 events, mouse
655  * movements, etc. Through exposing a set of file descriptors, libusb is
656  * designed to cleanly integrate into such main loops.
657  *
658  * In addition to polling file descriptors for the other event sources, you
659  * take a set of file descriptors from libusb and monitor those too. When you
660  * detect activity on libusb's file descriptors, you call
661  * libusb_handle_events_timeout() in non-blocking mode.
662  *
663  * What's more, libusb may also need to handle events at specific moments in
664  * time. No file descriptor activity is generated at these times, so your
665  * own application needs to be continually aware of when the next one of these
666  * moments occurs (through calling libusb_get_next_timeout()), and then it
667  * needs to call libusb_handle_events_timeout() in non-blocking mode when
668  * these moments occur. This means that you need to adjust your
669  * poll()/select() timeout accordingly.
670  *
671  * libusb provides you with a set of file descriptors to poll and expects you
672  * to poll all of them, treating them as a single entity. The meaning of each
673  * file descriptor in the set is an internal implementation detail,
674  * platform-dependent and may vary from release to release. Don't try and
675  * interpret the meaning of the file descriptors, just do as libusb indicates,
676  * polling all of them at once.
677  *
678  * In pseudo-code, you want something that looks like:
679 \code
680 // initialise libusb
681
682 libusb_get_pollfds(ctx)
683 while (user has not requested application exit) {
684         libusb_get_next_timeout(ctx);
685         poll(on libusb file descriptors plus any other event sources of interest,
686                 using a timeout no larger than the value libusb just suggested)
687         if (poll() indicated activity on libusb file descriptors)
688                 libusb_handle_events_timeout(ctx, &zero_tv);
689         if (time has elapsed to or beyond the libusb timeout)
690                 libusb_handle_events_timeout(ctx, &zero_tv);
691         // handle events from other sources here
692 }
693
694 // clean up and exit
695 \endcode
696  *
697  * \subsection polltime Notes on time-based events
698  *
699  * The above complication with having to track time and call into libusb at
700  * specific moments is a bit of a headache. For maximum compatibility, you do
701  * need to write your main loop as above, but you may decide that you can
702  * restrict the supported platforms of your application and get away with
703  * a more simplistic scheme.
704  *
705  * These time-based event complications are \b not required on the following
706  * platforms:
707  *  - Darwin
708  *  - Linux, provided that the following version requirements are satisfied:
709  *   - Linux v2.6.27 or newer, compiled with timerfd support
710  *   - glibc v2.9 or newer
711  *   - libusb v1.0.5 or newer
712  *
713  * Under these configurations, libusb_get_next_timeout() will \em always return
714  * 0, so your main loop can be simplified to:
715 \code
716 // initialise libusb
717
718 libusb_get_pollfds(ctx)
719 while (user has not requested application exit) {
720         poll(on libusb file descriptors plus any other event sources of interest,
721                 using any timeout that you like)
722         if (poll() indicated activity on libusb file descriptors)
723                 libusb_handle_events_timeout(ctx, &zero_tv);
724         // handle events from other sources here
725 }
726
727 // clean up and exit
728 \endcode
729  *
730  * Do remember that if you simplify your main loop to the above, you will
731  * lose compatibility with some platforms (including legacy Linux platforms,
732  * and <em>any future platforms supported by libusb which may have time-based
733  * event requirements</em>). The resultant problems will likely appear as
734  * strange bugs in your application.
735  *
736  * You can use the libusb_pollfds_handle_timeouts() function to do a runtime
737  * check to see if it is safe to ignore the time-based event complications.
738  * If your application has taken the shortcut of ignoring libusb's next timeout
739  * in your main loop, then you are advised to check the return value of
740  * libusb_pollfds_handle_timeouts() during application startup, and to abort
741  * if the platform does suffer from these timing complications.
742  *
743  * \subsection fdsetchange Changes in the file descriptor set
744  *
745  * The set of file descriptors that libusb uses as event sources may change
746  * during the life of your application. Rather than having to repeatedly
747  * call libusb_get_pollfds(), you can set up notification functions for when
748  * the file descriptor set changes using libusb_set_pollfd_notifiers().
749  *
750  * \subsection mtissues Multi-threaded considerations
751  *
752  * Unfortunately, the situation is complicated further when multiple threads
753  * come into play. If two threads are monitoring the same file descriptors,
754  * the fact that only one thread will be woken up when an event occurs causes
755  * some headaches.
756  *
757  * The events lock, event waiters lock, and libusb_handle_events_locked()
758  * entities are added to solve these problems. You do not need to be concerned
759  * with these entities otherwise.
760  *
761  * See the extra documentation: \ref libusb_mtasync
762  */
763
764 /** \page libusb_mtasync Multi-threaded applications and asynchronous I/O
765  *
766  * libusb is a thread-safe library, but extra considerations must be applied
767  * to applications which interact with libusb from multiple threads.
768  *
769  * The underlying issue that must be addressed is that all libusb I/O
770  * revolves around monitoring file descriptors through the poll()/select()
771  * system calls. This is directly exposed at the
772  * \ref libusb_asyncio "asynchronous interface" but it is important to note that the
773  * \ref libusb_syncio "synchronous interface" is implemented on top of the
774  * asynchonrous interface, therefore the same considerations apply.
775  *
776  * The issue is that if two or more threads are concurrently calling poll()
777  * or select() on libusb's file descriptors then only one of those threads
778  * will be woken up when an event arrives. The others will be completely
779  * oblivious that anything has happened.
780  *
781  * Consider the following pseudo-code, which submits an asynchronous transfer
782  * then waits for its completion. This style is one way you could implement a
783  * synchronous interface on top of the asynchronous interface (and libusb
784  * does something similar, albeit more advanced due to the complications
785  * explained on this page).
786  *
787 \code
788 void cb(struct libusb_transfer *transfer)
789 {
790         int *completed = transfer->user_data;
791         *completed = 1;
792 }
793
794 void myfunc() {
795         struct libusb_transfer *transfer;
796         unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE] __attribute__ ((aligned (2)));
797         int completed = 0;
798
799         transfer = libusb_alloc_transfer(0);
800         libusb_fill_control_setup(buffer,
801                 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x04, 0x01, 0, 0);
802         libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000);
803         libusb_submit_transfer(transfer);
804
805         while (!completed) {
806                 poll(libusb file descriptors, 120*1000);
807                 if (poll indicates activity)
808                         libusb_handle_events_timeout(ctx, &zero_tv);
809         }
810         printf("completed!");
811         // other code here
812 }
813 \endcode
814  *
815  * Here we are <em>serializing</em> completion of an asynchronous event
816  * against a condition - the condition being completion of a specific transfer.
817  * The poll() loop has a long timeout to minimize CPU usage during situations
818  * when nothing is happening (it could reasonably be unlimited).
819  *
820  * If this is the only thread that is polling libusb's file descriptors, there
821  * is no problem: there is no danger that another thread will swallow up the
822  * event that we are interested in. On the other hand, if there is another
823  * thread polling the same descriptors, there is a chance that it will receive
824  * the event that we were interested in. In this situation, <tt>myfunc()</tt>
825  * will only realise that the transfer has completed on the next iteration of
826  * the loop, <em>up to 120 seconds later.</em> Clearly a two-minute delay is
827  * undesirable, and don't even think about using short timeouts to circumvent
828  * this issue!
829  *
830  * The solution here is to ensure that no two threads are ever polling the
831  * file descriptors at the same time. A naive implementation of this would
832  * impact the capabilities of the library, so libusb offers the scheme
833  * documented below to ensure no loss of functionality.
834  *
835  * Before we go any further, it is worth mentioning that all libusb-wrapped
836  * event handling procedures fully adhere to the scheme documented below.
837  * This includes libusb_handle_events() and its variants, and all the
838  * synchronous I/O functions - libusb hides this headache from you.
839  *
840  * \section Using libusb_handle_events() from multiple threads
841  *
842  * Even when only using libusb_handle_events() and synchronous I/O functions,
843  * you can still have a race condition. You might be tempted to solve the
844  * above with libusb_handle_events() like so:
845  *
846 \code
847         libusb_submit_transfer(transfer);
848
849         while (!completed) {
850                 libusb_handle_events(ctx);
851         }
852         printf("completed!");
853 \endcode
854  *
855  * This however has a race between the checking of completed and
856  * libusb_handle_events() acquiring the events lock, so another thread
857  * could have completed the transfer, resulting in this thread hanging
858  * until either a timeout or another event occurs. See also commit
859  * 6696512aade99bb15d6792af90ae329af270eba6 which fixes this in the
860  * synchronous API implementation of libusb.
861  *
862  * Fixing this race requires checking the variable completed only after
863  * taking the event lock, which defeats the concept of just calling
864  * libusb_handle_events() without worrying about locking. This is why
865  * libusb-1.0.9 introduces the new libusb_handle_events_timeout_completed()
866  * and libusb_handle_events_completed() functions, which handles doing the
867  * completion check for you after they have acquired the lock:
868  *
869 \code
870         libusb_submit_transfer(transfer);
871
872         while (!completed) {
873                 libusb_handle_events_completed(ctx, &completed);
874         }
875         printf("completed!");
876 \endcode
877  *
878  * This nicely fixes the race in our example. Note that if all you want to
879  * do is submit a single transfer and wait for its completion, then using
880  * one of the synchronous I/O functions is much easier.
881  *
882  * \section eventlock The events lock
883  *
884  * The problem is when we consider the fact that libusb exposes file
885  * descriptors to allow for you to integrate asynchronous USB I/O into
886  * existing main loops, effectively allowing you to do some work behind
887  * libusb's back. If you do take libusb's file descriptors and pass them to
888  * poll()/select() yourself, you need to be aware of the associated issues.
889  *
890  * The first concept to be introduced is the events lock. The events lock
891  * is used to serialize threads that want to handle events, such that only
892  * one thread is handling events at any one time.
893  *
894  * You must take the events lock before polling libusb file descriptors,
895  * using libusb_lock_events(). You must release the lock as soon as you have
896  * aborted your poll()/select() loop, using libusb_unlock_events().
897  *
898  * \section threadwait Letting other threads do the work for you
899  *
900  * Although the events lock is a critical part of the solution, it is not
901  * enough on it's own. You might wonder if the following is sufficient...
902 \code
903         libusb_lock_events(ctx);
904         while (!completed) {
905                 poll(libusb file descriptors, 120*1000);
906                 if (poll indicates activity)
907                         libusb_handle_events_timeout(ctx, &zero_tv);
908         }
909         libusb_unlock_events(ctx);
910 \endcode
911  * ...and the answer is that it is not. This is because the transfer in the
912  * code shown above may take a long time (say 30 seconds) to complete, and
913  * the lock is not released until the transfer is completed.
914  *
915  * Another thread with similar code that wants to do event handling may be
916  * working with a transfer that completes after a few milliseconds. Despite
917  * having such a quick completion time, the other thread cannot check that
918  * status of its transfer until the code above has finished (30 seconds later)
919  * due to contention on the lock.
920  *
921  * To solve this, libusb offers you a mechanism to determine when another
922  * thread is handling events. It also offers a mechanism to block your thread
923  * until the event handling thread has completed an event (and this mechanism
924  * does not involve polling of file descriptors).
925  *
926  * After determining that another thread is currently handling events, you
927  * obtain the <em>event waiters</em> lock using libusb_lock_event_waiters().
928  * You then re-check that some other thread is still handling events, and if
929  * so, you call libusb_wait_for_event().
930  *
931  * libusb_wait_for_event() puts your application to sleep until an event
932  * occurs, or until a thread releases the events lock. When either of these
933  * things happen, your thread is woken up, and should re-check the condition
934  * it was waiting on. It should also re-check that another thread is handling
935  * events, and if not, it should start handling events itself.
936  *
937  * This looks like the following, as pseudo-code:
938 \code
939 retry:
940 if (libusb_try_lock_events(ctx) == 0) {
941         // we obtained the event lock: do our own event handling
942         while (!completed) {
943                 if (!libusb_event_handling_ok(ctx)) {
944                         libusb_unlock_events(ctx);
945                         goto retry;
946                 }
947                 poll(libusb file descriptors, 120*1000);
948                 if (poll indicates activity)
949                         libusb_handle_events_locked(ctx, 0);
950         }
951         libusb_unlock_events(ctx);
952 } else {
953         // another thread is doing event handling. wait for it to signal us that
954         // an event has completed
955         libusb_lock_event_waiters(ctx);
956
957         while (!completed) {
958                 // now that we have the event waiters lock, double check that another
959                 // thread is still handling events for us. (it may have ceased handling
960                 // events in the time it took us to reach this point)
961                 if (!libusb_event_handler_active(ctx)) {
962                         // whoever was handling events is no longer doing so, try again
963                         libusb_unlock_event_waiters(ctx);
964                         goto retry;
965                 }
966
967                 libusb_wait_for_event(ctx, NULL);
968         }
969         libusb_unlock_event_waiters(ctx);
970 }
971 printf("completed!\n");
972 \endcode
973  *
974  * A naive look at the above code may suggest that this can only support
975  * one event waiter (hence a total of 2 competing threads, the other doing
976  * event handling), because the event waiter seems to have taken the event
977  * waiters lock while waiting for an event. However, the system does support
978  * multiple event waiters, because libusb_wait_for_event() actually drops
979  * the lock while waiting, and reaquires it before continuing.
980  *
981  * We have now implemented code which can dynamically handle situations where
982  * nobody is handling events (so we should do it ourselves), and it can also
983  * handle situations where another thread is doing event handling (so we can
984  * piggyback onto them). It is also equipped to handle a combination of
985  * the two, for example, another thread is doing event handling, but for
986  * whatever reason it stops doing so before our condition is met, so we take
987  * over the event handling.
988  *
989  * Four functions were introduced in the above pseudo-code. Their importance
990  * should be apparent from the code shown above.
991  * -# libusb_try_lock_events() is a non-blocking function which attempts
992  *    to acquire the events lock but returns a failure code if it is contended.
993  * -# libusb_event_handling_ok() checks that libusb is still happy for your
994  *    thread to be performing event handling. Sometimes, libusb needs to
995  *    interrupt the event handler, and this is how you can check if you have
996  *    been interrupted. If this function returns 0, the correct behaviour is
997  *    for you to give up the event handling lock, and then to repeat the cycle.
998  *    The following libusb_try_lock_events() will fail, so you will become an
999  *    events waiter. For more information on this, read \ref fullstory below.
1000  * -# libusb_handle_events_locked() is a variant of
1001  *    libusb_handle_events_timeout() that you can call while holding the
1002  *    events lock. libusb_handle_events_timeout() itself implements similar
1003  *    logic to the above, so be sure not to call it when you are
1004  *    "working behind libusb's back", as is the case here.
1005  * -# libusb_event_handler_active() determines if someone is currently
1006  *    holding the events lock
1007  *
1008  * You might be wondering why there is no function to wake up all threads
1009  * blocked on libusb_wait_for_event(). This is because libusb can do this
1010  * internally: it will wake up all such threads when someone calls
1011  * libusb_unlock_events() or when a transfer completes (at the point after its
1012  * callback has returned).
1013  *
1014  * \subsection fullstory The full story
1015  *
1016  * The above explanation should be enough to get you going, but if you're
1017  * really thinking through the issues then you may be left with some more
1018  * questions regarding libusb's internals. If you're curious, read on, and if
1019  * not, skip to the next section to avoid confusing yourself!
1020  *
1021  * The immediate question that may spring to mind is: what if one thread
1022  * modifies the set of file descriptors that need to be polled while another
1023  * thread is doing event handling?
1024  *
1025  * There are 2 situations in which this may happen.
1026  * -# libusb_open() will add another file descriptor to the poll set,
1027  *    therefore it is desirable to interrupt the event handler so that it
1028  *    restarts, picking up the new descriptor.
1029  * -# libusb_close() will remove a file descriptor from the poll set. There
1030  *    are all kinds of race conditions that could arise here, so it is
1031  *    important that nobody is doing event handling at this time.
1032  *
1033  * libusb handles these issues internally, so application developers do not
1034  * have to stop their event handlers while opening/closing devices. Here's how
1035  * it works, focusing on the libusb_close() situation first:
1036  *
1037  * -# During initialization, libusb opens an internal pipe, and it adds the read
1038  *    end of this pipe to the set of file descriptors to be polled.
1039  * -# During libusb_close(), libusb writes some dummy data on this event pipe.
1040  *    This immediately interrupts the event handler. libusb also records
1041  *    internally that it is trying to interrupt event handlers for this
1042  *    high-priority event.
1043  * -# At this point, some of the functions described above start behaving
1044  *    differently:
1045  *   - libusb_event_handling_ok() starts returning 1, indicating that it is NOT
1046  *     OK for event handling to continue.
1047  *   - libusb_try_lock_events() starts returning 1, indicating that another
1048  *     thread holds the event handling lock, even if the lock is uncontended.
1049  *   - libusb_event_handler_active() starts returning 1, indicating that
1050  *     another thread is doing event handling, even if that is not true.
1051  * -# The above changes in behaviour result in the event handler stopping and
1052  *    giving up the events lock very quickly, giving the high-priority
1053  *    libusb_close() operation a "free ride" to acquire the events lock. All
1054  *    threads that are competing to do event handling become event waiters.
1055  * -# With the events lock held inside libusb_close(), libusb can safely remove
1056  *    a file descriptor from the poll set, in the safety of knowledge that
1057  *    nobody is polling those descriptors or trying to access the poll set.
1058  * -# After obtaining the events lock, the close operation completes very
1059  *    quickly (usually a matter of milliseconds) and then immediately releases
1060  *    the events lock.
1061  * -# At the same time, the behaviour of libusb_event_handling_ok() and friends
1062  *    reverts to the original, documented behaviour.
1063  * -# The release of the events lock causes the threads that are waiting for
1064  *    events to be woken up and to start competing to become event handlers
1065  *    again. One of them will succeed; it will then re-obtain the list of poll
1066  *    descriptors, and USB I/O will then continue as normal.
1067  *
1068  * libusb_open() is similar, and is actually a more simplistic case. Upon a
1069  * call to libusb_open():
1070  *
1071  * -# The device is opened and a file descriptor is added to the poll set.
1072  * -# libusb sends some dummy data on the event pipe, and records that it
1073  *    is trying to modify the poll descriptor set.
1074  * -# The event handler is interrupted, and the same behaviour change as for
1075  *    libusb_close() takes effect, causing all event handling threads to become
1076  *    event waiters.
1077  * -# The libusb_open() implementation takes its free ride to the events lock.
1078  * -# Happy that it has successfully paused the events handler, libusb_open()
1079  *    releases the events lock.
1080  * -# The event waiter threads are all woken up and compete to become event
1081  *    handlers again. The one that succeeds will obtain the list of poll
1082  *    descriptors again, which will include the addition of the new device.
1083  *
1084  * \subsection concl Closing remarks
1085  *
1086  * The above may seem a little complicated, but hopefully I have made it clear
1087  * why such complications are necessary. Also, do not forget that this only
1088  * applies to applications that take libusb's file descriptors and integrate
1089  * them into their own polling loops.
1090  *
1091  * You may decide that it is OK for your multi-threaded application to ignore
1092  * some of the rules and locks detailed above, because you don't think that
1093  * two threads can ever be polling the descriptors at the same time. If that
1094  * is the case, then that's good news for you because you don't have to worry.
1095  * But be careful here; remember that the synchronous I/O functions do event
1096  * handling internally. If you have one thread doing event handling in a loop
1097  * (without implementing the rules and locking semantics documented above)
1098  * and another trying to send a synchronous USB transfer, you will end up with
1099  * two threads monitoring the same descriptors, and the above-described
1100  * undesirable behaviour occurring. The solution is for your polling thread to
1101  * play by the rules; the synchronous I/O functions do so, and this will result
1102  * in them getting along in perfect harmony.
1103  *
1104  * If you do have a dedicated thread doing event handling, it is perfectly
1105  * legal for it to take the event handling lock for long periods of time. Any
1106  * synchronous I/O functions you call from other threads will transparently
1107  * fall back to the "event waiters" mechanism detailed above. The only
1108  * consideration that your event handling thread must apply is the one related
1109  * to libusb_event_handling_ok(): you must call this before every poll(), and
1110  * give up the events lock if instructed.
1111  */
1112
1113 int usbi_io_init(struct libusb_context *ctx)
1114 {
1115         int r;
1116
1117         usbi_mutex_init(&ctx->flying_transfers_lock);
1118         usbi_mutex_init(&ctx->events_lock);
1119         usbi_mutex_init(&ctx->event_waiters_lock);
1120         usbi_cond_init(&ctx->event_waiters_cond);
1121         usbi_mutex_init(&ctx->event_data_lock);
1122         usbi_tls_key_create(&ctx->event_handling_key);
1123         list_init(&ctx->flying_transfers);
1124         list_init(&ctx->ipollfds);
1125         list_init(&ctx->removed_ipollfds);
1126         list_init(&ctx->hotplug_msgs);
1127         list_init(&ctx->completed_transfers);
1128
1129         /* FIXME should use an eventfd on kernels that support it */
1130         r = usbi_pipe(ctx->event_pipe);
1131         if (r < 0) {
1132                 r = LIBUSB_ERROR_OTHER;
1133                 goto err;
1134         }
1135
1136         r = usbi_add_pollfd(ctx, ctx->event_pipe[0], POLLIN);
1137         if (r < 0)
1138                 goto err_close_pipe;
1139
1140 #ifdef HAVE_TIMERFD
1141         ctx->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
1142         if (ctx->timerfd >= 0) {
1143                 usbi_dbg("using timerfd for timeouts");
1144                 r = usbi_add_pollfd(ctx, ctx->timerfd, POLLIN);
1145                 if (r < 0)
1146                         goto err_close_timerfd;
1147         } else {
1148                 usbi_dbg("timerfd not available, errno=%d", errno);
1149         }
1150 #endif
1151
1152         return 0;
1153
1154 #ifdef HAVE_TIMERFD
1155 err_close_timerfd:
1156         close(ctx->timerfd);
1157         usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
1158 #endif
1159 err_close_pipe:
1160         usbi_close(ctx->event_pipe[0]);
1161         usbi_close(ctx->event_pipe[1]);
1162 err:
1163         usbi_mutex_destroy(&ctx->flying_transfers_lock);
1164         usbi_mutex_destroy(&ctx->events_lock);
1165         usbi_mutex_destroy(&ctx->event_waiters_lock);
1166         usbi_cond_destroy(&ctx->event_waiters_cond);
1167         usbi_mutex_destroy(&ctx->event_data_lock);
1168         usbi_tls_key_delete(ctx->event_handling_key);
1169         return r;
1170 }
1171
1172 static void cleanup_removed_pollfds(struct libusb_context *ctx)
1173 {
1174         struct usbi_pollfd *ipollfd, *tmp;
1175         list_for_each_entry_safe(ipollfd, tmp, &ctx->removed_ipollfds, list, struct usbi_pollfd) {
1176                 list_del(&ipollfd->list);
1177                 free(ipollfd);
1178         }
1179 }
1180
1181 void usbi_io_exit(struct libusb_context *ctx)
1182 {
1183         usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
1184         usbi_close(ctx->event_pipe[0]);
1185         usbi_close(ctx->event_pipe[1]);
1186 #ifdef HAVE_TIMERFD
1187         if (usbi_using_timerfd(ctx)) {
1188                 usbi_remove_pollfd(ctx, ctx->timerfd);
1189                 close(ctx->timerfd);
1190         }
1191 #endif
1192         usbi_mutex_destroy(&ctx->flying_transfers_lock);
1193         usbi_mutex_destroy(&ctx->events_lock);
1194         usbi_mutex_destroy(&ctx->event_waiters_lock);
1195         usbi_cond_destroy(&ctx->event_waiters_cond);
1196         usbi_mutex_destroy(&ctx->event_data_lock);
1197         usbi_tls_key_delete(ctx->event_handling_key);
1198         free(ctx->pollfds);
1199         cleanup_removed_pollfds(ctx);
1200 }
1201
1202 static int calculate_timeout(struct usbi_transfer *itransfer)
1203 {
1204         int r;
1205         unsigned int timeout =
1206                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)->timeout;
1207
1208         if (!timeout) {
1209                 TIMESPEC_CLEAR(&itransfer->timeout);
1210                 return 0;
1211         }
1212
1213         r = usbi_clock_gettime(USBI_CLOCK_MONOTONIC, &itransfer->timeout);
1214         if (r < 0) {
1215                 usbi_err(ITRANSFER_CTX(itransfer),
1216                         "failed to read monotonic clock, errno=%d", errno);
1217                 return r;
1218         }
1219
1220         itransfer->timeout.tv_sec += timeout / 1000U;
1221         itransfer->timeout.tv_nsec += (timeout % 1000U) * 1000000L;
1222         if (itransfer->timeout.tv_nsec >= 1000000000L) {
1223                 ++itransfer->timeout.tv_sec;
1224                 itransfer->timeout.tv_nsec -= 1000000000L;
1225         }
1226
1227         return 0;
1228 }
1229
1230 /** \ingroup libusb_asyncio
1231  * Allocate a libusb transfer with a specified number of isochronous packet
1232  * descriptors. The returned transfer is pre-initialized for you. When the new
1233  * transfer is no longer needed, it should be freed with
1234  * libusb_free_transfer().
1235  *
1236  * Transfers intended for non-isochronous endpoints (e.g. control, bulk,
1237  * interrupt) should specify an iso_packets count of zero.
1238  *
1239  * For transfers intended for isochronous endpoints, specify an appropriate
1240  * number of packet descriptors to be allocated as part of the transfer.
1241  * The returned transfer is not specially initialized for isochronous I/O;
1242  * you are still required to set the
1243  * \ref libusb_transfer::num_iso_packets "num_iso_packets" and
1244  * \ref libusb_transfer::type "type" fields accordingly.
1245  *
1246  * It is safe to allocate a transfer with some isochronous packets and then
1247  * use it on a non-isochronous endpoint. If you do this, ensure that at time
1248  * of submission, num_iso_packets is 0 and that type is set appropriately.
1249  *
1250  * \param iso_packets number of isochronous packet descriptors to allocate. Must be non-negative.
1251  * \returns a newly allocated transfer, or NULL on error
1252  */
1253 DEFAULT_VISIBILITY
1254 struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(
1255         int iso_packets)
1256 {
1257         size_t priv_size;
1258         size_t alloc_size;
1259         unsigned char *ptr;
1260         struct usbi_transfer *itransfer;
1261         struct libusb_transfer *transfer;
1262
1263         assert(iso_packets >= 0);
1264         if (iso_packets < 0)
1265                 return NULL;
1266
1267         priv_size = PTR_ALIGN(usbi_backend.transfer_priv_size);
1268         alloc_size = priv_size
1269                 + sizeof(struct usbi_transfer)
1270                 + (sizeof(struct libusb_iso_packet_descriptor) * (size_t)iso_packets);
1271         ptr = calloc(1, alloc_size);
1272         if (!ptr)
1273                 return NULL;
1274
1275         itransfer = (struct usbi_transfer *)(ptr + priv_size);
1276         itransfer->num_iso_packets = iso_packets;
1277         itransfer->priv = ptr;
1278         usbi_mutex_init(&itransfer->lock);
1279         transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1280         usbi_dbg("transfer %p", transfer);
1281         return transfer;
1282 }
1283
1284 /** \ingroup libusb_asyncio
1285  * Free a transfer structure. This should be called for all transfers
1286  * allocated with libusb_alloc_transfer().
1287  *
1288  * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
1289  * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is
1290  * non-NULL, this function will also free the transfer buffer using the
1291  * standard system memory allocator (e.g. free()).
1292  *
1293  * It is legal to call this function with a NULL transfer. In this case,
1294  * the function will simply return safely.
1295  *
1296  * It is not legal to free an active transfer (one which has been submitted
1297  * and has not yet completed).
1298  *
1299  * \param transfer the transfer to free
1300  */
1301 void API_EXPORTED libusb_free_transfer(struct libusb_transfer *transfer)
1302 {
1303         struct usbi_transfer *itransfer;
1304         size_t priv_size;
1305         unsigned char *ptr;
1306
1307         if (!transfer)
1308                 return;
1309
1310         usbi_dbg("transfer %p", transfer);
1311         if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER)
1312                 free(transfer->buffer);
1313
1314         itransfer = LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1315         usbi_mutex_destroy(&itransfer->lock);
1316
1317         priv_size = PTR_ALIGN(usbi_backend.transfer_priv_size);
1318         ptr = (unsigned char *)itransfer - priv_size;
1319         assert(ptr == itransfer->priv);
1320         free(ptr);
1321 }
1322
1323 #ifdef HAVE_TIMERFD
1324 static int disarm_timerfd(struct libusb_context *ctx)
1325 {
1326         const struct itimerspec disarm_timer = { { 0, 0 }, { 0, 0 } };
1327         int r;
1328
1329         usbi_dbg(" ");
1330         r = timerfd_settime(ctx->timerfd, 0, &disarm_timer, NULL);
1331         if (r < 0)
1332                 return LIBUSB_ERROR_OTHER;
1333         else
1334                 return 0;
1335 }
1336
1337 /* iterates through the flying transfers, and rearms the timerfd based on the
1338  * next upcoming timeout.
1339  * must be called with flying_list locked.
1340  * returns 0 on success or a LIBUSB_ERROR code on failure.
1341  */
1342 static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
1343 {
1344         struct usbi_transfer *itransfer;
1345
1346         list_for_each_entry(itransfer, &ctx->flying_transfers, list, struct usbi_transfer) {
1347                 struct timespec *cur_ts = &itransfer->timeout;
1348
1349                 /* if we've reached transfers of infinite timeout, then we have no
1350                  * arming to do */
1351                 if (!TIMESPEC_IS_SET(cur_ts))
1352                         goto disarm;
1353
1354                 /* act on first transfer that has not already been handled */
1355                 if (!(itransfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))) {
1356                         int r;
1357                         const struct itimerspec it = { {0, 0},
1358                                 { cur_ts->tv_sec, cur_ts->tv_nsec } };
1359                         usbi_dbg("next timeout originally %ums", USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)->timeout);
1360                         r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
1361                         if (r < 0)
1362                                 return LIBUSB_ERROR_OTHER;
1363                         return 0;
1364                 }
1365         }
1366
1367 disarm:
1368         return disarm_timerfd(ctx);
1369 }
1370 #else
1371 static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
1372 {
1373         UNUSED(ctx);
1374         return 0;
1375 }
1376 #endif
1377
1378 /* add a transfer to the (timeout-sorted) active transfers list.
1379  * This function will return non 0 if fails to update the timer,
1380  * in which case the transfer is *not* on the flying_transfers list. */
1381 static int add_to_flying_list(struct usbi_transfer *itransfer)
1382 {
1383         struct usbi_transfer *cur;
1384         struct timespec *timeout = &itransfer->timeout;
1385         struct libusb_context *ctx = ITRANSFER_CTX(itransfer);
1386         int r;
1387         int first = 1;
1388
1389         r = calculate_timeout(itransfer);
1390         if (r)
1391                 return r;
1392
1393         /* if we have no other flying transfers, start the list with this one */
1394         if (list_empty(&ctx->flying_transfers)) {
1395                 list_add(&itransfer->list, &ctx->flying_transfers);
1396                 goto out;
1397         }
1398
1399         /* if we have infinite timeout, append to end of list */
1400         if (!TIMESPEC_IS_SET(timeout)) {
1401                 list_add_tail(&itransfer->list, &ctx->flying_transfers);
1402                 /* first is irrelevant in this case */
1403                 goto out;
1404         }
1405
1406         /* otherwise, find appropriate place in list */
1407         list_for_each_entry(cur, &ctx->flying_transfers, list, struct usbi_transfer) {
1408                 /* find first timeout that occurs after the transfer in question */
1409                 struct timespec *cur_ts = &cur->timeout;
1410
1411                 if (!TIMESPEC_IS_SET(cur_ts) || TIMESPEC_CMP(cur_ts, timeout, >)) {
1412                         list_add_tail(&itransfer->list, &cur->list);
1413                         goto out;
1414                 }
1415                 first = 0;
1416         }
1417         /* first is 0 at this stage (list not empty) */
1418
1419         /* otherwise we need to be inserted at the end */
1420         list_add_tail(&itransfer->list, &ctx->flying_transfers);
1421 out:
1422 #ifdef HAVE_TIMERFD
1423         if (first && usbi_using_timerfd(ctx) && TIMESPEC_IS_SET(timeout)) {
1424                 /* if this transfer has the lowest timeout of all active transfers,
1425                  * rearm the timerfd with this transfer's timeout */
1426                 const struct itimerspec it = { {0, 0},
1427                         { timeout->tv_sec, timeout->tv_nsec } };
1428                 usbi_dbg("arm timerfd for timeout in %ums (first in line)",
1429                         USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)->timeout);
1430                 r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
1431                 if (r < 0) {
1432                         usbi_warn(ctx, "failed to arm first timerfd, errno=%d", errno);
1433                         r = LIBUSB_ERROR_OTHER;
1434                 }
1435         }
1436 #else
1437         UNUSED(first);
1438 #endif
1439
1440         if (r)
1441                 list_del(&itransfer->list);
1442
1443         return r;
1444 }
1445
1446 /* remove a transfer from the active transfers list.
1447  * This function will *always* remove the transfer from the
1448  * flying_transfers list. It will return a LIBUSB_ERROR code
1449  * if it fails to update the timer for the next timeout. */
1450 static int remove_from_flying_list(struct usbi_transfer *itransfer)
1451 {
1452         struct libusb_context *ctx = ITRANSFER_CTX(itransfer);
1453         int rearm_timerfd;
1454         int r = 0;
1455
1456         usbi_mutex_lock(&ctx->flying_transfers_lock);
1457         rearm_timerfd = (TIMESPEC_IS_SET(&itransfer->timeout) &&
1458                 list_first_entry(&ctx->flying_transfers, struct usbi_transfer, list) == itransfer);
1459         list_del(&itransfer->list);
1460         if (usbi_using_timerfd(ctx) && rearm_timerfd)
1461                 r = arm_timerfd_for_next_timeout(ctx);
1462         usbi_mutex_unlock(&ctx->flying_transfers_lock);
1463
1464         return r;
1465 }
1466
1467 /** \ingroup libusb_asyncio
1468  * Submit a transfer. This function will fire off the USB transfer and then
1469  * return immediately.
1470  *
1471  * \param transfer the transfer to submit
1472  * \returns 0 on success
1473  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1474  * \returns LIBUSB_ERROR_BUSY if the transfer has already been submitted.
1475  * \returns LIBUSB_ERROR_NOT_SUPPORTED if the transfer flags are not supported
1476  * by the operating system.
1477  * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
1478  * the operating system and/or hardware can support
1479  * \returns another LIBUSB_ERROR code on other failure
1480  */
1481 int API_EXPORTED libusb_submit_transfer(struct libusb_transfer *transfer)
1482 {
1483         struct usbi_transfer *itransfer =
1484                 LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1485         struct libusb_context *ctx = TRANSFER_CTX(transfer);
1486         int r;
1487
1488         usbi_dbg("transfer %p", transfer);
1489
1490         /*
1491          * Important note on locking, this function takes / releases locks
1492          * in the following order:
1493          *  take flying_transfers_lock
1494          *  take itransfer->lock
1495          *  clear transfer
1496          *  add to flying_transfers list
1497          *  release flying_transfers_lock
1498          *  submit transfer
1499          *  release itransfer->lock
1500          *  if submit failed:
1501          *   take flying_transfers_lock
1502          *   remove from flying_transfers list
1503          *   release flying_transfers_lock
1504          *
1505          * Note that it takes locks in the order a-b and then releases them
1506          * in the same order a-b. This is somewhat unusual but not wrong,
1507          * release order is not important as long as *all* locks are released
1508          * before re-acquiring any locks.
1509          *
1510          * This means that the ordering of first releasing itransfer->lock
1511          * and then re-acquiring the flying_transfers_list on error is
1512          * important and must not be changed!
1513          *
1514          * This is done this way because when we take both locks we must always
1515          * take flying_transfers_lock first to avoid ab-ba style deadlocks with
1516          * the timeout handling and usbi_handle_disconnect paths.
1517          *
1518          * And we cannot release itransfer->lock before the submission is
1519          * complete otherwise timeout handling for transfers with short
1520          * timeouts may run before submission.
1521          */
1522         usbi_mutex_lock(&ctx->flying_transfers_lock);
1523         usbi_mutex_lock(&itransfer->lock);
1524         if (itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT) {
1525                 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1526                 usbi_mutex_unlock(&itransfer->lock);
1527                 return LIBUSB_ERROR_BUSY;
1528         }
1529         itransfer->transferred = 0;
1530         itransfer->state_flags = 0;
1531         itransfer->timeout_flags = 0;
1532         r = add_to_flying_list(itransfer);
1533         if (r) {
1534                 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1535                 usbi_mutex_unlock(&itransfer->lock);
1536                 return r;
1537         }
1538         /*
1539          * We must release the flying transfers lock here, because with
1540          * some backends the submit_transfer method is synchroneous.
1541          */
1542         usbi_mutex_unlock(&ctx->flying_transfers_lock);
1543
1544         r = usbi_backend.submit_transfer(itransfer);
1545         if (r == LIBUSB_SUCCESS) {
1546                 itransfer->state_flags |= USBI_TRANSFER_IN_FLIGHT;
1547                 /* keep a reference to this device */
1548                 libusb_ref_device(transfer->dev_handle->dev);
1549         }
1550         usbi_mutex_unlock(&itransfer->lock);
1551
1552         if (r != LIBUSB_SUCCESS)
1553                 remove_from_flying_list(itransfer);
1554
1555         return r;
1556 }
1557
1558 /** \ingroup libusb_asyncio
1559  * Asynchronously cancel a previously submitted transfer.
1560  * This function returns immediately, but this does not indicate cancellation
1561  * is complete. Your callback function will be invoked at some later time
1562  * with a transfer status of
1563  * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED
1564  * "LIBUSB_TRANSFER_CANCELLED."
1565  *
1566  * \param transfer the transfer to cancel
1567  * \returns 0 on success
1568  * \returns LIBUSB_ERROR_NOT_FOUND if the transfer is not in progress,
1569  * already complete, or already cancelled.
1570  * \returns a LIBUSB_ERROR code on failure
1571  */
1572 int API_EXPORTED libusb_cancel_transfer(struct libusb_transfer *transfer)
1573 {
1574         struct usbi_transfer *itransfer =
1575                 LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1576         int r;
1577
1578         usbi_dbg("transfer %p", transfer );
1579         usbi_mutex_lock(&itransfer->lock);
1580         if (!(itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT)
1581                         || (itransfer->state_flags & USBI_TRANSFER_CANCELLING)) {
1582                 r = LIBUSB_ERROR_NOT_FOUND;
1583                 goto out;
1584         }
1585         r = usbi_backend.cancel_transfer(itransfer);
1586         if (r < 0) {
1587                 if (r != LIBUSB_ERROR_NOT_FOUND &&
1588                     r != LIBUSB_ERROR_NO_DEVICE)
1589                         usbi_err(TRANSFER_CTX(transfer),
1590                                 "cancel transfer failed error %d", r);
1591                 else
1592                         usbi_dbg("cancel transfer failed error %d", r);
1593
1594                 if (r == LIBUSB_ERROR_NO_DEVICE)
1595                         itransfer->state_flags |= USBI_TRANSFER_DEVICE_DISAPPEARED;
1596         }
1597
1598         itransfer->state_flags |= USBI_TRANSFER_CANCELLING;
1599
1600 out:
1601         usbi_mutex_unlock(&itransfer->lock);
1602         return r;
1603 }
1604
1605 /** \ingroup libusb_asyncio
1606  * Set a transfers bulk stream id. Note users are advised to use
1607  * libusb_fill_bulk_stream_transfer() instead of calling this function
1608  * directly.
1609  *
1610  * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1611  *
1612  * \param transfer the transfer to set the stream id for
1613  * \param stream_id the stream id to set
1614  * \see libusb_alloc_streams()
1615  */
1616 void API_EXPORTED libusb_transfer_set_stream_id(
1617         struct libusb_transfer *transfer, uint32_t stream_id)
1618 {
1619         struct usbi_transfer *itransfer =
1620                 LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1621
1622         itransfer->stream_id = stream_id;
1623 }
1624
1625 /** \ingroup libusb_asyncio
1626  * Get a transfers bulk stream id.
1627  *
1628  * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1629  *
1630  * \param transfer the transfer to get the stream id for
1631  * \returns the stream id for the transfer
1632  */
1633 uint32_t API_EXPORTED libusb_transfer_get_stream_id(
1634         struct libusb_transfer *transfer)
1635 {
1636         struct usbi_transfer *itransfer =
1637                 LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1638
1639         return itransfer->stream_id;
1640 }
1641
1642 /* Handle completion of a transfer (completion might be an error condition).
1643  * This will invoke the user-supplied callback function, which may end up
1644  * freeing the transfer. Therefore you cannot use the transfer structure
1645  * after calling this function, and you should free all backend-specific
1646  * data before calling it.
1647  * Do not call this function with the usbi_transfer lock held. User-specified
1648  * callback functions may attempt to directly resubmit the transfer, which
1649  * will attempt to take the lock. */
1650 int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
1651         enum libusb_transfer_status status)
1652 {
1653         struct libusb_transfer *transfer =
1654                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1655         struct libusb_device_handle *dev_handle = transfer->dev_handle;
1656         uint8_t flags;
1657         int r;
1658
1659         r = remove_from_flying_list(itransfer);
1660         if (r < 0)
1661                 usbi_err(ITRANSFER_CTX(itransfer), "failed to set timer for next timeout, errno=%d", errno);
1662
1663         usbi_mutex_lock(&itransfer->lock);
1664         itransfer->state_flags &= ~USBI_TRANSFER_IN_FLIGHT;
1665         usbi_mutex_unlock(&itransfer->lock);
1666
1667         if (status == LIBUSB_TRANSFER_COMPLETED
1668                         && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1669                 int rqlen = transfer->length;
1670                 if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL)
1671                         rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
1672                 if (rqlen != itransfer->transferred) {
1673                         usbi_dbg("interpreting short transfer as error");
1674                         status = LIBUSB_TRANSFER_ERROR;
1675                 }
1676         }
1677
1678         flags = transfer->flags;
1679         transfer->status = status;
1680         transfer->actual_length = itransfer->transferred;
1681         usbi_dbg("transfer %p has callback %p", transfer, transfer->callback);
1682         if (transfer->callback)
1683                 transfer->callback(transfer);
1684         /* transfer might have been freed by the above call, do not use from
1685          * this point. */
1686         if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
1687                 libusb_free_transfer(transfer);
1688         libusb_unref_device(dev_handle->dev);
1689         return r;
1690 }
1691
1692 /* Similar to usbi_handle_transfer_completion() but exclusively for transfers
1693  * that were asynchronously cancelled. The same concerns w.r.t. freeing of
1694  * transfers exist here.
1695  * Do not call this function with the usbi_transfer lock held. User-specified
1696  * callback functions may attempt to directly resubmit the transfer, which
1697  * will attempt to take the lock. */
1698 int usbi_handle_transfer_cancellation(struct usbi_transfer *itransfer)
1699 {
1700         struct libusb_context *ctx = ITRANSFER_CTX(itransfer);
1701         uint8_t timed_out;
1702
1703         usbi_mutex_lock(&ctx->flying_transfers_lock);
1704         timed_out = itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT;
1705         usbi_mutex_unlock(&ctx->flying_transfers_lock);
1706
1707         /* if the URB was cancelled due to timeout, report timeout to the user */
1708         if (timed_out) {
1709                 usbi_dbg("detected timeout cancellation");
1710                 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_TIMED_OUT);
1711         }
1712
1713         /* otherwise its a normal async cancel */
1714         return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_CANCELLED);
1715 }
1716
1717 /* Add a completed transfer to the completed_transfers list of the
1718  * context and signal the event. The backend's handle_transfer_completion()
1719  * function will be called the next time an event handler runs. */
1720 void usbi_signal_transfer_completion(struct usbi_transfer *itransfer)
1721 {
1722         libusb_device_handle *dev_handle = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)->dev_handle;
1723
1724         if (dev_handle) {
1725                 struct libusb_context *ctx = HANDLE_CTX(dev_handle);
1726                 int pending_events;
1727
1728                 usbi_mutex_lock(&ctx->event_data_lock);
1729                 pending_events = usbi_pending_events(ctx);
1730                 list_add_tail(&itransfer->completed_list, &ctx->completed_transfers);
1731                 if (!pending_events)
1732                         usbi_signal_event(ctx);
1733                 usbi_mutex_unlock(&ctx->event_data_lock);
1734         }
1735 }
1736
1737 /** \ingroup libusb_poll
1738  * Attempt to acquire the event handling lock. This lock is used to ensure that
1739  * only one thread is monitoring libusb event sources at any one time.
1740  *
1741  * You only need to use this lock if you are developing an application
1742  * which calls poll() or select() on libusb's file descriptors directly.
1743  * If you stick to libusb's event handling loop functions (e.g.
1744  * libusb_handle_events()) then you do not need to be concerned with this
1745  * locking.
1746  *
1747  * While holding this lock, you are trusted to actually be handling events.
1748  * If you are no longer handling events, you must call libusb_unlock_events()
1749  * as soon as possible.
1750  *
1751  * \param ctx the context to operate on, or NULL for the default context
1752  * \returns 0 if the lock was obtained successfully
1753  * \returns 1 if the lock was not obtained (i.e. another thread holds the lock)
1754  * \ref libusb_mtasync
1755  */
1756 int API_EXPORTED libusb_try_lock_events(libusb_context *ctx)
1757 {
1758         int r;
1759         unsigned int ru;
1760
1761         ctx = usbi_get_context(ctx);
1762
1763         /* is someone else waiting to close a device? if so, don't let this thread
1764          * start event handling */
1765         usbi_mutex_lock(&ctx->event_data_lock);
1766         ru = ctx->device_close;
1767         usbi_mutex_unlock(&ctx->event_data_lock);
1768         if (ru) {
1769                 usbi_dbg("someone else is closing a device");
1770                 return 1;
1771         }
1772
1773         r = usbi_mutex_trylock(&ctx->events_lock);
1774         if (r)
1775                 return 1;
1776
1777         ctx->event_handler_active = 1;
1778         return 0;
1779 }
1780
1781 /** \ingroup libusb_poll
1782  * Acquire the event handling lock, blocking until successful acquisition if
1783  * it is contended. This lock is used to ensure that only one thread is
1784  * monitoring libusb event sources at any one time.
1785  *
1786  * You only need to use this lock if you are developing an application
1787  * which calls poll() or select() on libusb's file descriptors directly.
1788  * If you stick to libusb's event handling loop functions (e.g.
1789  * libusb_handle_events()) then you do not need to be concerned with this
1790  * locking.
1791  *
1792  * While holding this lock, you are trusted to actually be handling events.
1793  * If you are no longer handling events, you must call libusb_unlock_events()
1794  * as soon as possible.
1795  *
1796  * \param ctx the context to operate on, or NULL for the default context
1797  * \ref libusb_mtasync
1798  */
1799 void API_EXPORTED libusb_lock_events(libusb_context *ctx)
1800 {
1801         ctx = usbi_get_context(ctx);
1802         usbi_mutex_lock(&ctx->events_lock);
1803         ctx->event_handler_active = 1;
1804 }
1805
1806 /** \ingroup libusb_poll
1807  * Release the lock previously acquired with libusb_try_lock_events() or
1808  * libusb_lock_events(). Releasing this lock will wake up any threads blocked
1809  * on libusb_wait_for_event().
1810  *
1811  * \param ctx the context to operate on, or NULL for the default context
1812  * \ref libusb_mtasync
1813  */
1814 void API_EXPORTED libusb_unlock_events(libusb_context *ctx)
1815 {
1816         ctx = usbi_get_context(ctx);
1817         ctx->event_handler_active = 0;
1818         usbi_mutex_unlock(&ctx->events_lock);
1819
1820         /* FIXME: perhaps we should be a bit more efficient by not broadcasting
1821          * the availability of the events lock when we are modifying pollfds
1822          * (check ctx->device_close)? */
1823         usbi_mutex_lock(&ctx->event_waiters_lock);
1824         usbi_cond_broadcast(&ctx->event_waiters_cond);
1825         usbi_mutex_unlock(&ctx->event_waiters_lock);
1826 }
1827
1828 /** \ingroup libusb_poll
1829  * Determine if it is still OK for this thread to be doing event handling.
1830  *
1831  * Sometimes, libusb needs to temporarily pause all event handlers, and this
1832  * is the function you should use before polling file descriptors to see if
1833  * this is the case.
1834  *
1835  * If this function instructs your thread to give up the events lock, you
1836  * should just continue the usual logic that is documented in \ref libusb_mtasync.
1837  * On the next iteration, your thread will fail to obtain the events lock,
1838  * and will hence become an event waiter.
1839  *
1840  * This function should be called while the events lock is held: you don't
1841  * need to worry about the results of this function if your thread is not
1842  * the current event handler.
1843  *
1844  * \param ctx the context to operate on, or NULL for the default context
1845  * \returns 1 if event handling can start or continue
1846  * \returns 0 if this thread must give up the events lock
1847  * \ref fullstory "Multi-threaded I/O: the full story"
1848  */
1849 int API_EXPORTED libusb_event_handling_ok(libusb_context *ctx)
1850 {
1851         unsigned int r;
1852
1853         ctx = usbi_get_context(ctx);
1854
1855         /* is someone else waiting to close a device? if so, don't let this thread
1856          * continue event handling */
1857         usbi_mutex_lock(&ctx->event_data_lock);
1858         r = ctx->device_close;
1859         usbi_mutex_unlock(&ctx->event_data_lock);
1860         if (r) {
1861                 usbi_dbg("someone else is closing a device");
1862                 return 0;
1863         }
1864
1865         return 1;
1866 }
1867
1868
1869 /** \ingroup libusb_poll
1870  * Determine if an active thread is handling events (i.e. if anyone is holding
1871  * the event handling lock).
1872  *
1873  * \param ctx the context to operate on, or NULL for the default context
1874  * \returns 1 if a thread is handling events
1875  * \returns 0 if there are no threads currently handling events
1876  * \ref libusb_mtasync
1877  */
1878 int API_EXPORTED libusb_event_handler_active(libusb_context *ctx)
1879 {
1880         unsigned int r;
1881
1882         ctx = usbi_get_context(ctx);
1883
1884         /* is someone else waiting to close a device? if so, don't let this thread
1885          * start event handling -- indicate that event handling is happening */
1886         usbi_mutex_lock(&ctx->event_data_lock);
1887         r = ctx->device_close;
1888         usbi_mutex_unlock(&ctx->event_data_lock);
1889         if (r) {
1890                 usbi_dbg("someone else is closing a device");
1891                 return 1;
1892         }
1893
1894         return ctx->event_handler_active;
1895 }
1896
1897 /** \ingroup libusb_poll
1898  * Interrupt any active thread that is handling events. This is mainly useful
1899  * for interrupting a dedicated event handling thread when an application
1900  * wishes to call libusb_exit().
1901  *
1902  * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
1903  *
1904  * \param ctx the context to operate on, or NULL for the default context
1905  * \ref libusb_mtasync
1906  */
1907 void API_EXPORTED libusb_interrupt_event_handler(libusb_context *ctx)
1908 {
1909         int pending_events;
1910
1911         usbi_dbg(" ");
1912
1913         ctx = usbi_get_context(ctx);
1914         usbi_mutex_lock(&ctx->event_data_lock);
1915
1916         pending_events = usbi_pending_events(ctx);
1917         ctx->event_flags |= USBI_EVENT_USER_INTERRUPT;
1918         if (!pending_events)
1919                 usbi_signal_event(ctx);
1920
1921         usbi_mutex_unlock(&ctx->event_data_lock);
1922 }
1923
1924 /** \ingroup libusb_poll
1925  * Acquire the event waiters lock. This lock is designed to be obtained under
1926  * the situation where you want to be aware when events are completed, but
1927  * some other thread is event handling so calling libusb_handle_events() is not
1928  * allowed.
1929  *
1930  * You then obtain this lock, re-check that another thread is still handling
1931  * events, then call libusb_wait_for_event().
1932  *
1933  * You only need to use this lock if you are developing an application
1934  * which calls poll() or select() on libusb's file descriptors directly,
1935  * <b>and</b> may potentially be handling events from 2 threads simultaenously.
1936  * If you stick to libusb's event handling loop functions (e.g.
1937  * libusb_handle_events()) then you do not need to be concerned with this
1938  * locking.
1939  *
1940  * \param ctx the context to operate on, or NULL for the default context
1941  * \ref libusb_mtasync
1942  */
1943 void API_EXPORTED libusb_lock_event_waiters(libusb_context *ctx)
1944 {
1945         ctx = usbi_get_context(ctx);
1946         usbi_mutex_lock(&ctx->event_waiters_lock);
1947 }
1948
1949 /** \ingroup libusb_poll
1950  * Release the event waiters lock.
1951  * \param ctx the context to operate on, or NULL for the default context
1952  * \ref libusb_mtasync
1953  */
1954 void API_EXPORTED libusb_unlock_event_waiters(libusb_context *ctx)
1955 {
1956         ctx = usbi_get_context(ctx);
1957         usbi_mutex_unlock(&ctx->event_waiters_lock);
1958 }
1959
1960 /** \ingroup libusb_poll
1961  * Wait for another thread to signal completion of an event. Must be called
1962  * with the event waiters lock held, see libusb_lock_event_waiters().
1963  *
1964  * This function will block until any of the following conditions are met:
1965  * -# The timeout expires
1966  * -# A transfer completes
1967  * -# A thread releases the event handling lock through libusb_unlock_events()
1968  *
1969  * Condition 1 is obvious. Condition 2 unblocks your thread <em>after</em>
1970  * the callback for the transfer has completed. Condition 3 is important
1971  * because it means that the thread that was previously handling events is no
1972  * longer doing so, so if any events are to complete, another thread needs to
1973  * step up and start event handling.
1974  *
1975  * This function releases the event waiters lock before putting your thread
1976  * to sleep, and reacquires the lock as it is being woken up.
1977  *
1978  * \param ctx the context to operate on, or NULL for the default context
1979  * \param tv maximum timeout for this blocking function. A NULL value
1980  * indicates unlimited timeout.
1981  * \returns 0 after a transfer completes or another thread stops event handling
1982  * \returns 1 if the timeout expired
1983  * \ref libusb_mtasync
1984  */
1985 int API_EXPORTED libusb_wait_for_event(libusb_context *ctx, struct timeval *tv)
1986 {
1987         int r;
1988
1989         ctx = usbi_get_context(ctx);
1990         if (tv == NULL) {
1991                 usbi_cond_wait(&ctx->event_waiters_cond, &ctx->event_waiters_lock);
1992                 return 0;
1993         }
1994
1995         r = usbi_cond_timedwait(&ctx->event_waiters_cond,
1996                 &ctx->event_waiters_lock, tv);
1997
1998         if (r < 0)
1999                 return r;
2000         else
2001                 return (r == ETIMEDOUT);
2002 }
2003
2004 static void handle_timeout(struct usbi_transfer *itransfer)
2005 {
2006         struct libusb_transfer *transfer =
2007                 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2008         int r;
2009
2010         itransfer->timeout_flags |= USBI_TRANSFER_TIMEOUT_HANDLED;
2011         r = libusb_cancel_transfer(transfer);
2012         if (r == LIBUSB_SUCCESS)
2013                 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2014         else
2015                 usbi_warn(TRANSFER_CTX(transfer),
2016                         "async cancel failed %d errno=%d", r, errno);
2017 }
2018
2019 static int handle_timeouts_locked(struct libusb_context *ctx)
2020 {
2021         int r;
2022         struct timespec systime;
2023         struct usbi_transfer *itransfer;
2024
2025         if (list_empty(&ctx->flying_transfers))
2026                 return 0;
2027
2028         /* get current time */
2029         r = usbi_clock_gettime(USBI_CLOCK_MONOTONIC, &systime);
2030         if (r < 0)
2031                 return r;
2032
2033         /* iterate through flying transfers list, finding all transfers that
2034          * have expired timeouts */
2035         list_for_each_entry(itransfer, &ctx->flying_transfers, list, struct usbi_transfer) {
2036                 struct timespec *cur_ts = &itransfer->timeout;
2037
2038                 /* if we've reached transfers of infinite timeout, we're all done */
2039                 if (!TIMESPEC_IS_SET(cur_ts))
2040                         return 0;
2041
2042                 /* ignore timeouts we've already handled */
2043                 if (itransfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
2044                         continue;
2045
2046                 /* if transfer has non-expired timeout, nothing more to do */
2047                 if (TIMESPEC_CMP(cur_ts, &systime, >))
2048                         return 0;
2049
2050                 /* otherwise, we've got an expired timeout to handle */
2051                 handle_timeout(itransfer);
2052         }
2053         return 0;
2054 }
2055
2056 static int handle_timeouts(struct libusb_context *ctx)
2057 {
2058         int r;
2059
2060         ctx = usbi_get_context(ctx);
2061         usbi_mutex_lock(&ctx->flying_transfers_lock);
2062         r = handle_timeouts_locked(ctx);
2063         usbi_mutex_unlock(&ctx->flying_transfers_lock);
2064         return r;
2065 }
2066
2067 #ifdef HAVE_TIMERFD
2068 static int handle_timerfd_trigger(struct libusb_context *ctx)
2069 {
2070         int r;
2071
2072         usbi_mutex_lock(&ctx->flying_transfers_lock);
2073
2074         /* process the timeout that just happened */
2075         r = handle_timeouts_locked(ctx);
2076         if (r < 0)
2077                 goto out;
2078
2079         /* arm for next timeout*/
2080         r = arm_timerfd_for_next_timeout(ctx);
2081
2082 out:
2083         usbi_mutex_unlock(&ctx->flying_transfers_lock);
2084         return r;
2085 }
2086 #endif
2087
2088 /* do the actual event handling. assumes that no other thread is concurrently
2089  * doing the same thing. */
2090 static int handle_events(struct libusb_context *ctx, struct timeval *tv)
2091 {
2092         int r;
2093         struct usbi_pollfd *ipollfd;
2094         usbi_nfds_t nfds = 0;
2095         usbi_nfds_t internal_nfds;
2096         struct pollfd *fds = NULL;
2097         int timeout_ms;
2098
2099         /* prevent attempts to recursively handle events (e.g. calling into
2100          * libusb_handle_events() from within a hotplug or transfer callback) */
2101         usbi_mutex_lock(&ctx->event_data_lock);
2102         r = 0;
2103         if (usbi_handling_events(ctx))
2104                 r = LIBUSB_ERROR_BUSY;
2105         else
2106                 usbi_start_event_handling(ctx);
2107         usbi_mutex_unlock(&ctx->event_data_lock);
2108
2109         if (r)
2110                 return r;
2111
2112         /* there are certain fds that libusb uses internally, currently:
2113          *
2114          *   1) event pipe
2115          *   2) timerfd
2116          *
2117          * the backend will never need to attempt to handle events on these fds, so
2118          * we determine how many fds are in use internally for this context and when
2119          * handle_events() is called in the backend, the pollfd list and count will
2120          * be adjusted to skip over these internal fds */
2121         if (usbi_using_timerfd(ctx))
2122                 internal_nfds = 2;
2123         else
2124                 internal_nfds = 1;
2125
2126         /* only reallocate the poll fds when the list of poll fds has been modified
2127          * since the last poll, otherwise reuse them to save the additional overhead */
2128         usbi_mutex_lock(&ctx->event_data_lock);
2129         /* clean up removed poll fds */
2130         cleanup_removed_pollfds(ctx);
2131         if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED) {
2132                 int i = 0;
2133
2134                 usbi_dbg("poll fds modified, reallocating");
2135
2136                 free(ctx->pollfds);
2137                 ctx->pollfds = NULL;
2138
2139                 /* sanity check - it is invalid for a context to have fewer than the
2140                  * required internal fds (memory corruption?) */
2141                 assert(ctx->pollfds_cnt >= internal_nfds);
2142
2143                 ctx->pollfds = calloc(ctx->pollfds_cnt, sizeof(*ctx->pollfds));
2144                 if (!ctx->pollfds) {
2145                         usbi_mutex_unlock(&ctx->event_data_lock);
2146                         r = LIBUSB_ERROR_NO_MEM;
2147                         goto done;
2148                 }
2149
2150                 list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd) {
2151                         struct libusb_pollfd *pollfd = &ipollfd->pollfd;
2152                         ctx->pollfds[i].fd = pollfd->fd;
2153                         ctx->pollfds[i].events = pollfd->events;
2154                         i++;
2155                 }
2156
2157                 /* reset the flag now that we have the updated list */
2158                 ctx->event_flags &= ~USBI_EVENT_POLLFDS_MODIFIED;
2159
2160                 /* if no further pending events, clear the event pipe so that we do
2161                  * not immediately return from poll */
2162                 if (!usbi_pending_events(ctx))
2163                         usbi_clear_event(ctx);
2164         }
2165         fds = ctx->pollfds;
2166         nfds = ctx->pollfds_cnt;
2167         usbi_mutex_unlock(&ctx->event_data_lock);
2168
2169         timeout_ms = (int)(tv->tv_sec * 1000) + (tv->tv_usec / 1000);
2170
2171         /* round up to next millisecond */
2172         if (tv->tv_usec % 1000)
2173                 timeout_ms++;
2174
2175         usbi_dbg("poll() %d fds with timeout in %dms", (int)nfds, timeout_ms);
2176         r = usbi_poll(fds, nfds, timeout_ms);
2177         usbi_dbg("poll() returned %d", r);
2178         if (r == 0) {
2179                 r = handle_timeouts(ctx);
2180                 goto done;
2181         } else if (r == -1 && errno == EINTR) {
2182                 r = LIBUSB_ERROR_INTERRUPTED;
2183                 goto done;
2184         } else if (r < 0) {
2185                 usbi_err(ctx, "poll failed, errno=%d", errno);
2186                 r = LIBUSB_ERROR_IO;
2187                 goto done;
2188         }
2189
2190         /* fds[0] is always the event pipe */
2191         if (fds[0].revents) {
2192                 struct list_head hotplug_msgs;
2193                 struct usbi_transfer *itransfer;
2194                 int hotplug_cb_deregistered = 0;
2195                 int ret = 0;
2196
2197                 list_init(&hotplug_msgs);
2198
2199                 usbi_dbg("caught a fish on the event pipe");
2200
2201                 /* take the the event data lock while processing events */
2202                 usbi_mutex_lock(&ctx->event_data_lock);
2203
2204                 /* check if someone added a new poll fd */
2205                 if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED)
2206                         usbi_dbg("someone updated the poll fds");
2207
2208                 if (ctx->event_flags & USBI_EVENT_USER_INTERRUPT) {
2209                         usbi_dbg("someone purposely interrupted");
2210                         ctx->event_flags &= ~USBI_EVENT_USER_INTERRUPT;
2211                 }
2212
2213                 if (ctx->event_flags & USBI_EVENT_HOTPLUG_CB_DEREGISTERED) {
2214                         usbi_dbg("someone unregistered a hotplug cb");
2215                         ctx->event_flags &= ~USBI_EVENT_HOTPLUG_CB_DEREGISTERED;
2216                         hotplug_cb_deregistered = 1;
2217                 }
2218
2219                 /* check if someone is closing a device */
2220                 if (ctx->device_close)
2221                         usbi_dbg("someone is closing a device");
2222
2223                 /* check for any pending hotplug messages */
2224                 if (!list_empty(&ctx->hotplug_msgs)) {
2225                         usbi_dbg("hotplug message received");
2226                         list_cut(&hotplug_msgs, &ctx->hotplug_msgs);
2227                 }
2228
2229                 /* complete any pending transfers */
2230                 while (ret == 0 && !list_empty(&ctx->completed_transfers)) {
2231                         itransfer = list_first_entry(&ctx->completed_transfers, struct usbi_transfer, completed_list);
2232                         list_del(&itransfer->completed_list);
2233                         usbi_mutex_unlock(&ctx->event_data_lock);
2234                         ret = usbi_backend.handle_transfer_completion(itransfer);
2235                         if (ret)
2236                                 usbi_err(ctx, "backend handle_transfer_completion failed with error %d", ret);
2237                         usbi_mutex_lock(&ctx->event_data_lock);
2238                 }
2239
2240                 /* if no further pending events, clear the event pipe */
2241                 if (!usbi_pending_events(ctx))
2242                         usbi_clear_event(ctx);
2243
2244                 usbi_mutex_unlock(&ctx->event_data_lock);
2245
2246                 if (hotplug_cb_deregistered)
2247                         usbi_hotplug_deregister(ctx, 0);
2248
2249                 /* process the hotplug messages, if any */
2250                 while (!list_empty(&hotplug_msgs)) {
2251                         struct libusb_hotplug_message *message =
2252                                 list_first_entry(&hotplug_msgs, struct libusb_hotplug_message, list);
2253
2254                         usbi_hotplug_match(ctx, message->device, message->event);
2255
2256                         /* the device left, dereference the device */
2257                         if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == message->event)
2258                                 libusb_unref_device(message->device);
2259
2260                         list_del(&message->list);
2261                         free(message);
2262                 }
2263
2264                 if (ret) {
2265                         /* return error code */
2266                         r = ret;
2267                         goto done;
2268                 }
2269
2270                 if (0 == --r)
2271                         goto done;
2272         }
2273
2274 #ifdef HAVE_TIMERFD
2275         /* on timerfd configurations, fds[1] is the timerfd */
2276         if (usbi_using_timerfd(ctx) && fds[1].revents) {
2277                 /* timerfd indicates that a timeout has expired */
2278                 int ret;
2279                 usbi_dbg("timerfd triggered");
2280
2281                 ret = handle_timerfd_trigger(ctx);
2282                 if (ret < 0) {
2283                         /* return error code */
2284                         r = ret;
2285                         goto done;
2286                 }
2287
2288                 if (0 == --r)
2289                         goto done;
2290         }
2291 #endif
2292
2293         list_for_each_entry(ipollfd, &ctx->removed_ipollfds, list, struct usbi_pollfd) {
2294                 usbi_nfds_t n;
2295
2296                 for (n = internal_nfds ; n < nfds ; n++) {
2297                         if (ipollfd->pollfd.fd == fds[n].fd) {
2298                                 /* pollfd was removed between the creation of the fd
2299                                  * array and here. remove any triggered revent as
2300                                  * it is no longer relevant */
2301                                 usbi_dbg("pollfd %d was removed. ignoring raised events",
2302                                          fds[n].fd);
2303                                 fds[n].revents = 0;
2304                                 break;
2305                         }
2306                 }
2307         }
2308
2309         r = usbi_backend.handle_events(ctx, fds + internal_nfds, nfds - internal_nfds, r);
2310         if (r)
2311                 usbi_err(ctx, "backend handle_events failed with error %d", r);
2312
2313 done:
2314         usbi_end_event_handling(ctx);
2315         return r;
2316 }
2317
2318 /* returns the smallest of:
2319  *  1. timeout of next URB
2320  *  2. user-supplied timeout
2321  * returns 1 if there is an already-expired timeout, otherwise returns 0
2322  * and populates out
2323  */
2324 static int get_next_timeout(libusb_context *ctx, struct timeval *tv,
2325         struct timeval *out)
2326 {
2327         struct timeval timeout;
2328         int r = libusb_get_next_timeout(ctx, &timeout);
2329         if (r) {
2330                 /* timeout already expired? */
2331                 if (!timerisset(&timeout))
2332                         return 1;
2333
2334                 /* choose the smallest of next URB timeout or user specified timeout */
2335                 if (timercmp(&timeout, tv, <))
2336                         *out = timeout;
2337                 else
2338                         *out = *tv;
2339         } else {
2340                 *out = *tv;
2341         }
2342         return 0;
2343 }
2344
2345 /** \ingroup libusb_poll
2346  * Handle any pending events.
2347  *
2348  * libusb determines "pending events" by checking if any timeouts have expired
2349  * and by checking the set of file descriptors for activity.
2350  *
2351  * If a zero timeval is passed, this function will handle any already-pending
2352  * events and then immediately return in non-blocking style.
2353  *
2354  * If a non-zero timeval is passed and no events are currently pending, this
2355  * function will block waiting for events to handle up until the specified
2356  * timeout. If an event arrives or a signal is raised, this function will
2357  * return early.
2358  *
2359  * If the parameter completed is not NULL then <em>after obtaining the event
2360  * handling lock</em> this function will return immediately if the integer
2361  * pointed to is not 0. This allows for race free waiting for the completion
2362  * of a specific transfer.
2363  *
2364  * \param ctx the context to operate on, or NULL for the default context
2365  * \param tv the maximum time to block waiting for events, or an all zero
2366  * timeval struct for non-blocking mode
2367  * \param completed pointer to completion integer to check, or NULL
2368  * \returns 0 on success, or a LIBUSB_ERROR code on failure
2369  * \ref libusb_mtasync
2370  */
2371 int API_EXPORTED libusb_handle_events_timeout_completed(libusb_context *ctx,
2372         struct timeval *tv, int *completed)
2373 {
2374         int r;
2375         struct timeval poll_timeout;
2376
2377         ctx = usbi_get_context(ctx);
2378         r = get_next_timeout(ctx, tv, &poll_timeout);
2379         if (r) {
2380                 /* timeout already expired */
2381                 return handle_timeouts(ctx);
2382         }
2383
2384 retry:
2385         if (libusb_try_lock_events(ctx) == 0) {
2386                 if (completed == NULL || !*completed) {
2387                         /* we obtained the event lock: do our own event handling */
2388                         usbi_dbg("doing our own event handling");
2389                         r = handle_events(ctx, &poll_timeout);
2390                 }
2391                 libusb_unlock_events(ctx);
2392                 return r;
2393         }
2394
2395         /* another thread is doing event handling. wait for thread events that
2396          * notify event completion. */
2397         libusb_lock_event_waiters(ctx);
2398
2399         if (completed && *completed)
2400                 goto already_done;
2401
2402         if (!libusb_event_handler_active(ctx)) {
2403                 /* we hit a race: whoever was event handling earlier finished in the
2404                  * time it took us to reach this point. try the cycle again. */
2405                 libusb_unlock_event_waiters(ctx);
2406                 usbi_dbg("event handler was active but went away, retrying");
2407                 goto retry;
2408         }
2409
2410         usbi_dbg("another thread is doing event handling");
2411         r = libusb_wait_for_event(ctx, &poll_timeout);
2412
2413 already_done:
2414         libusb_unlock_event_waiters(ctx);
2415
2416         if (r < 0)
2417                 return r;
2418         else if (r == 1)
2419                 return handle_timeouts(ctx);
2420         else
2421                 return 0;
2422 }
2423
2424 /** \ingroup libusb_poll
2425  * Handle any pending events
2426  *
2427  * Like libusb_handle_events_timeout_completed(), but without the completed
2428  * parameter, calling this function is equivalent to calling
2429  * libusb_handle_events_timeout_completed() with a NULL completed parameter.
2430  *
2431  * This function is kept primarily for backwards compatibility.
2432  * All new code should call libusb_handle_events_completed() or
2433  * libusb_handle_events_timeout_completed() to avoid race conditions.
2434  *
2435  * \param ctx the context to operate on, or NULL for the default context
2436  * \param tv the maximum time to block waiting for events, or an all zero
2437  * timeval struct for non-blocking mode
2438  * \returns 0 on success, or a LIBUSB_ERROR code on failure
2439  */
2440 int API_EXPORTED libusb_handle_events_timeout(libusb_context *ctx,
2441         struct timeval *tv)
2442 {
2443         return libusb_handle_events_timeout_completed(ctx, tv, NULL);
2444 }
2445
2446 /** \ingroup libusb_poll
2447  * Handle any pending events in blocking mode. There is currently a timeout
2448  * hardcoded at 60 seconds but we plan to make it unlimited in future. For
2449  * finer control over whether this function is blocking or non-blocking, or
2450  * for control over the timeout, use libusb_handle_events_timeout_completed()
2451  * instead.
2452  *
2453  * This function is kept primarily for backwards compatibility.
2454  * All new code should call libusb_handle_events_completed() or
2455  * libusb_handle_events_timeout_completed() to avoid race conditions.
2456  *
2457  * \param ctx the context to operate on, or NULL for the default context
2458  * \returns 0 on success, or a LIBUSB_ERROR code on failure
2459  */
2460 int API_EXPORTED libusb_handle_events(libusb_context *ctx)
2461 {
2462         struct timeval tv;
2463         tv.tv_sec = 60;
2464         tv.tv_usec = 0;
2465         return libusb_handle_events_timeout_completed(ctx, &tv, NULL);
2466 }
2467
2468 /** \ingroup libusb_poll
2469  * Handle any pending events in blocking mode.
2470  *
2471  * Like libusb_handle_events(), with the addition of a completed parameter
2472  * to allow for race free waiting for the completion of a specific transfer.
2473  *
2474  * See libusb_handle_events_timeout_completed() for details on the completed
2475  * parameter.
2476  *
2477  * \param ctx the context to operate on, or NULL for the default context
2478  * \param completed pointer to completion integer to check, or NULL
2479  * \returns 0 on success, or a LIBUSB_ERROR code on failure
2480  * \ref libusb_mtasync
2481  */
2482 int API_EXPORTED libusb_handle_events_completed(libusb_context *ctx,
2483         int *completed)
2484 {
2485         struct timeval tv;
2486         tv.tv_sec = 60;
2487         tv.tv_usec = 0;
2488         return libusb_handle_events_timeout_completed(ctx, &tv, completed);
2489 }
2490
2491 /** \ingroup libusb_poll
2492  * Handle any pending events by polling file descriptors, without checking if
2493  * any other threads are already doing so. Must be called with the event lock
2494  * held, see libusb_lock_events().
2495  *
2496  * This function is designed to be called under the situation where you have
2497  * taken the event lock and are calling poll()/select() directly on libusb's
2498  * file descriptors (as opposed to using libusb_handle_events() or similar).
2499  * You detect events on libusb's descriptors, so you then call this function
2500  * with a zero timeout value (while still holding the event lock).
2501  *
2502  * \param ctx the context to operate on, or NULL for the default context
2503  * \param tv the maximum time to block waiting for events, or zero for
2504  * non-blocking mode
2505  * \returns 0 on success, or a LIBUSB_ERROR code on failure
2506  * \ref libusb_mtasync
2507  */
2508 int API_EXPORTED libusb_handle_events_locked(libusb_context *ctx,
2509         struct timeval *tv)
2510 {
2511         int r;
2512         struct timeval poll_timeout;
2513
2514         ctx = usbi_get_context(ctx);
2515         r = get_next_timeout(ctx, tv, &poll_timeout);
2516         if (r) {
2517                 /* timeout already expired */
2518                 return handle_timeouts(ctx);
2519         }
2520
2521         return handle_events(ctx, &poll_timeout);
2522 }
2523
2524 /** \ingroup libusb_poll
2525  * Determines whether your application must apply special timing considerations
2526  * when monitoring libusb's file descriptors.
2527  *
2528  * This function is only useful for applications which retrieve and poll
2529  * libusb's file descriptors in their own main loop (\ref libusb_pollmain).
2530  *
2531  * Ordinarily, libusb's event handler needs to be called into at specific
2532  * moments in time (in addition to times when there is activity on the file
2533  * descriptor set). The usual approach is to use libusb_get_next_timeout()
2534  * to learn about when the next timeout occurs, and to adjust your
2535  * poll()/select() timeout accordingly so that you can make a call into the
2536  * library at that time.
2537  *
2538  * Some platforms supported by libusb do not come with this baggage - any
2539  * events relevant to timing will be represented by activity on the file
2540  * descriptor set, and libusb_get_next_timeout() will always return 0.
2541  * This function allows you to detect whether you are running on such a
2542  * platform.
2543  *
2544  * Since v1.0.5.
2545  *
2546  * \param ctx the context to operate on, or NULL for the default context
2547  * \returns 0 if you must call into libusb at times determined by
2548  * libusb_get_next_timeout(), or 1 if all timeout events are handled internally
2549  * or through regular activity on the file descriptors.
2550  * \ref libusb_pollmain "Polling libusb file descriptors for event handling"
2551  */
2552 int API_EXPORTED libusb_pollfds_handle_timeouts(libusb_context *ctx)
2553 {
2554 #ifdef HAVE_TIMERFD
2555         ctx = usbi_get_context(ctx);
2556         return usbi_using_timerfd(ctx);
2557 #else
2558         UNUSED(ctx);
2559         return 0;
2560 #endif
2561 }
2562
2563 /** \ingroup libusb_poll
2564  * Determine the next internal timeout that libusb needs to handle. You only
2565  * need to use this function if you are calling poll() or select() or similar
2566  * on libusb's file descriptors yourself - you do not need to use it if you
2567  * are calling libusb_handle_events() or a variant directly.
2568  *
2569  * You should call this function in your main loop in order to determine how
2570  * long to wait for select() or poll() to return results. libusb needs to be
2571  * called into at this timeout, so you should use it as an upper bound on
2572  * your select() or poll() call.
2573  *
2574  * When the timeout has expired, call into libusb_handle_events_timeout()
2575  * (perhaps in non-blocking mode) so that libusb can handle the timeout.
2576  *
2577  * This function may return 1 (success) and an all-zero timeval. If this is
2578  * the case, it indicates that libusb has a timeout that has already expired
2579  * so you should call libusb_handle_events_timeout() or similar immediately.
2580  * A return code of 0 indicates that there are no pending timeouts.
2581  *
2582  * On some platforms, this function will always returns 0 (no pending
2583  * timeouts). See \ref polltime.
2584  *
2585  * \param ctx the context to operate on, or NULL for the default context
2586  * \param tv output location for a relative time against the current
2587  * clock in which libusb must be called into in order to process timeout events
2588  * \returns 0 if there are no pending timeouts, 1 if a timeout was returned,
2589  * or LIBUSB_ERROR_OTHER on failure
2590  */
2591 int API_EXPORTED libusb_get_next_timeout(libusb_context *ctx,
2592         struct timeval *tv)
2593 {
2594         struct usbi_transfer *itransfer;
2595         struct timespec systime;
2596         struct timespec next_timeout = { 0, 0 };
2597         int r;
2598
2599         ctx = usbi_get_context(ctx);
2600         if (usbi_using_timerfd(ctx))
2601                 return 0;
2602
2603         usbi_mutex_lock(&ctx->flying_transfers_lock);
2604         if (list_empty(&ctx->flying_transfers)) {
2605                 usbi_mutex_unlock(&ctx->flying_transfers_lock);
2606                 usbi_dbg("no URBs, no timeout!");
2607                 return 0;
2608         }
2609
2610         /* find next transfer which hasn't already been processed as timed out */
2611         list_for_each_entry(itransfer, &ctx->flying_transfers, list, struct usbi_transfer) {
2612                 if (itransfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
2613                         continue;
2614
2615                 /* if we've reached transfers of infinte timeout, we're done looking */
2616                 if (!TIMESPEC_IS_SET(&itransfer->timeout))
2617                         break;
2618
2619                 next_timeout = itransfer->timeout;
2620                 break;
2621         }
2622         usbi_mutex_unlock(&ctx->flying_transfers_lock);
2623
2624         if (!TIMESPEC_IS_SET(&next_timeout)) {
2625                 usbi_dbg("no URB with timeout or all handled by OS; no timeout!");
2626                 return 0;
2627         }
2628
2629         r = usbi_clock_gettime(USBI_CLOCK_MONOTONIC, &systime);
2630         if (r < 0) {
2631                 usbi_err(ctx, "failed to read monotonic clock, errno=%d", errno);
2632                 return 0;
2633         }
2634
2635         if (!TIMESPEC_CMP(&systime, &next_timeout, <)) {
2636                 usbi_dbg("first timeout already expired");
2637                 timerclear(tv);
2638         } else {
2639                 TIMESPEC_SUB(&next_timeout, &systime, &next_timeout);
2640                 TIMESPEC_TO_TIMEVAL(tv, &next_timeout);
2641                 usbi_dbg("next timeout in %ld.%06lds", (long)tv->tv_sec, (long)tv->tv_usec);
2642         }
2643
2644         return 1;
2645 }
2646
2647 /** \ingroup libusb_poll
2648  * Register notification functions for file descriptor additions/removals.
2649  * These functions will be invoked for every new or removed file descriptor
2650  * that libusb uses as an event source.
2651  *
2652  * To remove notifiers, pass NULL values for the function pointers.
2653  *
2654  * Note that file descriptors may have been added even before you register
2655  * these notifiers (e.g. at libusb_init() time).
2656  *
2657  * Additionally, note that the removal notifier may be called during
2658  * libusb_exit() (e.g. when it is closing file descriptors that were opened
2659  * and added to the poll set at libusb_init() time). If you don't want this,
2660  * remove the notifiers immediately before calling libusb_exit().
2661  *
2662  * \param ctx the context to operate on, or NULL for the default context
2663  * \param added_cb pointer to function for addition notifications
2664  * \param removed_cb pointer to function for removal notifications
2665  * \param user_data User data to be passed back to callbacks (useful for
2666  * passing context information)
2667  */
2668 void API_EXPORTED libusb_set_pollfd_notifiers(libusb_context *ctx,
2669         libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
2670         void *user_data)
2671 {
2672         ctx = usbi_get_context(ctx);
2673         ctx->fd_added_cb = added_cb;
2674         ctx->fd_removed_cb = removed_cb;
2675         ctx->fd_cb_user_data = user_data;
2676 }
2677
2678 /*
2679  * Interrupt the iteration of the event handling thread, so that it picks
2680  * up the fd change. Callers of this function must hold the event_data_lock.
2681  */
2682 static void usbi_fd_notification(struct libusb_context *ctx)
2683 {
2684         int pending_events;
2685
2686         /* Record that there is a new poll fd.
2687          * Only signal an event if there are no prior pending events. */
2688         pending_events = usbi_pending_events(ctx);
2689         ctx->event_flags |= USBI_EVENT_POLLFDS_MODIFIED;
2690         if (!pending_events)
2691                 usbi_signal_event(ctx);
2692 }
2693
2694 /* Add a file descriptor to the list of file descriptors to be monitored.
2695  * events should be specified as a bitmask of events passed to poll(), e.g.
2696  * POLLIN and/or POLLOUT. */
2697 int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events)
2698 {
2699         struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
2700         if (!ipollfd)
2701                 return LIBUSB_ERROR_NO_MEM;
2702
2703         usbi_dbg("add fd %d events %d", fd, events);
2704         ipollfd->pollfd.fd = fd;
2705         ipollfd->pollfd.events = events;
2706         usbi_mutex_lock(&ctx->event_data_lock);
2707         list_add_tail(&ipollfd->list, &ctx->ipollfds);
2708         ctx->pollfds_cnt++;
2709         usbi_fd_notification(ctx);
2710         usbi_mutex_unlock(&ctx->event_data_lock);
2711
2712         if (ctx->fd_added_cb)
2713                 ctx->fd_added_cb(fd, events, ctx->fd_cb_user_data);
2714         return 0;
2715 }
2716
2717 /* Remove a file descriptor from the list of file descriptors to be polled. */
2718 void usbi_remove_pollfd(struct libusb_context *ctx, int fd)
2719 {
2720         struct usbi_pollfd *ipollfd;
2721         int found = 0;
2722
2723         usbi_dbg("remove fd %d", fd);
2724         usbi_mutex_lock(&ctx->event_data_lock);
2725         list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd)
2726                 if (ipollfd->pollfd.fd == fd) {
2727                         found = 1;
2728                         break;
2729                 }
2730
2731         if (!found) {
2732                 usbi_dbg("couldn't find fd %d to remove", fd);
2733                 usbi_mutex_unlock(&ctx->event_data_lock);
2734                 return;
2735         }
2736
2737         list_del(&ipollfd->list);
2738         list_add_tail(&ipollfd->list, &ctx->removed_ipollfds);
2739         ctx->pollfds_cnt--;
2740         usbi_fd_notification(ctx);
2741         usbi_mutex_unlock(&ctx->event_data_lock);
2742
2743         if (ctx->fd_removed_cb)
2744                 ctx->fd_removed_cb(fd, ctx->fd_cb_user_data);
2745 }
2746
2747 /** \ingroup libusb_poll
2748  * Retrieve a list of file descriptors that should be polled by your main loop
2749  * as libusb event sources.
2750  *
2751  * The returned list is NULL-terminated and should be freed with libusb_free_pollfds()
2752  * when done. The actual list contents must not be touched.
2753  *
2754  * As file descriptors are a Unix-specific concept, this function is not
2755  * available on Windows and will always return NULL.
2756  *
2757  * \param ctx the context to operate on, or NULL for the default context
2758  * \returns a NULL-terminated list of libusb_pollfd structures
2759  * \returns NULL on error
2760  * \returns NULL on platforms where the functionality is not available
2761  */
2762 DEFAULT_VISIBILITY
2763 const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds(
2764         libusb_context *ctx)
2765 {
2766 #ifndef OS_WINDOWS
2767         struct libusb_pollfd **ret = NULL;
2768         struct usbi_pollfd *ipollfd;
2769         size_t i = 0;
2770
2771         ctx = usbi_get_context(ctx);
2772
2773         usbi_mutex_lock(&ctx->event_data_lock);
2774
2775         ret = calloc(ctx->pollfds_cnt + 1, sizeof(struct libusb_pollfd *));
2776         if (!ret)
2777                 goto out;
2778
2779         list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd)
2780                 ret[i++] = (struct libusb_pollfd *) ipollfd;
2781         ret[ctx->pollfds_cnt] = NULL;
2782
2783 out:
2784         usbi_mutex_unlock(&ctx->event_data_lock);
2785         return (const struct libusb_pollfd **) ret;
2786 #else
2787         usbi_err(ctx, "external polling of libusb's internal descriptors "\
2788                 "is not yet supported on Windows platforms");
2789         return NULL;
2790 #endif
2791 }
2792
2793 /** \ingroup libusb_poll
2794  * Free a list of libusb_pollfd structures. This should be called for all
2795  * pollfd lists allocated with libusb_get_pollfds().
2796  *
2797  * Since version 1.0.20, \ref LIBUSB_API_VERSION >= 0x01000104
2798  *
2799  * It is legal to call this function with a NULL pollfd list. In this case,
2800  * the function will simply do nothing.
2801  *
2802  * \param pollfds the list of libusb_pollfd structures to free
2803  */
2804 void API_EXPORTED libusb_free_pollfds(const struct libusb_pollfd **pollfds)
2805 {
2806         free((void *)pollfds);
2807 }
2808
2809 /* Backends may call this from handle_events to report disconnection of a
2810  * device. This function ensures transfers get cancelled appropriately.
2811  * Callers of this function must hold the events_lock.
2812  */
2813 void usbi_handle_disconnect(struct libusb_device_handle *dev_handle)
2814 {
2815         struct usbi_transfer *cur;
2816         struct usbi_transfer *to_cancel;
2817
2818         usbi_dbg("device %d.%d",
2819                 dev_handle->dev->bus_number, dev_handle->dev->device_address);
2820
2821         /* terminate all pending transfers with the LIBUSB_TRANSFER_NO_DEVICE
2822          * status code.
2823          *
2824          * when we find a transfer for this device on the list, there are two
2825          * possible scenarios:
2826          * 1. the transfer is currently in-flight, in which case we terminate the
2827          *    transfer here
2828          * 2. the transfer has been added to the flying transfer list by
2829          *    libusb_submit_transfer, has failed to submit and
2830          *    libusb_submit_transfer is waiting for us to release the
2831          *    flying_transfers_lock to remove it, so we ignore it
2832          */
2833
2834         while (1) {
2835                 to_cancel = NULL;
2836                 usbi_mutex_lock(&HANDLE_CTX(dev_handle)->flying_transfers_lock);
2837                 list_for_each_entry(cur, &HANDLE_CTX(dev_handle)->flying_transfers, list, struct usbi_transfer)
2838                         if (USBI_TRANSFER_TO_LIBUSB_TRANSFER(cur)->dev_handle == dev_handle) {
2839                                 usbi_mutex_lock(&cur->lock);
2840                                 if (cur->state_flags & USBI_TRANSFER_IN_FLIGHT)
2841                                         to_cancel = cur;
2842                                 usbi_mutex_unlock(&cur->lock);
2843
2844                                 if (to_cancel)
2845                                         break;
2846                         }
2847                 usbi_mutex_unlock(&HANDLE_CTX(dev_handle)->flying_transfers_lock);
2848
2849                 if (!to_cancel)
2850                         break;
2851
2852                 usbi_dbg("cancelling transfer %p from disconnect",
2853                          USBI_TRANSFER_TO_LIBUSB_TRANSFER(to_cancel));
2854
2855                 usbi_mutex_lock(&to_cancel->lock);
2856                 usbi_backend.clear_transfer_priv(to_cancel);
2857                 usbi_mutex_unlock(&to_cancel->lock);
2858                 usbi_handle_transfer_completion(to_cancel, LIBUSB_TRANSFER_NO_DEVICE);
2859         }
2860
2861 }