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