Documentation touchups
[platform/upstream/libusb.git] / libusb / io.c
1 /*
2  * I/O functions for libusb
3  * Copyright (C) 2007-2008 Daniel Drake <dsd@gentoo.org>
4  * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <config.h>
22 #include <errno.h>
23 #include <poll.h>
24 #include <pthread.h>
25 #include <signal.h>
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/select.h>
30 #include <sys/time.h>
31 #include <time.h>
32 #include <unistd.h>
33
34 #include "libusbi.h"
35
36 /* this is a list of in-flight transfer handles, sorted by timeout expiration.
37  * URBs to timeout the soonest are placed at the beginning of the list, URBs
38  * that will time out later are placed after, and urbs with infinite timeout
39  * are always placed at the very end. */
40 static struct list_head flying_transfers;
41 static pthread_mutex_t flying_transfers_lock = PTHREAD_MUTEX_INITIALIZER;
42
43 /* list of poll fd's */
44 static struct list_head pollfds;
45 static pthread_mutex_t pollfds_lock = PTHREAD_MUTEX_INITIALIZER;
46
47 /* user callbacks for pollfd changes */
48 static libusb_pollfd_added_cb fd_added_cb = NULL;
49 static libusb_pollfd_removed_cb fd_removed_cb = NULL;
50
51 /**
52  * \page io Synchronous and asynchronous device I/O
53  *
54  * \section intro Introduction
55  *
56  * If you're using libusb in your application, you're probably wanting to
57  * perform I/O with devices - you want to perform USB data transfers.
58  *
59  * libusb offers two separate interfaces for device I/O. This page aims to
60  * introduce the two in order to help you decide which one is more suitable
61  * for your application. You can also choose to use both interfaces in your
62  * application by considering each transfer on a case-by-case basis.
63  *
64  * Once you have read through the following discussion, you should consult the
65  * detailed API documentation pages for the details:
66  * - \ref syncio
67  * - \ref asyncio
68  *
69  * \section theory Transfers at a logical level
70  *
71  * At a logical level, USB transfers typically happen in two parts. For
72  * example, when reading data from a endpoint:
73  * -# A request for data is sent to the device
74  * -# Some time later, the incoming data is received by the host
75  *
76  * or when writing data to an endpoint:
77  *
78  * -# The data is sent to the device
79  * -# Some time later, the host receives acknowledgement from the device that
80  *    the data has been transferred.
81  *
82  * There may be an indefinite delay between the two steps. Consider a
83  * fictional USB input device with a button that the user can press. In order
84  * to determine when the button is pressed, you would likely submit a request
85  * to read data on a bulk or interrupt endpoint and wait for data to arrive.
86  * Data will arrive when the button is pressed by the user, which is
87  * potentially hours later.
88  *
89  * libusb offers both a synchronous and an asynchronous interface to performing
90  * USB transfers. The main difference is that the synchronous interface
91  * combines both steps indicated above into a single function call, whereas
92  * the asynchronous interface separates them.
93  *
94  * \section sync The synchronous interface
95  *
96  * The synchronous I/O interface allows you to perform a USB transfer with
97  * a single function call. When the function call returns, the transfer has
98  * completed and you can parse the results.
99  *
100  * If you have used the libusb-0.1 before, this I/O style will seem familar to
101  * you. libusb-0.1 only offered a synchronous interface.
102  *
103  * In our input device example, to read button presses you might write code
104  * in the following style:
105 \code
106 unsigned char data[4];
107 int actual_length,
108 int r = libusb_bulk_transfer(handle, EP_IN, data, sizeof(data), &actual_length, 0);
109 if (r == 0 && actual_length == sizeof(data)) {
110         // results of the transaction can now be found in the data buffer
111         // parse them here and report button press
112 } else {
113         error();
114 }
115 \endcode
116  *
117  * The main advantage of this model is simplicity: you did everything with
118  * a single simple function call.
119  *
120  * However, this interface has its limitations. Your application will sleep
121  * inside libusb_bulk_transfer() until the transaction has completed. If it
122  * takes the user 3 hours to press the button, your application will be
123  * sleeping for that long. Execution will be tied up inside the library -
124  * the entire thread will be useless for that duration.
125  *
126  * Another issue is that by tieing up the thread with that single transaction
127  * there is no possibility of performing I/O with multiple endpoints and/or
128  * multiple devices simultaneously, unless you resort to creating one thread
129  * per transaction.
130  *
131  * Additionally, there is no opportunity to cancel the transfer after the
132  * request has been submitted.
133  *
134  * For details on how to use the synchronous API, see the
135  * \ref syncio "synchronous I/O API documentation" pages.
136  * 
137  * \section async The asynchronous interface
138  *
139  * Asynchronous I/O is the most significant new feature in libusb-1.0.
140  * Although it is a more complex interface, it solves all the issues detailed
141  * above.
142  *
143  * Instead of providing which functions that block until the I/O has complete,
144  * libusb's asynchronous interface presents non-blocking functions which
145  * begin a transfer and then return immediately. Your application passes a
146  * callback function pointer to this non-blocking function, which libusb will
147  * call with the results of the transaction when it has completed.
148  *
149  * Transfers which have been submitted through the non-blocking functions
150  * can be cancelled with a separate function call.
151  *
152  * The non-blocking nature of this interface allows you to be simultaneously
153  * performing I/O to multiple endpoints on multiple devices, without having
154  * to use threads.
155  *
156  * This added flexibility does come with some complications though:
157  * - In the interest of being a lightweight library, libusb does not create
158  * threads and can only operate when your application is calling into it. Your
159  * application must call into libusb from it's main loop when events are ready
160  * to be handled, or you must use some other scheme to allow libusb to
161  * undertake whatever work needs to be done.
162  * - libusb also needs to be called into at certain fixed points in time in
163  * order to accurately handle transfer timeouts.
164  * - Memory handling becomes more complex. You cannot use stack memory unless
165  * the function with that stack is guaranteed not to return until the transfer
166  * callback has finished executing.
167  * - You generally lose some linearity from your code flow because submitting
168  * the transfer request is done in a separate function from where the transfer
169  * results are handled. This becomes particularly obvious when you want to
170  * submit a second transfer based on the results of an earlier transfer.
171  *
172  * Internally, libusb's synchronous interface is expressed in terms of function
173  * calls to the asynchronous interface.
174  *
175  * For details on how to use the asynchronous API, see the
176  * \ref asyncio "asynchronous I/O API" documentation pages.
177  */
178
179 /**
180  * @defgroup asyncio Asynchronous device I/O
181  *
182  * This page details libusb's asynchronous (non-blocking) API for USB device
183  * I/O. This interface is very powerful but is also quite complex - you will
184  * need to read this page carefully to understand the necessary considerations
185  * and issues surrounding use of this interface. Simplistic applications
186  * may wish to consider the \ref syncio "synchronous I/O API" instead.
187  *
188  * The asynchronous interface is built around the idea of separating transfer
189  * submission and handling of transfer completion (the synchronous model
190  * combines both of these into one). There may be a long delay between
191  * submission and completion, however the asynchronous submission function
192  * is non-blocking so will return control to your application during that
193  * potentially long delay.
194  *
195  * \section asyncabstraction Transfer abstraction
196  *
197  * For the asynchronous I/O, libusb implements the concept of a generic
198  * transfer entity for all types of I/O (control, bulk, interrupt,
199  * isochronous). The generic transfer object must be treated slightly
200  * differently depending on which type of I/O you are performing with it.
201  *
202  * This is represented by the public libusb_transfer structure type.
203  *
204  * \section asynctrf Asynchronous transfers
205  *
206  * We can view asynchronous I/O as a 5 step process:
207  * -# Allocation
208  * -# Filling
209  * -# Submission
210  * -# Completion handling
211  * -# Deallocation
212  *
213  * \subsection asyncalloc Allocation
214  *
215  * This step involves allocating memory for a USB transfer. This is the
216  * generic transfer object mentioned above. At this stage, the transfer
217  * is "blank" with no details about what type of I/O it will be used for.
218  *
219  * Allocation is done with the libusb_alloc_transfer() function. You must use
220  * this function rather than allocating your own transfers.
221  *
222  * \subsection asyncfill Filling
223  *
224  * This step is where you take a previously allocated transfer and fill it
225  * with information to determine the message type and direction, data buffer,
226  * callback function, etc.
227  *
228  * You can either fill the required fields yourself or you can use the
229  * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer()
230  * and libusb_fill_interrupt_transfer().
231  *
232  * \subsection asyncsubmit Submission
233  *
234  * When you have allocated a transfer and filled it, you can submit it using
235  * libusb_submit_transfer(). This function returns immediately but can be
236  * regarded as firing off the I/O request in the background.
237  *
238  * \subsection asynccomplete Completion handling
239  *
240  * After a transfer has been submitted, one of four things can happen to it:
241  *
242  * - The transfer completes (i.e. some data was transferred)
243  * - The transfer has a timeout and the timeout expires before all data is
244  * transferred
245  * - The transfer fails due to an error
246  * - The transfer is cancelled
247  *
248  * Each of these will cause the user-specified transfer callback function to
249  * be invoked. It is up to the callback function to determine which of the
250  * above actually happened and to act accordingly.
251  *
252  * \subsection Deallocation
253  *
254  * When a transfer has completed (i.e. the callback function has been invoked),
255  * you are advised to free the transfer (unless you wish to resubmit it, see
256  * below). Transfers are deallocated with libusb_free_transfer().
257  *
258  * It is undefined behaviour to free a transfer which has not completed.
259  *
260  * \section asyncresubmit Resubmission
261  *
262  * You may be wondering why allocation, filling, and submission are all
263  * separated above where they could reasonably be combined into a single
264  * operation.
265  *
266  * The reason for separation is to allow you to resubmit transfers without
267  * having to allocate new ones every time. This is especially useful for
268  * common situations dealing with interrupt endpoints - you allocate one
269  * transfer, fill and submit it, and when it returns with results you just
270  * resubmit it for the next interrupt.
271  *
272  * \section asynccancel Cancellation
273  *
274  * Another advantage of using the asynchronous interface is that you have
275  * the ability to cancel transfers which have not yet completed. This is
276  * done by calling the libusb_cancel_transfer() function.
277  *
278  * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the
279  * cancellation actually completes, the transfer's callback function will
280  * be invoked, and the callback function should check the transfer status to
281  * determine that it was cancelled.
282  *
283  * Freeing the transfer after it has been cancelled but before cancellation
284  * has completed will result in undefined behaviour.
285  *
286  * \section asyncctrl Considerations for control transfers
287  *
288  * The <tt>libusb_transfer</tt> structure is generic and hence does not
289  * include specific fields for the control-specific setup packet structure.
290  *
291  * In order to perform a control transfer, you must place the 8-byte setup
292  * packet at the start of the data buffer. To simplify this, you could
293  * cast the buffer pointer to type struct libusb_control_setup, or you can
294  * use the helper function libusb_fill_control_setup().
295  *
296  * The wLength field placed in the setup packet must be the length you would
297  * expect to be sent in the setup packet: the length of the payload that
298  * follows (or the expected maximum number of bytes to receive). However,
299  * the length field of the libusb_transfer object must be the length of
300  * the data buffer - i.e. it should be wLength <em>plus</em> the size of
301  * the setup packet (LIBUSB_CONTROL_SETUP_SIZE).
302  *
303  * If you use the helper functions, this is simplified for you:
304  * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the
305  * data you are sending/requesting.
306  * -# Call libusb_fill_control_setup() on the data buffer, using the transfer
307  * request size as the wLength value (i.e. do not include the extra space you
308  * allocated for the control setup).
309  * -# If this is a host-to-device transfer, place the data to be transferred
310  * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE.
311  * -# Call libusb_fill_control_transfer() to associate the data buffer with
312  * the transfer (and to set the remaining details such as callback and timeout).
313  *   - Note that there is no parameter to set the length field of the transfer.
314  *     The length is automatically inferred from the wLength field of the setup
315  *     packet.
316  * -# Submit the transfer.
317  *
318  * Further considerations are needed when handling transfer completion in
319  * your callback function:
320  * - As you might expect, the setup packet will still be sitting at the start
321  * of the data buffer.
322  * - If this was a device-to-host transfer, the received data will be sitting
323  * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer.
324  * - The actual_length field of the transfer structure is relative to the
325  * wLength of the setup packet, rather than the size of the data buffer. So,
326  * if your wLength was 4, your transfer's <tt>length</tt> was 12, then you
327  * should expect an <tt>actual_length</tt> of 4 to indicate that the data was
328  * transferred in entirity.
329  *
330  * To simplify parsing of setup packets and obtaining the data from the
331  * correct offset, you may wish to use the libusb_control_transfer_get_data()
332  * and libusb_control_transfer_get_setup() functions within your transfer
333  * callback.
334  *
335  * \section asyncintr Considerations for interrupt transfers
336  * 
337  * All interrupt transfers are performed using the polling interval presented
338  * by the bInterval value of the endpoint descriptor.
339  *
340  * \section asynciso Considerations for isochronous transfers
341  *
342  * As isochronous transfers are more complicated than transfers to
343  * non-isochronous endpoints.
344  *
345  * To perform I/O to an isochronous endpoint, allocate the transfer by calling
346  * libusb_alloc_transfer() with an appropriate number of isochronous packets.
347  *
348  * During filling, set \ref libusb_transfer::endpoint_type "endpoint_type" to
349  * \ref libusb_endpoint_type::LIBUSB_ENDPOINT_TYPE_ISOCHRONOUS
350  * "LIBUSB_ENDPOINT_TYPE_ISOCHRONOUS", and set
351  * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than
352  * or equal to the number of packets you requested during allocation.
353  * libusb_alloc_transfer() does not set either of these fields for you, given
354  * that you might not even use the transfer on an isochronous endpoint.
355  *
356  * Next, populate the length field for the first num_iso_packets entries in
357  * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section
358  * 5.6.3 of the USB2 specifications describe how the maximum isochronous
359  * packet length is determined by the endpoint descriptor. FIXME need a helper
360  * function to find this.
361  * FIXME, write a helper function to set the length for all iso packets in an
362  * array
363  *
364  * For outgoing transfers, you'll obviously fill the buffer and populate the
365  * packet descriptors in hope that all the data gets transferred. For incoming
366  * transfers, you must ensure the buffer has sufficient capacity for
367  * the situation where all packets transfer the full amount of requested data.
368  *
369  * Completion handling requires some extra consideration. The
370  * \ref libusb_transfer::actual_length "actual_length" field of the transfer
371  * is meaningless and should not be examined; instead you must refer to the
372  * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of
373  * each individual packet.
374  *
375  * The \ref libusb_transfer::status "status" field of the transfer is also a
376  * little misleading:
377  *  - If the packets were submitted and the isochronous data microframes
378  *    completed normally, status will have value
379  *    \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED
380  *    "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred
381  *    delays are not counted as transfer errors; the transfer.status field may
382  *    indicate COMPLETED even if some or all of the packets failed. Refer to
383  *    the \ref libusb_iso_packet_descriptor::status "status" field of each
384  *    individual packet to determine packet failures.
385  *  - The status field will have value
386  *    \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR
387  *    "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered.
388  *  - Other transfer status codes occur with normal behaviour.
389  *
390  * The data for each packet will be found at an offset into the buffer that
391  * can be calculated as if each prior packet completed in full. FIXME write
392  * a helper function to determine this, and flesh this description out a bit
393  * more.
394  *
395  * \section asyncmem Memory caveats
396  *
397  * In most circumstances, it is not safe to use stack memory for transfer
398  * buffers. This is because the function that fired off the asynchronous
399  * transfer may return before libusb has finished using the buffer, and when
400  * the function returns it's stack gets destroyed. This is true for both
401  * host-to-device and device-to-host transfers.
402  *
403  * The only case in which it is safe to use stack memory is where you can
404  * guarantee that the function owning the stack space for the buffer does not
405  * return until after the transfer's callback function has completed. In every
406  * other case, you need to use heap memory instead.
407  *
408  * \section asyncflags Fine control
409  *
410  * Through using this asynchronous interface, you may find yourself repeating
411  * a few simple operations many times. You can apply a bitwise OR of certain
412  * flags to a transfer to simplify certain things:
413  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK
414  *   "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred
415  *   less than the requested amount of data being marked with status
416  *   \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR"
417  *   (they would normally be regarded as COMPLETED)
418  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
419  *   "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer
420  *   buffer when freeing the transfer.
421  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER
422  *   "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the
423  *   transfer after the transfer callback returns.
424  *
425  * \section asyncevent Event handling
426  *
427  * In accordance of the aim of being a lightweight library, libusb does not
428  * create threads internally. This means that libusb code does not execute
429  * at any time other than when your application is calling a libusb function.
430  * However, an asynchronous model requires that libusb perform work at various
431  * points in time - namely processing the results of previously-submitted
432  * transfers and invoking the user-supplied callback function.
433  *
434  * This gives rise to the libusb_handle_events() function which your
435  * application must call into when libusb has work do to. This gives libusb
436  * the opportunity to reap pending transfers, invoke callbacks, etc.
437  *
438  * The first issue to discuss here is how your application can figure out
439  * when libusb has work to do. In fact, there are two naive options which
440  * do not actually require your application to know this:
441  * -# Periodically call libusb_handle_events() in non-blocking mode at fixed
442  *    short intervals from your main loop
443  * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated
444  *    thread.
445  *
446  * The first option is plainly not very nice, and will cause unnecessary 
447  * CPU wakeups leading to increased power usage and decreased battery life.
448  * The second option is not very nice either, but may be the nicest option
449  * available to you if the "proper" approach can not be applied to your
450  * application (read on...).
451  * 
452  * The recommended option is to integrate libusb with your application main
453  * event loop. libusb exposes a set of file descriptors which allow you to do
454  * this. Your main loop is probably already calling poll() or select() or a
455  * variant on a set of file descriptors for other event sources (e.g. keyboard
456  * button presses, mouse movements, network sockets, etc). You then add
457  * libusb's file descriptors to your poll()/select() calls, and when activity
458  * is detected on such descriptors you know it is time to call
459  * libusb_handle_events().
460  *
461  * There is one final event handling complication. libusb supports
462  * asynchronous transfers which time out after a specified time period, and
463  * this requires that libusb is called into at or after the timeout so that
464  * the timeout can be handled. So, in addition to considering libusb's file
465  * descriptors in your main event loop, you must also consider that libusb
466  * sometimes needs to be called into at fixed points in time even when there
467  * is no file descriptor activity.
468  *
469  * For the details on retrieving the set of file descriptors and determining
470  * the next timeout, see the \ref poll "polling and timing" API documentation.
471  */
472
473 /**
474  * @defgroup poll Polling and timing
475  *
476  * This page documents libusb's functions for polling events and timing.
477  * These functions are only necessary for users of the
478  * \ref asyncio "asynchronous API". If you are only using the simpler
479  * \ref syncio "synchronous API" then you do not need to ever call these
480  * functions.
481  *
482  * The justification for the functionality described here has already been
483  * discussed in the \ref asyncevent "event handling" section of the
484  * asynchronous API documentation. In summary, libusb does not create internal
485  * threads for event processing and hence relies on your application calling
486  * into libusb at certain points in time so that pending events can be handled.
487  * In order to know precisely when libusb needs to be called into, libusb
488  * offers you a set of pollable file descriptors and information about when
489  * the next timeout expires.
490  *
491  * If you are using the asynchronous I/O API, you must take one of the two
492  * following options, otherwise your I/O will not complete.
493  *
494  * \section pollsimple The simple option
495  *
496  * If your application revolves solely around libusb and does not need to
497  * handle other event sources, you can have a program structure as follows:
498 \code
499 // initialize libusb
500 // find and open device
501 // maybe fire off some initial async I/O
502
503 while (user_has_not_requested_exit)
504         libusb_handle_events();
505
506 // clean up and exit
507 \endcode
508  *
509  * With such a simple main loop, you do not have to worry about managing
510  * sets of file descriptors or handling timeouts. libusb_handle_events() will
511  * handle those details internally.
512  *
513  * \section pollmain The more advanced option
514  *
515  * In more advanced applications, you will already have a main loop which
516  * is monitoring other event sources: network sockets, X11 events, mouse
517  * movements, etc. Through exposing a set of file descriptors, libusb is
518  * designed to cleanly integrate into such main loops.
519  *
520  * In addition to polling file descriptors for the other event sources, you
521  * take a set of file descriptors from libusb and monitor those too. When you
522  * detect activity on libusb's file descriptors, you call
523  * libusb_handle_events_timeout() in non-blocking mode.
524  *
525  * You must also consider the fact that libusb sometimes has to handle events
526  * at certain known times which do not generate activity on file descriptors.
527  * Your main loop must also consider these times, modify it's poll()/select()
528  * timeout accordingly, and track time so that libusb_handle_events_timeout()
529  * is called in non-blocking mode when timeouts expire.
530  *
531  * In pseudo-code, you want something that looks like:
532 \code
533 // initialise libusb
534
535 libusb_get_pollfds()
536 while (user has not requested application exit) {
537         libusb_get_next_timeout();
538         select(on libusb file descriptors plus any other event sources of interest,
539                 using a timeout no larger than the value libusb just suggested)
540         if (select() indicated activity on libusb file descriptors)
541                 libusb_handle_events_timeout(0);
542         if (time has elapsed to or beyond the libusb timeout)
543                 libusb_handle_events_timeout(0);
544 }
545
546 // clean up and exit
547 \endcode
548  *
549  * The set of file descriptors that libusb uses as event sources may change
550  * during the life of your application. Rather than having to repeatedly
551  * call libusb_get_pollfds(), you can set up notification functions for when
552  * the file descriptor set changes using libusb_set_pollfd_notifiers().
553  *
554  */
555
556 void usbi_io_init()
557 {
558         list_init(&flying_transfers);
559         list_init(&pollfds);
560         fd_added_cb = NULL;
561         fd_removed_cb = NULL;
562 }
563
564 static int calculate_timeout(struct usbi_transfer *transfer)
565 {
566         int r;
567         struct timespec current_time;
568         unsigned int timeout =
569                 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout;
570
571         if (!timeout)
572                 return 0;
573
574         r = clock_gettime(CLOCK_MONOTONIC, &current_time);
575         if (r < 0) {
576                 usbi_err("failed to read monotonic clock, errno=%d", errno);
577                 return r;
578         }
579
580         current_time.tv_sec += timeout / 1000;
581         current_time.tv_nsec += (timeout % 1000) * 1000000;
582
583         if (current_time.tv_nsec > 1000000000) {
584                 current_time.tv_nsec -= 1000000000;
585                 current_time.tv_sec++;
586         }
587
588         TIMESPEC_TO_TIMEVAL(&transfer->timeout, &current_time);
589         return 0;
590 }
591
592 static void add_to_flying_list(struct usbi_transfer *transfer)
593 {
594         struct usbi_transfer *cur;
595         struct timeval *timeout = &transfer->timeout;
596         
597         pthread_mutex_lock(&flying_transfers_lock);
598
599         /* if we have no other flying transfers, start the list with this one */
600         if (list_empty(&flying_transfers)) {
601                 list_add(&transfer->list, &flying_transfers);
602                 goto out;
603         }
604
605         /* if we have infinite timeout, append to end of list */
606         if (!timerisset(timeout)) {
607                 list_add_tail(&transfer->list, &flying_transfers);
608                 goto out;
609         }
610
611         /* otherwise, find appropriate place in list */
612         list_for_each_entry(cur, &flying_transfers, list) {
613                 /* find first timeout that occurs after the transfer in question */
614                 struct timeval *cur_tv = &cur->timeout;
615
616                 if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
617                                 (cur_tv->tv_sec == timeout->tv_sec &&
618                                         cur_tv->tv_usec > timeout->tv_usec)) {
619                         list_add_tail(&transfer->list, &cur->list);
620                         goto out;
621                 }
622         }
623
624         /* otherwise we need to be inserted at the end */
625         list_add_tail(&transfer->list, &flying_transfers);
626 out:
627         pthread_mutex_unlock(&flying_transfers_lock);
628 }
629
630 static int submit_transfer(struct usbi_transfer *itransfer)
631 {
632         int r;
633         
634         add_to_flying_list(itransfer);
635         r = usbi_backend->submit_transfer(itransfer);
636         if (r < 0)
637                 list_del(&itransfer->list);
638
639         return r;
640 }
641
642 /** \ingroup asyncio
643  * Allocate a libusb transfer with a specified number of isochronous packet
644  * descriptors. The returned transfer is pre-initialized for you. When the new
645  * transfer is no longer needed, it should be freed with
646  * libusb_free_transfer().
647  *
648  * Transfers intended for non-isochronous endpoints (e.g. control, bulk,
649  * interrupt) should specify an iso_packets count of zero.
650  *
651  * For transfers intended for isochronous endpoints, specify an appropriate
652  * number of packet descriptors to be allocated as part of the transfer.
653  * The returned transfer is not specially initialized for isochronous I/O;
654  * you are still required to set the
655  * \ref libusb_transfer::num_iso_packets "num_iso_packets" and
656  * \ref libusb_transfer::endpoint_type "endpoint_type" fields accordingly.
657  *
658  * It is safe to allocate a transfer with some isochronous packets and then
659  * use it on a non-isochronous endpoint. If you do this, ensure that at time
660  * of submission, num_iso_packets is 0 and that endpoint_type is set
661  * appropriately.
662  *
663  * \param iso_packets number of isochronous packet descriptors to allocate
664  * \returns a newly allocated transfer, or NULL on error
665  */
666 API_EXPORTED struct libusb_transfer *libusb_alloc_transfer(int iso_packets)
667 {
668         size_t os_alloc_size = usbi_backend->transfer_priv_size
669                 + (usbi_backend->add_iso_packet_size * iso_packets);
670         int alloc_size = sizeof(struct usbi_transfer)
671                 + sizeof(struct libusb_transfer)
672                 + (sizeof(struct libusb_iso_packet_descriptor) * iso_packets)
673                 + os_alloc_size;
674         struct usbi_transfer *itransfer = malloc(alloc_size);
675         if (!itransfer)
676                 return NULL;
677
678         memset(itransfer, 0, alloc_size);
679         itransfer->num_iso_packets = iso_packets;
680         return __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
681 }
682
683 /** \ingroup asyncio
684  * Free a transfer structure. This should be called for all transfers
685  * allocated with libusb_alloc_transfer().
686  *
687  * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
688  * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is
689  * non-NULL, this function will also free the transfer buffer using the
690  * standard system memory allocator (e.g. free()).
691  *
692  * It is legal to call this function with a NULL transfer. In this case,
693  * the function will simply return safely.
694  *
695  * \param transfer the transfer to free
696  */
697 API_EXPORTED void libusb_free_transfer(struct libusb_transfer *transfer)
698 {
699         struct usbi_transfer *itransfer;
700         if (!transfer)
701                 return;
702
703         if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)
704                 free(transfer->buffer);
705
706         itransfer = __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
707         free(itransfer);
708 }
709
710 /** \ingroup asyncio
711  * Submit a transfer. This function will fire off the USB transfer and then
712  * return immediately.
713  *
714  * It is undefined behaviour to submit a transfer that has already been
715  * submitted but has not yet completed.
716  *
717  * \param transfer the transfer to submit
718  * \returns 0 on success
719  * \returns negative on error
720  */
721 API_EXPORTED int libusb_submit_transfer(struct libusb_transfer *transfer)
722 {
723         struct usbi_transfer *itransfer =
724                 __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
725         int r;
726
727         itransfer->transferred = 0;
728         r = calculate_timeout(itransfer);
729         if (r < 0)
730                 return r;
731
732         if (transfer->endpoint_type == LIBUSB_ENDPOINT_TYPE_CONTROL) {
733                 struct libusb_control_setup *setup =
734                         (struct libusb_control_setup *) transfer->buffer;
735         
736                 usbi_dbg("RQT=%02x RQ=%02x VAL=%04x IDX=%04x length=%d",
737                         setup->bmRequestType, setup->bRequest, setup->wValue, setup->wIndex,
738                         setup->wLength);
739
740                 setup->wValue = cpu_to_le16(setup->wValue);
741                 setup->wIndex = cpu_to_le16(setup->wIndex);
742                 setup->wLength = cpu_to_le16(setup->wLength);
743         }
744
745         return submit_transfer(itransfer);
746 }
747
748 /** \ingroup asyncio
749  * Asynchronously cancel a previously submitted transfer.
750  * It is undefined behaviour to call this function on a transfer that is
751  * already being cancelled or has already completed.
752  * This function returns immediately, but this does not indicate cancellation
753  * is complete. Your callback function will be invoked at some later time
754  * with a transfer status of
755  * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED
756  * "LIBUSB_TRANSFER_CANCELLED."
757  *
758  * \param transfer the transfer to cancel
759  * \returns 0 on success
760  * \returns non-zero on error
761  */
762 API_EXPORTED int libusb_cancel_transfer(struct libusb_transfer *transfer)
763 {
764         struct usbi_transfer *itransfer =
765                 __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
766         int r;
767
768         usbi_dbg("");
769         r = usbi_backend->cancel_transfer(itransfer);
770         if (r < 0)
771                 usbi_err("cancel transfer failed error %d", r);
772         return r;
773 }
774
775 /** \ingroup asyncio
776  * Cancel a transfer and wait for cancellation completion without invoking
777  * the transfer callback. This function will block. 
778  *
779  * It is undefined behaviour to call this function on a transfer that is
780  * already being cancelled or has already completed.
781  *
782  * \param transfer the transfer to cancel
783  * \returns 0 on success
784  * \returns non-zero on error
785  */
786 API_EXPORTED int libusb_cancel_transfer_sync(struct libusb_transfer *transfer)
787 {
788         struct usbi_transfer *itransfer =
789                 __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
790         int r;
791
792         usbi_dbg("");
793         r = usbi_backend->cancel_transfer(itransfer);
794         if (r < 0) {
795                 usbi_err("cancel transfer failed error %d", r);
796                 return r;
797         }
798
799         itransfer->flags |= USBI_TRANSFER_SYNC_CANCELLED;
800         while (itransfer->flags & USBI_TRANSFER_SYNC_CANCELLED) {
801                 r = libusb_handle_events();
802                 if (r < 0)
803                         return r;
804         }
805
806         return 0;
807 }
808
809 void usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
810         enum libusb_transfer_status status)
811 {
812         struct libusb_transfer *transfer =
813                 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
814         uint8_t flags;
815
816         pthread_mutex_lock(&flying_transfers_lock);
817         list_del(&itransfer->list);
818         pthread_mutex_unlock(&flying_transfers_lock);
819
820         if (status == LIBUSB_TRANSFER_SILENT_COMPLETION)
821                 return;
822
823         if (status == LIBUSB_TRANSFER_COMPLETED
824                         && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
825                 int rqlen = transfer->length;
826                 if (transfer->endpoint_type == LIBUSB_ENDPOINT_TYPE_CONTROL)
827                         rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
828                 if (rqlen != itransfer->transferred) {
829                         usbi_dbg("interpreting short transfer as error");
830                         status = LIBUSB_TRANSFER_ERROR;
831                 }
832         }
833
834         flags = transfer->flags;
835         transfer->status = status;
836         transfer->actual_length = itransfer->transferred;
837         if (transfer->callback)
838                 transfer->callback(transfer);
839         /* transfer might have been freed by the above call, do not use from
840          * this point. */
841         if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
842                 libusb_free_transfer(transfer);
843 }
844
845 void usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
846 {
847         /* if the URB is being cancelled synchronously, raise cancellation
848          * completion event by unsetting flag, and ensure that user callback does
849          * not get called.
850          */
851         if (transfer->flags & USBI_TRANSFER_SYNC_CANCELLED) {
852                 transfer->flags &= ~USBI_TRANSFER_SYNC_CANCELLED;
853                 usbi_dbg("detected sync. cancel");
854                 usbi_handle_transfer_completion(transfer,
855                         LIBUSB_TRANSFER_SILENT_COMPLETION);
856                 return;
857         }
858
859         /* if the URB was cancelled due to timeout, report timeout to the user */
860         if (transfer->flags & USBI_TRANSFER_TIMED_OUT) {
861                 usbi_dbg("detected timeout cancellation");
862                 usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT);
863                 return;
864         }
865
866         /* otherwise its a normal async cancel */
867         usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
868 }
869
870 static void handle_timeout(struct usbi_transfer *itransfer)
871 {
872         struct libusb_transfer *transfer =
873                 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
874         int r;
875
876         itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
877         r = libusb_cancel_transfer(transfer);
878         if (r < 0)
879                 usbi_warn("async cancel failed %d errno=%d", r, errno);
880 }
881
882 static int handle_timeouts(void)
883 {
884         struct timespec systime_ts;
885         struct timeval systime;
886         struct usbi_transfer *transfer;
887         int r = 0;
888
889         pthread_mutex_lock(&flying_transfers_lock);
890         if (list_empty(&flying_transfers))
891                 goto out;
892
893         /* get current time */
894         r = clock_gettime(CLOCK_MONOTONIC, &systime_ts);
895         if (r < 0)
896                 goto out;
897
898         TIMESPEC_TO_TIMEVAL(&systime, &systime_ts);
899
900         /* iterate through flying transfers list, finding all transfers that
901          * have expired timeouts */
902         list_for_each_entry(transfer, &flying_transfers, list) {
903                 struct timeval *cur_tv = &transfer->timeout;
904
905                 /* if we've reached transfers of infinite timeout, we're all done */
906                 if (!timerisset(cur_tv))
907                         goto out;
908
909                 /* ignore timeouts we've already handled */
910                 if (transfer->flags & USBI_TRANSFER_TIMED_OUT)
911                         continue;
912
913                 /* if transfer has non-expired timeout, nothing more to do */
914                 if ((cur_tv->tv_sec > systime.tv_sec) ||
915                                 (cur_tv->tv_sec == systime.tv_sec &&
916                                         cur_tv->tv_usec > systime.tv_usec))
917                         goto out;
918         
919                 /* otherwise, we've got an expired timeout to handle */
920                 handle_timeout(transfer);
921         }
922
923 out:
924         pthread_mutex_unlock(&flying_transfers_lock);
925         return r;
926 }
927
928 static int handle_events(struct timeval *tv)
929 {
930         int r;
931         int maxfd = 0;
932         fd_set readfds, writefds;
933         fd_set *_readfds = NULL;
934         fd_set *_writefds = NULL;
935         struct usbi_pollfd *ipollfd;
936         int have_readfds = 0;
937         int have_writefds = 0;
938         struct timeval select_timeout;
939         struct timeval timeout;
940
941         r = libusb_get_next_timeout(&timeout);
942         if (r) {
943                 /* timeout already expired? */
944                 if (!timerisset(&timeout))
945                         return handle_timeouts();
946
947                 /* choose the smallest of next URB timeout or user specified timeout */
948                 if (timercmp(&timeout, tv, <))
949                         select_timeout = timeout;
950                 else
951                         select_timeout = *tv;
952         } else {
953                 select_timeout = *tv;
954         }
955
956         FD_ZERO(&readfds);
957         FD_ZERO(&writefds);
958         pthread_mutex_lock(&pollfds_lock);
959         list_for_each_entry(ipollfd, &pollfds, list) {
960                 struct libusb_pollfd *pollfd = &ipollfd->pollfd;
961                 int fd = pollfd->fd;
962                 if (pollfd->events & POLLIN) {
963                         have_readfds = 1;
964                         FD_SET(fd, &readfds);
965                 }
966                 if (pollfd->events & POLLOUT) {
967                         have_writefds = 1;
968                         FD_SET(fd, &writefds);
969                 }
970                 if (fd > maxfd)
971                         maxfd = fd;
972         }
973         pthread_mutex_unlock(&pollfds_lock);
974
975         if (have_readfds)
976                 _readfds = &readfds;
977         if (have_writefds)
978                 _writefds = &writefds;
979
980         usbi_dbg("select() with timeout in %d.%06ds", select_timeout.tv_sec,
981                 select_timeout.tv_usec);
982         r = select(maxfd + 1, _readfds, _writefds, NULL, &select_timeout);
983         usbi_dbg("select() returned %d with %d.%06ds remaining",
984                 r, select_timeout.tv_sec, select_timeout.tv_usec);
985         if (r == 0) {
986                 *tv = select_timeout;
987                 return handle_timeouts();
988         } else if (r == -1 && errno == EINTR) {
989                 return 0;
990         } else if (r < 0) {
991                 usbi_err("select failed %d err=%d\n", r, errno);
992                 return r;
993         }
994
995         r = usbi_backend->handle_events(_readfds, _writefds);
996         if (r < 0)
997                 return r;
998
999         /* FIXME check return value? */
1000         return handle_timeouts();
1001 }
1002
1003 /** \ingroup poll
1004  * Handle any pending events.
1005  *
1006  * libusb determines "pending events" by checking if any timeouts have expired
1007  * and by checking the set of file descriptors for activity.
1008  *
1009  * If a zero timeval is passed, this function will handle any already-pending
1010  * events and then immediately return in non-blocking style.
1011  *
1012  * If a non-zero timeval is passed and no events are currently pending, this
1013  * function will block waiting for events to handle up until the specified
1014  * timeout. If an event arrives or a signal is raised, this function will
1015  * return early.
1016  *
1017  * \param tv the maximum time to block waiting for events, or zero for
1018  * non-blocking mode
1019  * \returns 0 on success
1020  * \returns non-zero on error
1021  */
1022 API_EXPORTED int libusb_handle_events_timeout(struct timeval *tv)
1023 {
1024         return handle_events(tv);
1025 }
1026
1027 /** \ingroup poll
1028  * Handle any pending events in blocking mode with a sensible timeout. This
1029  * timeout is currently hardcoded at 2 seconds but we may change this if we
1030  * decide other values are more sensible. For finer control over whether this
1031  * function is blocking or non-blocking, or the maximum timeout, use
1032  * libusb_handle_events_timeout() instead.
1033  *
1034  * \returns 0 on success
1035  * \returns non-zero on error
1036  */
1037 API_EXPORTED int libusb_handle_events(void)
1038 {
1039         struct timeval tv;
1040         tv.tv_sec = 2;
1041         tv.tv_usec = 0;
1042         return handle_events(&tv);
1043 }
1044
1045 /** \ingroup poll
1046  * Determine the next internal timeout that libusb needs to handle. You only
1047  * need to use this function if you are calling poll() or select() or similar
1048  * on libusb's file descriptors yourself - you do not need to use it if you
1049  * are calling libusb_handle_events() or a variant directly.
1050  * 
1051  * You should call this function in your main loop in order to determine how
1052  * long to wait for select() or poll() to return results. libusb needs to be
1053  * called into at this timeout, so you should use it as an upper bound on
1054  * your select() or poll() call.
1055  *
1056  * When the timeout has expired, call into libusb_handle_events_timeout()
1057  * (perhaps in non-blocking mode) so that libusb can handle the timeout.
1058  *
1059  * This function may return 0 (success) and an all-zero timeval. If this is
1060  * the case, it indicates that libusb has a timeout that has already expired
1061  * so you should call libusb_handle_events_timeout() or similar immediately.
1062  *
1063  * \param tv output location for a relative time against the current
1064  * clock in which libusb must be called into in order to process timeout events
1065  * \returns 0 on success
1066  * \returns non-zero on error
1067  */
1068 API_EXPORTED int libusb_get_next_timeout(struct timeval *tv)
1069 {
1070         struct usbi_transfer *transfer;
1071         struct timespec cur_ts;
1072         struct timeval cur_tv;
1073         struct timeval *next_timeout;
1074         int r;
1075         int found = 0;
1076
1077         pthread_mutex_lock(&flying_transfers_lock);
1078         if (list_empty(&flying_transfers)) {
1079                 pthread_mutex_unlock(&flying_transfers_lock);
1080                 usbi_dbg("no URBs, no timeout!");
1081                 return 0;
1082         }
1083
1084         /* find next transfer which hasn't already been processed as timed out */
1085         list_for_each_entry(transfer, &flying_transfers, list) {
1086                 if (!(transfer->flags & USBI_TRANSFER_TIMED_OUT)) {
1087                         found = 1;
1088                         break;
1089                 }
1090         }
1091         pthread_mutex_unlock(&flying_transfers_lock);
1092
1093         if (!found) {
1094                 usbi_dbg("all URBs have already been processed for timeouts");
1095                 return 0;
1096         }
1097
1098         next_timeout = &transfer->timeout;
1099
1100         /* no timeout for next transfer */
1101         if (!timerisset(next_timeout)) {
1102                 usbi_dbg("no URBs with timeouts, no timeout!");
1103                 return 0;
1104         }
1105
1106         r = clock_gettime(CLOCK_MONOTONIC, &cur_ts);
1107         if (r < 0) {
1108                 usbi_err("failed to read monotonic clock, errno=%d", errno);
1109                 return r;
1110         }
1111         TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts);
1112
1113         if (timercmp(&cur_tv, next_timeout, >=)) {
1114                 usbi_dbg("first timeout already expired");
1115                 timerclear(tv);
1116         } else {
1117                 timersub(next_timeout, &cur_tv, tv);
1118                 usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec);
1119         }
1120
1121         return 1;
1122 }
1123
1124 /** \ingroup poll
1125  * Register notification functions for file descriptor additions/removals.
1126  * These functions will be invoked for every new or removed file descriptor
1127  * that libusb uses as an event source.
1128  *
1129  * To remove notifiers, pass NULL values for the function pointers.
1130  *
1131  * \param added_cb pointer to function for addition notifications
1132  * \param removed_cb pointer to function for removal notifications
1133  */
1134 API_EXPORTED void libusb_set_pollfd_notifiers(libusb_pollfd_added_cb added_cb,
1135         libusb_pollfd_removed_cb removed_cb)
1136 {
1137         fd_added_cb = added_cb;
1138         fd_removed_cb = removed_cb;
1139 }
1140
1141 int usbi_add_pollfd(int fd, short events)
1142 {
1143         struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
1144         if (!ipollfd)
1145                 return -ENOMEM;
1146
1147         usbi_dbg("add fd %d events %d", fd, events);
1148         ipollfd->pollfd.fd = fd;
1149         ipollfd->pollfd.events = events;
1150         pthread_mutex_lock(&pollfds_lock);
1151         list_add(&ipollfd->list, &pollfds);
1152         pthread_mutex_unlock(&pollfds_lock);
1153
1154         if (fd_added_cb)
1155                 fd_added_cb(fd, events);
1156         return 0;
1157 }
1158
1159 void usbi_remove_pollfd(int fd)
1160 {
1161         struct usbi_pollfd *ipollfd;
1162         int found = 0;
1163
1164         usbi_dbg("remove fd %d", fd);
1165         pthread_mutex_lock(&pollfds_lock);
1166         list_for_each_entry(ipollfd, &pollfds, list)
1167                 if (ipollfd->pollfd.fd == fd) {
1168                         found = 1;
1169                         break;
1170                 }
1171
1172         if (!found) {
1173                 usbi_err("couldn't find fd %d to remove", fd);
1174                 pthread_mutex_unlock(&pollfds_lock);
1175                 return;
1176         }
1177
1178         list_del(&ipollfd->list);
1179         pthread_mutex_unlock(&pollfds_lock);
1180         free(ipollfd);
1181         if (fd_removed_cb)
1182                 fd_removed_cb(fd);
1183 }
1184
1185 /** \ingroup poll
1186  * Retrieve a list of file descriptors that should be polled by your main loop
1187  * as libusb event sources.
1188  *
1189  * The returned list is NULL-terminated and should be freed with free() when
1190  * done. The actual list contents must not be touched.
1191  *
1192  * \returns a NULL-terminated list of libusb_pollfd structures, or NULL on
1193  * error
1194  */
1195 API_EXPORTED const struct libusb_pollfd **libusb_get_pollfds(void)
1196 {
1197         struct libusb_pollfd **ret = NULL;
1198         struct usbi_pollfd *ipollfd;
1199         size_t i = 0;
1200         size_t cnt = 0;
1201
1202         pthread_mutex_lock(&pollfds_lock);
1203         list_for_each_entry(ipollfd, &pollfds, list)
1204                 cnt++;
1205
1206         ret = calloc(cnt + 1, sizeof(struct libusb_pollfd *));
1207         if (!ret)
1208                 goto out;
1209
1210         list_for_each_entry(ipollfd, &pollfds, list)
1211                 ret[i++] = (struct libusb_pollfd *) ipollfd;
1212         ret[cnt] = NULL;
1213
1214 out:
1215         pthread_mutex_unlock(&pollfds_lock);
1216         return (const struct libusb_pollfd **) ret;
1217 }
1218