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