7900603902c9ca5b5bcc0ef75f170a09eeea3f4b
[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 #define TRANSFER_TO_PRIV(trf) (container_of((trf), struct usbi_transfer, pub))
36
37 /* this is a list of in-flight rb_handles, sorted by timeout expiration.
38  * URBs to timeout the soonest are placed at the beginning of the list, URBs
39  * that will time out later are placed after, and urbs with infinite timeout
40  * are always placed at the very end. */
41 static struct list_head flying_transfers;
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. It is also
219  * possible to allocate your own libusb_transfer structure, but only if you
220  * take the following into account:
221  * -# For implementation reasons, the memory allocated for the transfer must
222  * actually be larger than sizeof(struct libusb_transfer). If you wish to
223  * allocate your own transfers, you must allocate them with the size
224  * determined by libusb_get_transfer_alloc_size().
225  * -# After allocating space for a transfer, you must initialize it with
226  * libusb_init_transfer().
227  *
228  * \subsection asyncfill Filling
229  *
230  * This step is where you take a previously allocated transfer and fill it
231  * with information to determine the message type and direction, data buffer,
232  * callback function, etc.
233  *
234  * You can either fill the required fields yourself or you can use the
235  * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer()
236  * and libusb_fill_interrupt_transfer().
237  *
238  * \subsection asyncsubmit Submission
239  *
240  * When you have allocated a transfer and filled it, you can submit it using
241  * libusb_submit_transfer(). This function returns immediately but can be
242  * regarded as firing off the I/O request in the background.
243  *
244  * \subsection asynccomplete Completion handling
245  *
246  * After a transfer has been submitted, one of four things can happen to it:
247  *
248  * - The transfer completes (i.e. some data was transferred)
249  * - The transfer has a timeout and the timeout expires before all data is
250  * transferred
251  * - The transfer fails due to an error
252  * - The transfer is cancelled
253  *
254  * Each of these will cause the user-specified transfer callback function to
255  * be invoked. It is up to the callback function to determine which of the
256  * above actually happened and to act accordingly.
257  *
258  * \subsection Deallocation
259  *
260  * When a transfer has completed (i.e. the callback function has been invoked),
261  * you are advised to free the transfer (unless you wish to resubmit it, see
262  * below).
263  *
264  * If you allocated the transfer with libusb_alloc_transfer(), deallocate it
265  * with libusb_free_transfer(). If you're using your own memory management
266  * scheme, free it through your scheme.
267  *
268  * It is undefined behaviour to free a transfer which has not completed.
269  *
270  * \section asyncresubmit Resubmission
271  *
272  * You may be wondering why allocation, filling, and submission are all
273  * separated above where they could reasonably be combined into a single
274  * operation.
275  *
276  * The reason for separation is to allow you to resubmit transfers without
277  * having to allocate new ones every time. This is especially useful for
278  * common situations dealing with interrupt endpoints - you allocate one
279  * transfer, fill and submit it, and when it returns with results you just
280  * resubmit it for the next interrupt.
281  *
282  * \section asynccancel Cancellation
283  *
284  * Another advantage of using the asynchronous interface is that you have
285  * the ability to cancel transfers which have not yet completed. This is
286  * done by calling the libusb_cancel_transfer() function.
287  *
288  * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the
289  * cancellation actually completes, the transfer's callback function will
290  * be invoked, and the callback function should check the transfer status to
291  * determine that it was cancelled.
292  *
293  * Freeing the transfer after it has been cancelled but before cancellation
294  * has completed will result in undefined behaviour.
295  *
296  * \section asyncctrl Considerations for control transfers
297  *
298  * The <tt>libusb_transfer</tt> structure is generic and hence does not
299  * include specific fields for the control-specific setup packet structure.
300  *
301  * In order to perform a control transfer, you must place the 8-byte setup
302  * packet at the start of the data buffer. To simplify this, you could
303  * cast the buffer pointer to type struct libusb_control_setup, or you can
304  * use the helper function libusb_fill_control_setup().
305  *
306  * The wLength field placed in the setup packet must be the length you would
307  * expect to be sent in the setup packet: the length of the payload that
308  * follows (or the expected maximum number of bytes to receive). However,
309  * the length field of the libusb_transfer object must be the length of
310  * the data buffer - i.e. it should be wLength <em>plus</em> the size of
311  * the setup packet (LIBUSB_CONTROL_SETUP_SIZE).
312  *
313  * If you use the helper functions, this is simplified for you:
314  * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the
315  * data you are sending/requesting.
316  * -# Call libusb_fill_control_setup() on the data buffer, using the transfer
317  * request size as the wLength value (i.e. do not include the extra space you
318  * allocated for the control setup).
319  * -# If this is a host-to-device transfer, place the data to be transferred
320  * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE.
321  * -# Call libusb_fill_control_transfer() to associate the data buffer with
322  * the transfer (and to set the remaining details such as callback and timeout).
323  *   - Note that there is no parameter to set the length field of the transfer.
324  *     The length is automatically inferred from the wLength field of the setup
325  *     packet.
326  * -# Submit the transfer.
327  *
328  * Further considerations are needed when handling transfer completion in
329  * your callback function:
330  * - As you might expect, the setup packet will still be sitting at the start
331  * of the data buffer.
332  * - If this was a device-to-host transfer, the received data will be sitting
333  * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer.
334  * - The actual_length field of the transfer structure is relative to the
335  * wLength of the setup packet, rather than the size of the data buffer. So,
336  * if your wLength was 4, your transfer's <tt>length</tt> was 12, then you
337  * should expect an <tt>actual_length</tt> of 4 to indicate that the data was
338  * transferred in entirity.
339  *
340  * To simplify parsing of setup packets and obtaining the data from the
341  * correct offset, you may wish to use the libusb_control_transfer_get_data()
342  * and libusb_control_transfer_get_setup() functions within your transfer
343  * callback.
344  *
345  * \section asyncmem Memory caveats
346  *
347  * In most circumstances, it is not safe to use stack memory for transfer
348  * buffers. This is because the function that fired off the asynchronous
349  * transfer may return before libusb has finished using the buffer, and when
350  * the function returns it's stack gets destroyed. This is true for both
351  * host-to-device and device-to-host transfers.
352  *
353  * The only case in which it is safe to use stack memory is where you can
354  * guarantee that the function owning the stack space for the buffer does not
355  * return until after the transfer's callback function has completed. In every
356  * other case, you need to use heap memory instead.
357  *
358  * \section asyncflags Fine control
359  *
360  * Through using this asynchronous interface, you may find yourself repeating
361  * a few simple operations many times. You can apply a bitwise OR of certain
362  * flags to a transfer to simplify certain things:
363  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK
364  *   "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred
365  *   less than the requested amount of data being marked with status
366  *   \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR"
367  *   (they would normally be regarded as COMPLETED)
368  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
369  *   "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer
370  *   buffer when freeing the transfer.
371  * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER
372  *   "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the
373  *   transfer after the transfer callback returns.
374  *
375  * \section asyncevent Event handling
376  *
377  * In accordance of the aim of being a lightweight library, libusb does not
378  * create threads internally. This means that libusb code does not execute
379  * at any time other than when your application is calling a libusb function.
380  * However, an asynchronous model requires that libusb perform work at various
381  * points in time - namely processing the results of previously-submitted
382  * transfers and invoking the user-supplied callback function.
383  *
384  * This gives rise to the libusb_poll() function which your
385  * application must call into when libusb has work do to. This gives libusb
386  * the opportunity to reap pending transfers, invoke callbacks, etc.
387  *
388  * The first issue to discuss here is how your application can figure out
389  * when libusb has work to do. In fact, there are two naive options which
390  * do not actually require your application to know this:
391  * -# Periodically call libusb_poll() in non-blocking mode at fixed short
392  *  intervals from your main loop
393  * -# Repeatedly call libusb_poll() in blocking mode from a dedicated thread.
394  *
395  * The first option is plainly not very nice, and will cause unnecessary 
396  * CPU wakeups leading to increased power usage and decreased battery life.
397  * The second option is not very nice either, but may be the nicest option
398  * available to you if the "proper" approach can not be applied to your
399  * application (read on...).
400  * 
401  * The recommended option is to integrate libusb with your application main
402  * event loop. libusb exposes a set of file descriptors which allow you to do
403  * this. Your main loop is probably already calling poll() or select() or a
404  * variant on a set of file descriptors for other event sources (e.g. keyboard
405  * button presses, mouse movements, network sockets, etc). You then add
406  * libusb's file descriptors to your poll()/select() calls, and when activity
407  * is detected on such descriptors you know it is time to call
408  * libusb_poll().
409  *
410  * There is one final event handling complication. libusb supports
411  * asynchronous transfers which time out after a specified time period, and
412  * this requires that libusb is called into at or after the timeout so that
413  * the timeout can be handled. So, in addition to considering libusb's file
414  * descriptors in your main event loop, you must also consider that libusb
415  * sometimes needs to be called into at fixed points in time even when there
416  * is no file descriptor activity.
417  *
418  * For the details on retrieving the set of file descriptors and determining
419  * the next timeout, see the \ref poll "polling and timing" API documentation.
420  */
421
422 /**
423  * @defgroup poll Polling and timing
424  *
425  * This page documents libusb's functions for polling events and timing.
426  * These functions are only necessary for users of the
427  * \ref asyncio "asynchronous API". If you are only using the simpler
428  * \ref syncio "synchronous API" then you do not need to ever call these
429  * functions.
430  *
431  * The justification for the functionality described here has already been
432  * discussed in the \ref asyncevent "event handling" section of the
433  * asynchronous API documentation. In summary, libusb does not create internal
434  * threads for event processing and hence relies on your application calling
435  * into libusb at certain points in time so that pending events can be handled.
436  * In order to know precisely when libusb needs to be called into, libusb
437  * offers you a set of pollable file descriptors and information about when
438  * the next timeout expires.
439  *
440  * If you are using the asynchronous I/O API, you must take one of the two
441  * following options, otherwise your I/O will not complete.
442  *
443  * \section pollsimple The simple option
444  *
445  * If your application revolves solely around libusb and does not need to
446  * handle other event sources, you can have a program structure as follows:
447 \code
448 // initialize libusb
449 // find and open device
450 // maybe fire off some initial async I/O
451
452 while (user_has_not_requested_exit)
453         libusb_poll();
454
455 // clean up and exit
456 \endcode
457  *
458  * With such a simple main loop, you do not have to worry about managing
459  * sets of file descriptors or handling timeouts. libusb_poll() will handle
460  * those details internally.
461  *
462  * \section pollmain The more advanced option
463  *
464  * In more advanced applications, you will already have a main loop which
465  * is monitoring other event sources: network sockets, X11 events, mouse
466  * movements, etc. Through exposing a set of file descriptors, libusb is
467  * designed to cleanly integrate into such main loops.
468  *
469  * In addition to polling file descriptors for the other event sources, you
470  * take a set of file descriptors from libusb and monitor those too. When you
471  * detect activity on libusb's file descriptors, you call libusb_poll_timeout()
472  * in non-blocking mode.
473  *
474  * You must also consider the fact that libusb sometimes has to handle events
475  * at certain known times which do not generate activity on file descriptors.
476  * Your main loop must also consider these times, modify it's poll()/select()
477  * timeout accordingly, and track time so that libusb_poll_timeout() is called
478  * in non-blocking mode when timeouts expire.
479  *
480  * In pseudo-code, you want something that looks like:
481 \code
482 // initialise libusb
483
484 libusb_get_pollfds()
485 while (user has not requested application exit):
486         libusb_get_next_timeout()
487         select(on libusb file descriptors plus any other event sources of interest,
488                 using a timeout no larger than the value libusb just suggested)
489         if (select() indicated activity on libusb file descriptors):
490                 libusb_poll_timeout(0);
491         if (time has elapsed to or beyond the libusb timeout):
492                 libusb_poll_timeout(0);
493  
494 // clean up and exit
495 \endcode
496  *
497  * The set of file descriptors that libusb uses as event sources may change
498  * during the life of your application. Rather than having to repeatedly
499  * call libusb_get_pollfds(), you can set up notification functions for when
500  * the file descriptor set changes using libusb_set_pollfd_notifiers().
501  *
502  */
503
504 void usbi_io_init()
505 {
506         list_init(&flying_transfers);
507         list_init(&pollfds);
508         fd_added_cb = NULL;
509         fd_removed_cb = NULL;
510 }
511
512 static int calculate_timeout(struct usbi_transfer *transfer)
513 {
514         int r;
515         struct timespec current_time;
516         unsigned int timeout = transfer->pub.timeout;
517
518         if (!timeout)
519                 return 0;
520
521         r = clock_gettime(CLOCK_MONOTONIC, &current_time);
522         if (r < 0) {
523                 usbi_err("failed to read monotonic clock, errno=%d", errno);
524                 return r;
525         }
526
527         current_time.tv_sec += timeout / 1000;
528         current_time.tv_nsec += (timeout % 1000) * 1000000;
529
530         if (current_time.tv_nsec > 1000000000) {
531                 current_time.tv_nsec -= 1000000000;
532                 current_time.tv_sec++;
533         }
534
535         TIMESPEC_TO_TIMEVAL(&transfer->timeout, &current_time);
536         return 0;
537 }
538
539 static void add_to_flying_list(struct usbi_transfer *transfer)
540 {
541         struct usbi_transfer *cur;
542         struct timeval *timeout = &transfer->timeout;
543
544         /* if we have no other flying transfers, start the list with this one */
545         if (list_empty(&flying_transfers)) {
546                 list_add(&transfer->list, &flying_transfers);
547                 return;
548         }
549
550         /* if we have infinite timeout, append to end of list */
551         if (!timerisset(timeout)) {
552                 list_add_tail(&transfer->list, &flying_transfers);
553                 return;
554         }
555
556         /* otherwise, find appropriate place in list */
557         list_for_each_entry(cur, &flying_transfers, list) {
558                 /* find first timeout that occurs after the transfer in question */
559                 struct timeval *cur_tv = &cur->timeout;
560
561                 if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
562                                 (cur_tv->tv_sec == timeout->tv_sec &&
563                                         cur_tv->tv_usec > timeout->tv_usec)) {
564                         list_add_tail(&transfer->list, &cur->list);
565                         return;
566                 }
567         }
568
569         /* otherwise we need to be inserted at the end */
570         list_add_tail(&transfer->list, &flying_transfers);
571 }
572
573 static int submit_transfer(struct usbi_transfer *itransfer)
574 {
575         int r = usbi_backend->submit_transfer(itransfer);
576         if (r < 0)
577                 return r;
578
579         add_to_flying_list(itransfer);
580         return 0;
581 }
582
583 /** \ingroup asyncio
584  * Obtain the memory-resident size of a transfer structure. Normally, you do
585  * not care about this as you will use libusb_alloc_transfer() and
586  * libusb_free_transfer() which hide this implementation detail from you.
587  *
588  * This function is useful when you wish to allocate transfers using your
589  * own custom memory allocator. libusb's transfer structure is bigger than
590  * it appears, so you must use this function to find out how much space is
591  * required for each transfer allocation.
592  *
593  * If you are allocating your own transfers, remember to initialize them
594  * with libusb_init_transfer().
595  *
596  * \returns the true size of a libusb_transfer structure
597  */
598 API_EXPORTED size_t libusb_get_transfer_alloc_size(void)
599 {
600         return sizeof(struct usbi_transfer) + usbi_backend->transfer_priv_size;
601 }
602
603 void __init_transfer(struct usbi_transfer *transfer)
604 {
605         memset(transfer, 0, sizeof(*transfer));
606 }
607
608 /** \ingroup asyncio
609  * Initialize a libusb transfer. This function is only for users who allocate
610  * their transfers using their own memory allocator. The more standard
611  * libusb_alloc_transfer() returns pre-initialized transfers.
612  * \param transfer a transfer to initialize
613  */
614 API_EXPORTED void libusb_init_transfer(struct libusb_transfer *transfer)
615 {
616         __init_transfer(TRANSFER_TO_PRIV(transfer));
617 }
618
619 /** \ingroup asyncio
620  * Allocate a libusb transfer using the standard system memory allocator. The
621  * returned transfer is pre-initialized for you. When the new transfer is no
622  * longer needed, it should be freed with libusb_free_transfer().
623  *
624  * \note
625  * Instead of using this function, it is legal for you to allocate transfers
626  * using a memory allocator of your choosing, but only if you consider the
627  * hidden size requirement (see libusb_get_transfer_alloc_size()) and
628  * initialize them before use (see libusb_init_transfer()).
629  *
630  * \returns a newly allocated transfer, or NULL on error
631  */
632 API_EXPORTED struct libusb_transfer *libusb_alloc_transfer(void)
633 {
634         struct usbi_transfer *transfer =
635                 malloc(sizeof(*transfer) + usbi_backend->transfer_priv_size);
636         if (!transfer)
637                 return NULL;
638
639         __init_transfer(transfer);
640         return &transfer->pub;
641 }
642
643 /** \ingroup asyncio
644  * Free a transfer structure. This should be called for all transfers
645  * allocated with libusb_alloc_transfer().
646  *
647  * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
648  * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is
649  * non-NULL, this function will also free the transfer buffer using the
650  * standard system memory allocator (e.g. free()).
651  *
652  * It is legal to call this function with a NULL transfer. In this case,
653  * the function will simply return safely.
654  *
655  * \param transfer the transfer to free
656  */
657 API_EXPORTED void libusb_free_transfer(struct libusb_transfer *transfer)
658 {
659         struct usbi_transfer *itransfer;
660         if (!transfer)
661                 return;
662
663         if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)
664                 free(transfer->buffer);
665
666         itransfer = TRANSFER_TO_PRIV(transfer);
667         free(itransfer);
668 }
669
670 /** \ingroup asyncio
671  * Submit a transfer. This function will fire off the USB transfer and then
672  * return immediately.
673  *
674  * It is undefined behaviour to submit a transfer that has already been
675  * submitted but has not yet completed.
676  *
677  * \param transfer the transfer to submit
678  * \returns 0 on success
679  * \returns negative on error
680  */
681 API_EXPORTED int libusb_submit_transfer(struct libusb_transfer *transfer)
682 {
683         struct usbi_transfer *itransfer = TRANSFER_TO_PRIV(transfer);
684         int r;
685
686         itransfer->transferred = 0;
687         r = calculate_timeout(itransfer);
688         if (r < 0)
689                 return r;
690
691         if (transfer->endpoint_type == LIBUSB_ENDPOINT_TYPE_CONTROL) {
692                 struct libusb_control_setup *setup =
693                         (struct libusb_control_setup *) transfer->buffer;
694         
695                 usbi_dbg("RQT=%02x RQ=%02x VAL=%04x IDX=%04x length=%d",
696                         setup->bRequestType, setup->bRequest, setup->wValue, setup->wIndex,
697                         setup->wLength);
698
699                 setup->wValue = cpu_to_le16(setup->wValue);
700                 setup->wIndex = cpu_to_le16(setup->wIndex);
701                 setup->wLength = cpu_to_le16(setup->wLength);
702         }
703
704         return submit_transfer(itransfer);
705 }
706
707 /** \ingroup asyncio
708  * Asynchronously cancel a previously submitted transfer.
709  * It is undefined behaviour to call this function on a transfer that is
710  * already being cancelled or has already completed.
711  * This function returns immediately, but this does not indicate cancellation
712  * is complete. Your callback function will be invoked at some later time
713  * with a transfer status of
714  * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED
715  * "LIBUSB_TRANSFER_CANCELLED."
716  *
717  * \param transfer the transfer to cancel
718  * \returns 0 on success
719  * \returns non-zero on error
720  */
721 API_EXPORTED int libusb_cancel_transfer(struct libusb_transfer *transfer)
722 {
723         struct usbi_transfer *itransfer = TRANSFER_TO_PRIV(transfer);
724         int r;
725
726         usbi_dbg("");
727         r = usbi_backend->cancel_transfer(itransfer);
728         if (r < 0)
729                 usbi_err("cancel transfer failed error %d", r);
730         return r;
731 }
732
733 /** \ingroup asyncio
734  * Cancel a transfer and wait for cancellation completion without invoking
735  * the transfer callback. This function will block. 
736  *
737  * It is undefined behaviour to call this function on a transfer that is
738  * already being cancelled or has already completed.
739  *
740  * \param transfer the transfer to cancel
741  * \returns 0 on success
742  * \returns non-zero on error
743  */
744 API_EXPORTED int libusb_cancel_transfer_sync(struct libusb_transfer *transfer)
745 {
746         struct usbi_transfer *itransfer = TRANSFER_TO_PRIV(transfer);
747         int r;
748
749         usbi_dbg("");
750         r = usbi_backend->cancel_transfer(itransfer);
751         if (r < 0) {
752                 usbi_err("cancel transfer failed error %d", r);
753                 return r;
754         }
755
756         itransfer->flags |= USBI_TRANSFER_SYNC_CANCELLED;
757         while (itransfer->flags & USBI_TRANSFER_SYNC_CANCELLED) {
758                 r = libusb_poll();
759                 if (r < 0)
760                         return r;
761         }
762
763         return 0;
764 }
765
766 void usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
767         enum libusb_transfer_status status)
768 {
769         struct libusb_transfer *transfer = &itransfer->pub;
770         uint8_t flags;
771
772         if (status == LIBUSB_TRANSFER_SILENT_COMPLETION)
773                 return;
774
775         if (status == LIBUSB_TRANSFER_COMPLETED
776                         && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
777                 int rqlen = transfer->length;
778                 if (transfer->endpoint_type == LIBUSB_ENDPOINT_TYPE_CONTROL)
779                         rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
780                 if (rqlen != itransfer->transferred) {
781                         usbi_dbg("interpreting short transfer as error");
782                         status = LIBUSB_TRANSFER_ERROR;
783                 }
784         }
785
786         flags = transfer->flags;
787         transfer->status = status;
788         transfer->actual_length = itransfer->transferred;
789         if (transfer->callback)
790                 transfer->callback(transfer);
791         /* transfer might have been freed by the above call, do not use from
792          * this point. */
793         if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
794                 libusb_free_transfer(transfer);
795 }
796
797 void usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
798 {
799         /* if the URB is being cancelled synchronously, raise cancellation
800          * completion event by unsetting flag, and ensure that user callback does
801          * not get called.
802          */
803         if (transfer->flags & USBI_TRANSFER_SYNC_CANCELLED) {
804                 transfer->flags &= ~USBI_TRANSFER_SYNC_CANCELLED;
805                 usbi_dbg("detected sync. cancel");
806                 usbi_handle_transfer_completion(transfer,
807                         LIBUSB_TRANSFER_SILENT_COMPLETION);
808                 return;
809         }
810
811         /* if the URB was cancelled due to timeout, report timeout to the user */
812         if (transfer->flags & USBI_TRANSFER_TIMED_OUT) {
813                 usbi_dbg("detected timeout cancellation");
814                 usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT);
815                 return;
816         }
817
818         /* otherwise its a normal async cancel */
819         usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
820 }
821
822 static void handle_timeout(struct usbi_transfer *itransfer)
823 {
824         /* handling timeouts is tricky, as we may race with the kernel: we may
825          * detect a timeout racing with the condition that the urb has actually
826          * completed. we asynchronously cancel the URB and report timeout
827          * to the user when the URB cancellation completes (or not at all if the
828          * URB actually gets delivered as per this race) */
829         struct libusb_transfer *transfer = &itransfer->pub;
830         int r;
831
832         itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
833         r = libusb_cancel_transfer(transfer);
834         if (r < 0)
835                 usbi_warn("async cancel failed %d errno=%d", r, errno);
836 }
837
838 static int handle_timeouts(void)
839 {
840         struct timespec systime_ts;
841         struct timeval systime;
842         struct usbi_transfer *transfer;
843         int r;
844
845         if (list_empty(&flying_transfers))
846                 return 0;
847
848         /* get current time */
849         r = clock_gettime(CLOCK_MONOTONIC, &systime_ts);
850         if (r < 0)
851                 return r;
852
853         TIMESPEC_TO_TIMEVAL(&systime, &systime_ts);
854
855         /* iterate through flying transfers list, finding all transfers that
856          * have expired timeouts */
857         list_for_each_entry(transfer, &flying_transfers, list) {
858                 struct timeval *cur_tv = &transfer->timeout;
859
860                 /* if we've reached transfers of infinite timeout, we're all done */
861                 if (!timerisset(cur_tv))
862                         return 0;
863
864                 /* ignore timeouts we've already handled */
865                 if (transfer->flags & USBI_TRANSFER_TIMED_OUT)
866                         continue;
867
868                 /* if transfer has non-expired timeout, nothing more to do */
869                 if ((cur_tv->tv_sec > systime.tv_sec) ||
870                                 (cur_tv->tv_sec == systime.tv_sec &&
871                                         cur_tv->tv_usec > systime.tv_usec))
872                         return 0;
873         
874                 /* otherwise, we've got an expired timeout to handle */
875                 handle_timeout(transfer);
876         }
877
878         return 0;
879 }
880
881 static int poll_io(struct timeval *tv)
882 {
883         int r;
884         int maxfd = 0;
885         fd_set readfds, writefds;
886         fd_set *_readfds = NULL;
887         fd_set *_writefds = NULL;
888         struct usbi_pollfd *ipollfd;
889         int have_readfds = 0;
890         int have_writefds = 0;
891         struct timeval select_timeout;
892         struct timeval timeout;
893
894         r = libusb_get_next_timeout(&timeout);
895         if (r) {
896                 /* timeout already expired? */
897                 if (!timerisset(&timeout))
898                         return handle_timeouts();
899
900                 /* choose the smallest of next URB timeout or user specified timeout */
901                 if (timercmp(&timeout, tv, <))
902                         select_timeout = timeout;
903                 else
904                         select_timeout = *tv;
905         } else {
906                 select_timeout = *tv;
907         }
908
909         FD_ZERO(&readfds);
910         FD_ZERO(&writefds);
911         list_for_each_entry(ipollfd, &pollfds, list) {
912                 struct libusb_pollfd *pollfd = &ipollfd->pollfd;
913                 int fd = pollfd->fd;
914                 if (pollfd->events & POLLIN) {
915                         have_readfds = 1;
916                         FD_SET(fd, &readfds);
917                 }
918                 if (pollfd->events & POLLOUT) {
919                         have_writefds = 1;
920                         FD_SET(fd, &writefds);
921                 }
922                 if (fd > maxfd)
923                         maxfd = fd;
924         }
925
926         if (have_readfds)
927                 _readfds = &readfds;
928         if (have_writefds)
929                 _writefds = &writefds;
930
931         usbi_dbg("select() with timeout in %d.%06ds", select_timeout.tv_sec,
932                 select_timeout.tv_usec);
933         r = select(maxfd + 1, _readfds, _writefds, NULL, &select_timeout);
934         usbi_dbg("select() returned %d with %d.%06ds remaining",
935                 r, select_timeout.tv_sec, select_timeout.tv_usec);
936         if (r == 0) {
937                 *tv = select_timeout;
938                 return handle_timeouts();
939         } else if (r == -1 && errno == EINTR) {
940                 return 0;
941         } else if (r < 0) {
942                 usbi_err("select failed %d err=%d\n", r, errno);
943                 return r;
944         }
945
946         r = usbi_backend->handle_events(_readfds, _writefds);
947         if (r < 0)
948                 return r;
949
950         /* FIXME check return value? */
951         return handle_timeouts();
952 }
953
954 /** \ingroup poll
955  * Handle any pending events.
956  *
957  * libusb determines "pending events" by checking if any timeouts have expired
958  * and by checking the set of file descriptors for activity.
959  *
960  * If a zero timeval is passed, this function will handle any already-pending
961  * events and then immediately return in non-blocking style.
962  *
963  * If a non-zero timeval is passed and no events are currently pending, this
964  * function will block waiting for events to handle up until the specified
965  * timeout. If an event arrives or a signal is raised, this function will
966  * return early.
967  *
968  * \param tv the maximum time to block waiting for events, or zero for
969  * non-blocking mode
970  * \returns 0 on success
971  * \returns non-zero on error
972  */
973 API_EXPORTED int libusb_poll_timeout(struct timeval *tv)
974 {
975         return poll_io(tv);
976 }
977
978 /** \ingroup poll
979  * Handle any pending events in blocking mode with a sensible timeout. This
980  * timeout is currently hardcoded at 2 seconds but we may change this if we
981  * decide other values are more sensible. For finer control over whether this
982  * function is blocking or non-blocking, or the maximum timeout, use
983  * libusb_poll_timeout() instead.
984  *
985  * \returns 0 on success
986  * \returns non-zero on error
987  */
988 API_EXPORTED int libusb_poll(void)
989 {
990         struct timeval tv;
991         tv.tv_sec = 2;
992         tv.tv_usec = 0;
993         return poll_io(&tv);
994 }
995
996 /** \ingroup poll
997  * Determine the next internal timeout that libusb needs to handle. You only
998  * need to use this function if you are calling poll() or select() or similar
999  * on libusb's file descriptors yourself - you do not need to use it if you
1000  * are calling libusb_poll() or a variant directly.
1001  * 
1002  * You should call this function in your main loop in order to determine how
1003  * long to wait for select() or poll() to return results. libusb needs to be
1004  * called into at this timeout, so you should use it as an upper bound on
1005  * your select() or poll() call.
1006  *
1007  * When the timeout has expired, call into libusb_poll_timeout() (perhaps in 
1008  * non-blocking mode) so that libusb can handle the timeout.
1009  *
1010  * This function may return 0 (success) and an all-zero timeval. If this is
1011  * the case, it indicates that libusb has a timeout that has already expired
1012  * so you should call libusb_poll_timeout() or similar immediately.
1013  *
1014  * \param tv output location for a relative time against the current
1015  * clock in which libusb must be called into in order to process timeout events
1016  * \returns 0 on success
1017  * \returns non-zero on error
1018  */
1019 API_EXPORTED int libusb_get_next_timeout(struct timeval *tv)
1020 {
1021         struct usbi_transfer *transfer;
1022         struct timespec cur_ts;
1023         struct timeval cur_tv;
1024         struct timeval *next_timeout;
1025         int r;
1026         int found = 0;
1027
1028         if (list_empty(&flying_transfers)) {
1029                 usbi_dbg("no URBs, no timeout!");
1030                 return 0;
1031         }
1032
1033         /* find next transfer which hasn't already been processed as timed out */
1034         list_for_each_entry(transfer, &flying_transfers, list) {
1035                 if (!(transfer->flags & USBI_TRANSFER_TIMED_OUT)) {
1036                         found = 1;
1037                         break;
1038                 }
1039         }
1040
1041         if (!found) {
1042                 usbi_dbg("all URBs have already been processed for timeouts");
1043                 return 0;
1044         }
1045
1046         next_timeout = &transfer->timeout;
1047
1048         /* no timeout for next transfer */
1049         if (!timerisset(next_timeout)) {
1050                 usbi_dbg("no URBs with timeouts, no timeout!");
1051                 return 0;
1052         }
1053
1054         r = clock_gettime(CLOCK_MONOTONIC, &cur_ts);
1055         if (r < 0) {
1056                 usbi_err("failed to read monotonic clock, errno=%d", errno);
1057                 return r;
1058         }
1059         TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts);
1060
1061         if (timercmp(&cur_tv, next_timeout, >=)) {
1062                 usbi_dbg("first timeout already expired");
1063                 timerclear(tv);
1064         } else {
1065                 timersub(next_timeout, &cur_tv, tv);
1066                 usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec);
1067         }
1068
1069         return 1;
1070 }
1071
1072 /** \ingroup poll
1073  * Register notification functions for file descriptor additions/removals.
1074  * These functions will be invoked for every new or removed file descriptor
1075  * that libusb uses as an event source.
1076  *
1077  * To remove notifiers, pass NULL values for the function pointers.
1078  *
1079  * \param added_cb pointer to function for addition notifications
1080  * \param removed_cb pointer to function for removal notifications
1081  */
1082 API_EXPORTED void libusb_set_pollfd_notifiers(libusb_pollfd_added_cb added_cb,
1083         libusb_pollfd_removed_cb removed_cb)
1084 {
1085         fd_added_cb = added_cb;
1086         fd_removed_cb = removed_cb;
1087 }
1088
1089 int usbi_add_pollfd(int fd, short events)
1090 {
1091         struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
1092         if (!ipollfd)
1093                 return -ENOMEM;
1094
1095         usbi_dbg("add fd %d events %d", fd, events);
1096         ipollfd->pollfd.fd = fd;
1097         ipollfd->pollfd.events = events;
1098         list_add(&ipollfd->list, &pollfds);
1099
1100         if (fd_added_cb)
1101                 fd_added_cb(fd, events);
1102         return 0;
1103 }
1104
1105 void usbi_remove_pollfd(int fd)
1106 {
1107         struct usbi_pollfd *ipollfd;
1108         int found = 0;
1109
1110         usbi_dbg("remove fd %d", fd);
1111         list_for_each_entry(ipollfd, &pollfds, list)
1112                 if (ipollfd->pollfd.fd == fd) {
1113                         found = 1;
1114                         break;
1115                 }
1116
1117         if (!found) {
1118                 usbi_err("couldn't find fd %d to remove", fd);
1119                 return;
1120         }
1121
1122         list_del(&ipollfd->list);
1123         free(ipollfd);
1124         if (fd_removed_cb)
1125                 fd_removed_cb(fd);
1126 }
1127
1128 /** \ingroup poll
1129  * Retrieve a list of file descriptors that should be polled by your main loop
1130  * as libusb event sources.
1131  *
1132  * The returned list is NULL-terminated and should be freed with free() when
1133  * done. The actual list contents must not be touched.
1134  *
1135  * \returns a NULL-terminated list of libusb_pollfd structures, or NULL on
1136  * error
1137  */
1138 API_EXPORTED struct libusb_pollfd **libusb_get_pollfds(void)
1139 {
1140         struct libusb_pollfd **ret;
1141         struct usbi_pollfd *ipollfd;
1142         size_t i = 0;
1143         size_t cnt = 0;
1144
1145         list_for_each_entry(ipollfd, &pollfds, list)
1146                 cnt++;
1147
1148         ret = calloc(cnt + 1, sizeof(struct libusb_pollfd *));
1149         if (!ret)
1150                 return NULL;
1151
1152         list_for_each_entry(ipollfd, &pollfds, list)
1153                 ret[i++] = (struct libusb_pollfd *) ipollfd;
1154         ret[cnt] = NULL;
1155
1156         return ret;
1157 }
1158