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>
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.
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.
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
36 * \page io Synchronous and asynchronous device I/O
38 * \section intro Introduction
40 * If you're using libusb in your application, you're probably wanting to
41 * perform I/O with devices - you want to perform USB data transfers.
43 * libusb offers two separate interfaces for device I/O. This page aims to
44 * introduce the two in order to help you decide which one is more suitable
45 * for your application. You can also choose to use both interfaces in your
46 * application by considering each transfer on a case-by-case basis.
48 * Once you have read through the following discussion, you should consult the
49 * detailed API documentation pages for the details:
53 * \section theory Transfers at a logical level
55 * At a logical level, USB transfers typically happen in two parts. For
56 * example, when reading data from a endpoint:
57 * -# A request for data is sent to the device
58 * -# Some time later, the incoming data is received by the host
60 * or when writing data to an endpoint:
62 * -# The data is sent to the device
63 * -# Some time later, the host receives acknowledgement from the device that
64 * the data has been transferred.
66 * There may be an indefinite delay between the two steps. Consider a
67 * fictional USB input device with a button that the user can press. In order
68 * to determine when the button is pressed, you would likely submit a request
69 * to read data on a bulk or interrupt endpoint and wait for data to arrive.
70 * Data will arrive when the button is pressed by the user, which is
71 * potentially hours later.
73 * libusb offers both a synchronous and an asynchronous interface to performing
74 * USB transfers. The main difference is that the synchronous interface
75 * combines both steps indicated above into a single function call, whereas
76 * the asynchronous interface separates them.
78 * \section sync The synchronous interface
80 * The synchronous I/O interface allows you to perform a USB transfer with
81 * a single function call. When the function call returns, the transfer has
82 * completed and you can parse the results.
84 * If you have used the libusb-0.1 before, this I/O style will seem familar to
85 * you. libusb-0.1 only offered a synchronous interface.
87 * In our input device example, to read button presses you might write code
88 * in the following style:
90 unsigned char data[4];
92 int r = libusb_bulk_transfer(handle, EP_IN, data, sizeof(data), &actual_length, 0);
93 if (r == 0 && actual_length == sizeof(data)) {
94 // results of the transaction can now be found in the data buffer
95 // parse them here and report button press
101 * The main advantage of this model is simplicity: you did everything with
102 * a single simple function call.
104 * However, this interface has its limitations. Your application will sleep
105 * inside libusb_bulk_transfer() until the transaction has completed. If it
106 * takes the user 3 hours to press the button, your application will be
107 * sleeping for that long. Execution will be tied up inside the library -
108 * the entire thread will be useless for that duration.
110 * Another issue is that by tieing up the thread with that single transaction
111 * there is no possibility of performing I/O with multiple endpoints and/or
112 * multiple devices simultaneously, unless you resort to creating one thread
115 * Additionally, there is no opportunity to cancel the transfer after the
116 * request has been submitted.
118 * For details on how to use the synchronous API, see the
119 * \ref syncio "synchronous I/O API documentation" pages.
121 * \section async The asynchronous interface
123 * Asynchronous I/O is the most significant new feature in libusb-1.0.
124 * Although it is a more complex interface, it solves all the issues detailed
127 * Instead of providing which functions that block until the I/O has complete,
128 * libusb's asynchronous interface presents non-blocking functions which
129 * begin a transfer and then return immediately. Your application passes a
130 * callback function pointer to this non-blocking function, which libusb will
131 * call with the results of the transaction when it has completed.
133 * Transfers which have been submitted through the non-blocking functions
134 * can be cancelled with a separate function call.
136 * The non-blocking nature of this interface allows you to be simultaneously
137 * performing I/O to multiple endpoints on multiple devices, without having
140 * This added flexibility does come with some complications though:
141 * - In the interest of being a lightweight library, libusb does not create
142 * threads and can only operate when your application is calling into it. Your
143 * application must call into libusb from it's main loop when events are ready
144 * to be handled, or you must use some other scheme to allow libusb to
145 * undertake whatever work needs to be done.
146 * - libusb also needs to be called into at certain fixed points in time in
147 * order to accurately handle transfer timeouts.
148 * - Memory handling becomes more complex. You cannot use stack memory unless
149 * the function with that stack is guaranteed not to return until the transfer
150 * callback has finished executing.
151 * - You generally lose some linearity from your code flow because submitting
152 * the transfer request is done in a separate function from where the transfer
153 * results are handled. This becomes particularly obvious when you want to
154 * submit a second transfer based on the results of an earlier transfer.
156 * Internally, libusb's synchronous interface is expressed in terms of function
157 * calls to the asynchronous interface.
159 * For details on how to use the asynchronous API, see the
160 * \ref asyncio "asynchronous I/O API" documentation pages.
165 * \page packetoverflow Packets and overflows
167 * \section packets Packet abstraction
169 * The USB specifications describe how data is transmitted in packets, with
170 * constraints on packet size defined by endpoint descriptors. The host must
171 * not send data payloads larger than the endpoint's maximum packet size.
173 * libusb and the underlying OS abstract out the packet concept, allowing you
174 * to request transfers of any size. Internally, the request will be divided
175 * up into correctly-sized packets. You do not have to be concerned with
176 * packet sizes, but there is one exception when considering overflows.
178 * \section overflow Bulk/interrupt transfer overflows
180 * When requesting data on a bulk endpoint, libusb requires you to supply a
181 * buffer and the maximum number of bytes of data that libusb can put in that
182 * buffer. However, the size of the buffer is not communicated to the device -
183 * the device is just asked to send any amount of data.
185 * There is no problem if the device sends an amount of data that is less than
186 * or equal to the buffer size. libusb reports this condition to you through
187 * the \ref libusb_transfer::actual_length "libusb_transfer.actual_length"
190 * Problems may occur if the device attempts to send more data than can fit in
191 * the buffer. libusb reports LIBUSB_TRANSFER_OVERFLOW for this condition but
192 * other behaviour is largely undefined: actual_length may or may not be
193 * accurate, the chunk of data that can fit in the buffer (before overflow)
194 * may or may not have been transferred.
196 * Overflows are nasty, but can be avoided. Even though you were told to
197 * ignore packets above, think about the lower level details: each transfer is
198 * split into packets (typically small, with a maximum size of 512 bytes).
199 * Overflows can only happen if the final packet in an incoming data transfer
200 * is smaller than the actual packet that the device wants to transfer.
201 * Therefore, you will never see an overflow if your transfer buffer size is a
202 * multiple of the endpoint's packet size: the final packet will either
203 * fill up completely or will be only partially filled.
207 * @defgroup asyncio Asynchronous device I/O
209 * This page details libusb's asynchronous (non-blocking) API for USB device
210 * I/O. This interface is very powerful but is also quite complex - you will
211 * need to read this page carefully to understand the necessary considerations
212 * and issues surrounding use of this interface. Simplistic applications
213 * may wish to consider the \ref syncio "synchronous I/O API" instead.
215 * The asynchronous interface is built around the idea of separating transfer
216 * submission and handling of transfer completion (the synchronous model
217 * combines both of these into one). There may be a long delay between
218 * submission and completion, however the asynchronous submission function
219 * is non-blocking so will return control to your application during that
220 * potentially long delay.
222 * \section asyncabstraction Transfer abstraction
224 * For the asynchronous I/O, libusb implements the concept of a generic
225 * transfer entity for all types of I/O (control, bulk, interrupt,
226 * isochronous). The generic transfer object must be treated slightly
227 * differently depending on which type of I/O you are performing with it.
229 * This is represented by the public libusb_transfer structure type.
231 * \section asynctrf Asynchronous transfers
233 * We can view asynchronous I/O as a 5 step process:
237 * -# Completion handling
240 * \subsection asyncalloc Allocation
242 * This step involves allocating memory for a USB transfer. This is the
243 * generic transfer object mentioned above. At this stage, the transfer
244 * is "blank" with no details about what type of I/O it will be used for.
246 * Allocation is done with the libusb_alloc_transfer() function. You must use
247 * this function rather than allocating your own transfers.
249 * \subsection asyncfill Filling
251 * This step is where you take a previously allocated transfer and fill it
252 * with information to determine the message type and direction, data buffer,
253 * callback function, etc.
255 * You can either fill the required fields yourself or you can use the
256 * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer()
257 * and libusb_fill_interrupt_transfer().
259 * \subsection asyncsubmit Submission
261 * When you have allocated a transfer and filled it, you can submit it using
262 * libusb_submit_transfer(). This function returns immediately but can be
263 * regarded as firing off the I/O request in the background.
265 * \subsection asynccomplete Completion handling
267 * After a transfer has been submitted, one of four things can happen to it:
269 * - The transfer completes (i.e. some data was transferred)
270 * - The transfer has a timeout and the timeout expires before all data is
272 * - The transfer fails due to an error
273 * - The transfer is cancelled
275 * Each of these will cause the user-specified transfer callback function to
276 * be invoked. It is up to the callback function to determine which of the
277 * above actually happened and to act accordingly.
279 * \subsection Deallocation
281 * When a transfer has completed (i.e. the callback function has been invoked),
282 * you are advised to free the transfer (unless you wish to resubmit it, see
283 * below). Transfers are deallocated with libusb_free_transfer().
285 * It is undefined behaviour to free a transfer which has not completed.
287 * \section asyncresubmit Resubmission
289 * You may be wondering why allocation, filling, and submission are all
290 * separated above where they could reasonably be combined into a single
293 * The reason for separation is to allow you to resubmit transfers without
294 * having to allocate new ones every time. This is especially useful for
295 * common situations dealing with interrupt endpoints - you allocate one
296 * transfer, fill and submit it, and when it returns with results you just
297 * resubmit it for the next interrupt.
299 * \section asynccancel Cancellation
301 * Another advantage of using the asynchronous interface is that you have
302 * the ability to cancel transfers which have not yet completed. This is
303 * done by calling the libusb_cancel_transfer() function.
305 * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the
306 * cancellation actually completes, the transfer's callback function will
307 * be invoked, and the callback function should check the transfer status to
308 * determine that it was cancelled.
310 * Freeing the transfer after it has been cancelled but before cancellation
311 * has completed will result in undefined behaviour.
313 * \section bulk_overflows Overflows on device-to-host bulk/interrupt endpoints
315 * If your device does not have predictable transfer sizes (or it misbehaves),
316 * your application may submit a request for data on an IN endpoint which is
317 * smaller than the data that the device wishes to send. In some circumstances
318 * this will cause an overflow, which is a nasty condition to deal with. See
319 * the \ref packetoverflow page for discussion.
321 * \section asyncctrl Considerations for control transfers
323 * The <tt>libusb_transfer</tt> structure is generic and hence does not
324 * include specific fields for the control-specific setup packet structure.
326 * In order to perform a control transfer, you must place the 8-byte setup
327 * packet at the start of the data buffer. To simplify this, you could
328 * cast the buffer pointer to type struct libusb_control_setup, or you can
329 * use the helper function libusb_fill_control_setup().
331 * The wLength field placed in the setup packet must be the length you would
332 * expect to be sent in the setup packet: the length of the payload that
333 * follows (or the expected maximum number of bytes to receive). However,
334 * the length field of the libusb_transfer object must be the length of
335 * the data buffer - i.e. it should be wLength <em>plus</em> the size of
336 * the setup packet (LIBUSB_CONTROL_SETUP_SIZE).
338 * If you use the helper functions, this is simplified for you:
339 * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the
340 * data you are sending/requesting.
341 * -# Call libusb_fill_control_setup() on the data buffer, using the transfer
342 * request size as the wLength value (i.e. do not include the extra space you
343 * allocated for the control setup).
344 * -# If this is a host-to-device transfer, place the data to be transferred
345 * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE.
346 * -# Call libusb_fill_control_transfer() to associate the data buffer with
347 * the transfer (and to set the remaining details such as callback and timeout).
348 * - Note that there is no parameter to set the length field of the transfer.
349 * The length is automatically inferred from the wLength field of the setup
351 * -# Submit the transfer.
353 * The multi-byte control setup fields (wValue, wIndex and wLength) must
354 * be given in little-endian byte order (the endianness of the USB bus).
355 * Endianness conversion is transparently handled by
356 * libusb_fill_control_setup() which is documented to accept host-endian
359 * Further considerations are needed when handling transfer completion in
360 * your callback function:
361 * - As you might expect, the setup packet will still be sitting at the start
362 * of the data buffer.
363 * - If this was a device-to-host transfer, the received data will be sitting
364 * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer.
365 * - The actual_length field of the transfer structure is relative to the
366 * wLength of the setup packet, rather than the size of the data buffer. So,
367 * if your wLength was 4, your transfer's <tt>length</tt> was 12, then you
368 * should expect an <tt>actual_length</tt> of 4 to indicate that the data was
369 * transferred in entirity.
371 * To simplify parsing of setup packets and obtaining the data from the
372 * correct offset, you may wish to use the libusb_control_transfer_get_data()
373 * and libusb_control_transfer_get_setup() functions within your transfer
376 * Even though control endpoints do not halt, a completed control transfer
377 * may have a LIBUSB_TRANSFER_STALL status code. This indicates the control
378 * request was not supported.
380 * \section asyncintr Considerations for interrupt transfers
382 * All interrupt transfers are performed using the polling interval presented
383 * by the bInterval value of the endpoint descriptor.
385 * \section asynciso Considerations for isochronous transfers
387 * Isochronous transfers are more complicated than transfers to
388 * non-isochronous endpoints.
390 * To perform I/O to an isochronous endpoint, allocate the transfer by calling
391 * libusb_alloc_transfer() with an appropriate number of isochronous packets.
393 * During filling, set \ref libusb_transfer::type "type" to
394 * \ref libusb_transfer_type::LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
395 * "LIBUSB_TRANSFER_TYPE_ISOCHRONOUS", and set
396 * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than
397 * or equal to the number of packets you requested during allocation.
398 * libusb_alloc_transfer() does not set either of these fields for you, given
399 * that you might not even use the transfer on an isochronous endpoint.
401 * Next, populate the length field for the first num_iso_packets entries in
402 * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section
403 * 5.6.3 of the USB2 specifications describe how the maximum isochronous
404 * packet length is determined by wMaxPacketSize field in the endpoint
405 * descriptor. Two functions can help you here:
407 * - libusb_get_max_packet_size() is an easy way to determine the max
408 * packet size for an endpoint.
409 * - libusb_set_iso_packet_lengths() assigns the same length to all packets
410 * within a transfer, which is usually what you want.
412 * For outgoing transfers, you'll obviously fill the buffer and populate the
413 * packet descriptors in hope that all the data gets transferred. For incoming
414 * transfers, you must ensure the buffer has sufficient capacity for
415 * the situation where all packets transfer the full amount of requested data.
417 * Completion handling requires some extra consideration. The
418 * \ref libusb_transfer::actual_length "actual_length" field of the transfer
419 * is meaningless and should not be examined; instead you must refer to the
420 * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of
421 * each individual packet.
423 * The \ref libusb_transfer::status "status" field of the transfer is also a
425 * - If the packets were submitted and the isochronous data microframes
426 * completed normally, status will have value
427 * \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED
428 * "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred
429 * delays are not counted as transfer errors; the transfer.status field may
430 * indicate COMPLETED even if some or all of the packets failed. Refer to
431 * the \ref libusb_iso_packet_descriptor::status "status" field of each
432 * individual packet to determine packet failures.
433 * - The status field will have value
434 * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR
435 * "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered.
436 * - Other transfer status codes occur with normal behaviour.
438 * The data for each packet will be found at an offset into the buffer that
439 * can be calculated as if each prior packet completed in full. The
440 * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple()
441 * functions may help you here.
443 * \section asyncmem Memory caveats
445 * In most circumstances, it is not safe to use stack memory for transfer
446 * buffers. This is because the function that fired off the asynchronous
447 * transfer may return before libusb has finished using the buffer, and when
448 * the function returns it's stack gets destroyed. This is true for both
449 * host-to-device and device-to-host transfers.
451 * The only case in which it is safe to use stack memory is where you can
452 * guarantee that the function owning the stack space for the buffer does not
453 * return until after the transfer's callback function has completed. In every
454 * other case, you need to use heap memory instead.
456 * \section asyncflags Fine control
458 * Through using this asynchronous interface, you may find yourself repeating
459 * a few simple operations many times. You can apply a bitwise OR of certain
460 * flags to a transfer to simplify certain things:
461 * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK
462 * "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred
463 * less than the requested amount of data being marked with status
464 * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR"
465 * (they would normally be regarded as COMPLETED)
466 * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
467 * "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer
468 * buffer when freeing the transfer.
469 * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER
470 * "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the
471 * transfer after the transfer callback returns.
473 * \section asyncevent Event handling
475 * In accordance of the aim of being a lightweight library, libusb does not
476 * create threads internally. This means that libusb code does not execute
477 * at any time other than when your application is calling a libusb function.
478 * However, an asynchronous model requires that libusb perform work at various
479 * points in time - namely processing the results of previously-submitted
480 * transfers and invoking the user-supplied callback function.
482 * This gives rise to the libusb_handle_events() function which your
483 * application must call into when libusb has work do to. This gives libusb
484 * the opportunity to reap pending transfers, invoke callbacks, etc.
486 * The first issue to discuss here is how your application can figure out
487 * when libusb has work to do. In fact, there are two naive options which
488 * do not actually require your application to know this:
489 * -# Periodically call libusb_handle_events() in non-blocking mode at fixed
490 * short intervals from your main loop
491 * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated
494 * The first option is plainly not very nice, and will cause unnecessary
495 * CPU wakeups leading to increased power usage and decreased battery life.
496 * The second option is not very nice either, but may be the nicest option
497 * available to you if the "proper" approach can not be applied to your
498 * application (read on...).
500 * The recommended option is to integrate libusb with your application main
501 * event loop. libusb exposes a set of file descriptors which allow you to do
502 * this. Your main loop is probably already calling poll() or select() or a
503 * variant on a set of file descriptors for other event sources (e.g. keyboard
504 * button presses, mouse movements, network sockets, etc). You then add
505 * libusb's file descriptors to your poll()/select() calls, and when activity
506 * is detected on such descriptors you know it is time to call
507 * libusb_handle_events().
509 * There is one final event handling complication. libusb supports
510 * asynchronous transfers which time out after a specified time period, and
511 * this requires that libusb is called into at or after the timeout so that
512 * the timeout can be handled. So, in addition to considering libusb's file
513 * descriptors in your main event loop, you must also consider that libusb
514 * sometimes needs to be called into at fixed points in time even when there
515 * is no file descriptor activity.
517 * For the details on retrieving the set of file descriptors and determining
518 * the next timeout, see the \ref poll "polling and timing" API documentation.
522 * @defgroup poll Polling and timing
524 * This page documents libusb's functions for polling events and timing.
525 * These functions are only necessary for users of the
526 * \ref asyncio "asynchronous API". If you are only using the simpler
527 * \ref syncio "synchronous API" then you do not need to ever call these
530 * The justification for the functionality described here has already been
531 * discussed in the \ref asyncevent "event handling" section of the
532 * asynchronous API documentation. In summary, libusb does not create internal
533 * threads for event processing and hence relies on your application calling
534 * into libusb at certain points in time so that pending events can be handled.
535 * In order to know precisely when libusb needs to be called into, libusb
536 * offers you a set of pollable file descriptors and information about when
537 * the next timeout expires.
539 * If you are using the asynchronous I/O API, you must take one of the two
540 * following options, otherwise your I/O will not complete.
542 * \section pollsimple The simple option
544 * If your application revolves solely around libusb and does not need to
545 * handle other event sources, you can have a program structure as follows:
548 // find and open device
549 // maybe fire off some initial async I/O
551 while (user_has_not_requested_exit)
552 libusb_handle_events(ctx);
557 * With such a simple main loop, you do not have to worry about managing
558 * sets of file descriptors or handling timeouts. libusb_handle_events() will
559 * handle those details internally.
561 * \section pollmain The more advanced option
563 * In more advanced applications, you will already have a main loop which
564 * is monitoring other event sources: network sockets, X11 events, mouse
565 * movements, etc. Through exposing a set of file descriptors, libusb is
566 * designed to cleanly integrate into such main loops.
568 * In addition to polling file descriptors for the other event sources, you
569 * take a set of file descriptors from libusb and monitor those too. When you
570 * detect activity on libusb's file descriptors, you call
571 * libusb_handle_events_timeout() in non-blocking mode.
573 * You must also consider the fact that libusb sometimes has to handle events
574 * at certain known times which do not generate activity on file descriptors.
575 * Your main loop must also consider these times, modify it's poll()/select()
576 * timeout accordingly, and track time so that libusb_handle_events_timeout()
577 * is called in non-blocking mode when timeouts expire.
579 * In pseudo-code, you want something that looks like:
583 libusb_get_pollfds(ctx)
584 while (user has not requested application exit) {
585 libusb_get_next_timeout(ctx);
586 select(on libusb file descriptors plus any other event sources of interest,
587 using a timeout no larger than the value libusb just suggested)
588 if (select() indicated activity on libusb file descriptors)
589 libusb_handle_events_timeout(ctx, 0);
590 if (time has elapsed to or beyond the libusb timeout)
591 libusb_handle_events_timeout(ctx, 0);
597 * The set of file descriptors that libusb uses as event sources may change
598 * during the life of your application. Rather than having to repeatedly
599 * call libusb_get_pollfds(), you can set up notification functions for when
600 * the file descriptor set changes using libusb_set_pollfd_notifiers().
602 * \section mtissues Multi-threaded considerations
604 * Unfortunately, the situation is complicated further when multiple threads
605 * come into play. If two threads are monitoring the same file descriptors,
606 * the fact that only one thread will be woken up when an event occurs causes
609 * The events lock, event waiters lock, and libusb_handle_events_locked()
610 * entities are added to solve these problems. You do not need to be concerned
611 * with these entities otherwise.
613 * See the extra documentation: \ref mtasync
616 /** \page mtasync Multi-threaded applications and asynchronous I/O
618 * libusb is a thread-safe library, but extra considerations must be applied
619 * to applications which interact with libusb from multiple threads.
621 * The underlying issue that must be addressed is that all libusb I/O
622 * revolves around monitoring file descriptors through the poll()/select()
623 * system calls. This is directly exposed at the
624 * \ref asyncio "asynchronous interface" but it is important to note that the
625 * \ref syncio "synchronous interface" is implemented on top of the
626 * asynchonrous interface, therefore the same considerations apply.
628 * The issue is that if two or more threads are concurrently calling poll()
629 * or select() on libusb's file descriptors then only one of those threads
630 * will be woken up when an event arrives. The others will be completely
631 * oblivious that anything has happened.
633 * Consider the following pseudo-code, which submits an asynchronous transfer
634 * then waits for its completion. This style is one way you could implement a
635 * synchronous interface on top of the asynchronous interface (and libusb
636 * does something similar, albeit more advanced due to the complications
637 * explained on this page).
640 void cb(struct libusb_transfer *transfer)
642 int *completed = transfer->user_data;
647 const struct timeval timeout = { 120, 0 };
648 struct libusb_transfer *transfer;
649 unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE];
652 transfer = libusb_alloc_transfer(0);
653 libusb_fill_control_setup(buffer,
654 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x04, 0x01, 0, 0);
655 libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000);
656 libusb_submit_transfer(transfer);
659 poll(libusb file descriptors, 120*1000);
660 if (poll indicates activity)
661 libusb_handle_events_timeout(ctx, 0);
663 printf("completed!");
668 * Here we are <em>serializing</em> completion of an asynchronous event
669 * against a condition - the condition being completion of a specific transfer.
670 * The poll() loop has a long timeout to minimize CPU usage during situations
671 * when nothing is happening (it could reasonably be unlimited).
673 * If this is the only thread that is polling libusb's file descriptors, there
674 * is no problem: there is no danger that another thread will swallow up the
675 * event that we are interested in. On the other hand, if there is another
676 * thread polling the same descriptors, there is a chance that it will receive
677 * the event that we were interested in. In this situation, <tt>myfunc()</tt>
678 * will only realise that the transfer has completed on the next iteration of
679 * the loop, <em>up to 120 seconds later.</em> Clearly a two-minute delay is
680 * undesirable, and don't even think about using short timeouts to circumvent
683 * The solution here is to ensure that no two threads are ever polling the
684 * file descriptors at the same time. A naive implementation of this would
685 * impact the capabilities of the library, so libusb offers the scheme
686 * documented below to ensure no loss of functionality.
688 * Before we go any further, it is worth mentioning that all libusb-wrapped
689 * event handling procedures fully adhere to the scheme documented below.
690 * This includes libusb_handle_events() and all the synchronous I/O functions -
691 * libusb hides this headache from you. You do not need to worry about any
692 * of these issues if you stick to that level.
694 * The problem is when we consider the fact that libusb exposes file
695 * descriptors to allow for you to integrate asynchronous USB I/O into
696 * existing main loops, effectively allowing you to do some work behind
697 * libusb's back. If you do take libusb's file descriptors and pass them to
698 * poll()/select() yourself, you need to be aware of the associated issues.
700 * \section eventlock The events lock
702 * The first concept to be introduced is the events lock. The events lock
703 * is used to serialize threads that want to handle events, such that only
704 * one thread is handling events at any one time.
706 * You must take the events lock before polling libusb file descriptors,
707 * using libusb_lock_events(). You must release the lock as soon as you have
708 * aborted your poll()/select() loop, using libusb_unlock_events().
710 * \section threadwait Letting other threads do the work for you
712 * Although the events lock is a critical part of the solution, it is not
713 * enough on it's own. You might wonder if the following is sufficient...
715 libusb_lock_events(ctx);
717 poll(libusb file descriptors, 120*1000);
718 if (poll indicates activity)
719 libusb_handle_events_timeout(ctx, 0);
721 libusb_unlock_events(ctx);
723 * ...and the answer is that it is not. This is because the transfer in the
724 * code shown above may take a long time (say 30 seconds) to complete, and
725 * the lock is not released until the transfer is completed.
727 * Another thread with similar code that wants to do event handling may be
728 * working with a transfer that completes after a few milliseconds. Despite
729 * having such a quick completion time, the other thread cannot check that
730 * status of its transfer until the code above has finished (30 seconds later)
731 * due to contention on the lock.
733 * To solve this, libusb offers you a mechanism to determine when another
734 * thread is handling events. It also offers a mechanism to block your thread
735 * until the event handling thread has completed an event (and this mechanism
736 * does not involve polling of file descriptors).
738 * After determining that another thread is currently handling events, you
739 * obtain the <em>event waiters</em> lock using libusb_lock_event_waiters().
740 * You then re-check that some other thread is still handling events, and if
741 * so, you call libusb_wait_for_event().
743 * libusb_wait_for_event() puts your application to sleep until an event
744 * occurs, or until a thread releases the events lock. When either of these
745 * things happen, your thread is woken up, and should re-check the condition
746 * it was waiting on. It should also re-check that another thread is handling
747 * events, and if not, it should start handling events itself.
749 * This looks like the following, as pseudo-code:
752 if (libusb_try_lock_events(ctx) == 0) {
753 // we obtained the event lock: do our own event handling
754 libusb_lock_events(ctx);
756 poll(libusb file descriptors, 120*1000);
757 if (poll indicates activity)
758 libusb_handle_events_locked(ctx, 0);
760 libusb_unlock_events(ctx);
762 // another thread is doing event handling. wait for it to signal us that
763 // an event has completed
764 libusb_lock_event_waiters(ctx);
767 // now that we have the event waiters lock, double check that another
768 // thread is still handling events for us. (it may have ceased handling
769 // events in the time it took us to reach this point)
770 if (!libusb_event_handler_active(ctx)) {
771 // whoever was handling events is no longer doing so, try again
772 libusb_unlock_event_waiters(ctx);
776 libusb_wait_for_event(ctx);
778 libusb_unlock_event_waiters(ctx);
780 printf("completed!\n");
783 * We have now implemented code which can dynamically handle situations where
784 * nobody is handling events (so we should do it ourselves), and it can also
785 * handle situations where another thread is doing event handling (so we can
786 * piggyback onto them). It is also equipped to handle a combination of
787 * the two, for example, another thread is doing event handling, but for
788 * whatever reason it stops doing so before our condition is met, so we take
789 * over the event handling.
791 * Three functions were introduced in the above pseudo-code. Their importance
792 * should be apparent from the code shown above.
793 * -# libusb_try_lock_events() is a non-blocking function which attempts
794 * to acquire the events lock but returns a failure code if it is contended.
795 * -# libusb_handle_events_locked() is a variant of
796 * libusb_handle_events_timeout() that you can call while holding the
797 * events lock. libusb_handle_events_timeout() itself implements similar
798 * logic to the above, so be sure not to call it when you are
799 * "working behind libusb's back", as is the case here.
800 * -# libusb_event_handler_active() determines if someone is currently
801 * holding the events lock
803 * You might be wondering why there is no function to wake up all threads
804 * blocked on libusb_wait_for_event(). This is because libusb can do this
805 * internally: it will wake up all such threads when someone calls
806 * libusb_unlock_events() or when a transfer completes (at the point after its
807 * callback has returned).
809 * \subsection concl Closing remarks
811 * The above may seem a little complicated, but hopefully I have made it clear
812 * why such complications are necessary. Also, do not forget that this only
813 * applies to applications that take libusb's file descriptors and integrate
814 * them into their own polling loops.
816 * You may decide that it is OK for your multi-threaded application to ignore
817 * some of the rules and locks detailed above, because you don't think that
818 * two threads can ever be polling the descriptors at the same time. If that
819 * is the case, then that's good news for you because you don't have to worry.
820 * But be careful here; remember that the synchronous I/O functions do event
821 * handling internally. If you have one thread doing event handling in a loop
822 * (without implementing the rules and locking semantics documented above)
823 * and another trying to send a synchronous USB transfer, you will end up with
824 * two threads monitoring the same descriptors, and the above-described
825 * undesirable behaviour occuring. The solution is for your polling thread to
826 * play by the rules; the synchronous I/O functions do so, and this will result
827 * in them getting along in perfect harmony.
829 * If you do have a dedicated thread doing event handling, it is perfectly
830 * legal for it to take the event handling lock and never release it. Any
831 * synchronous I/O functions you call from other threads will transparently
832 * fall back to the "event waiters" mechanism detailed above.
835 void usbi_io_init(struct libusb_context *ctx)
837 pthread_mutex_init(&ctx->flying_transfers_lock, NULL);
838 pthread_mutex_init(&ctx->pollfds_lock, NULL);
839 pthread_mutex_init(&ctx->events_lock, NULL);
840 pthread_mutex_init(&ctx->event_waiters_lock, NULL);
841 pthread_cond_init(&ctx->event_waiters_cond, NULL);
842 list_init(&ctx->flying_transfers);
843 list_init(&ctx->pollfds);
846 static int calculate_timeout(struct usbi_transfer *transfer)
849 struct timespec current_time;
850 unsigned int timeout =
851 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout;
856 r = clock_gettime(CLOCK_MONOTONIC, ¤t_time);
858 usbi_err(ITRANSFER_CTX(transfer),
859 "failed to read monotonic clock, errno=%d", errno);
863 current_time.tv_sec += timeout / 1000;
864 current_time.tv_nsec += (timeout % 1000) * 1000000;
866 if (current_time.tv_nsec > 1000000000) {
867 current_time.tv_nsec -= 1000000000;
868 current_time.tv_sec++;
871 TIMESPEC_TO_TIMEVAL(&transfer->timeout, ¤t_time);
875 static void add_to_flying_list(struct usbi_transfer *transfer)
877 struct usbi_transfer *cur;
878 struct timeval *timeout = &transfer->timeout;
879 struct libusb_context *ctx = ITRANSFER_CTX(transfer);
881 pthread_mutex_lock(&ctx->flying_transfers_lock);
883 /* if we have no other flying transfers, start the list with this one */
884 if (list_empty(&ctx->flying_transfers)) {
885 list_add(&transfer->list, &ctx->flying_transfers);
889 /* if we have infinite timeout, append to end of list */
890 if (!timerisset(timeout)) {
891 list_add_tail(&transfer->list, &ctx->flying_transfers);
895 /* otherwise, find appropriate place in list */
896 list_for_each_entry(cur, &ctx->flying_transfers, list) {
897 /* find first timeout that occurs after the transfer in question */
898 struct timeval *cur_tv = &cur->timeout;
900 if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
901 (cur_tv->tv_sec == timeout->tv_sec &&
902 cur_tv->tv_usec > timeout->tv_usec)) {
903 list_add_tail(&transfer->list, &cur->list);
908 /* otherwise we need to be inserted at the end */
909 list_add_tail(&transfer->list, &ctx->flying_transfers);
911 pthread_mutex_unlock(&ctx->flying_transfers_lock);
915 * Allocate a libusb transfer with a specified number of isochronous packet
916 * descriptors. The returned transfer is pre-initialized for you. When the new
917 * transfer is no longer needed, it should be freed with
918 * libusb_free_transfer().
920 * Transfers intended for non-isochronous endpoints (e.g. control, bulk,
921 * interrupt) should specify an iso_packets count of zero.
923 * For transfers intended for isochronous endpoints, specify an appropriate
924 * number of packet descriptors to be allocated as part of the transfer.
925 * The returned transfer is not specially initialized for isochronous I/O;
926 * you are still required to set the
927 * \ref libusb_transfer::num_iso_packets "num_iso_packets" and
928 * \ref libusb_transfer::type "type" fields accordingly.
930 * It is safe to allocate a transfer with some isochronous packets and then
931 * use it on a non-isochronous endpoint. If you do this, ensure that at time
932 * of submission, num_iso_packets is 0 and that type is set appropriately.
934 * \param iso_packets number of isochronous packet descriptors to allocate
935 * \returns a newly allocated transfer, or NULL on error
937 API_EXPORTED struct libusb_transfer *libusb_alloc_transfer(int iso_packets)
939 size_t os_alloc_size = usbi_backend->transfer_priv_size
940 + (usbi_backend->add_iso_packet_size * iso_packets);
941 int alloc_size = sizeof(struct usbi_transfer)
942 + sizeof(struct libusb_transfer)
943 + (sizeof(struct libusb_iso_packet_descriptor) * iso_packets)
945 struct usbi_transfer *itransfer = malloc(alloc_size);
949 memset(itransfer, 0, alloc_size);
950 itransfer->num_iso_packets = iso_packets;
951 return __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
955 * Free a transfer structure. This should be called for all transfers
956 * allocated with libusb_alloc_transfer().
958 * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
959 * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is
960 * non-NULL, this function will also free the transfer buffer using the
961 * standard system memory allocator (e.g. free()).
963 * It is legal to call this function with a NULL transfer. In this case,
964 * the function will simply return safely.
966 * \param transfer the transfer to free
968 API_EXPORTED void libusb_free_transfer(struct libusb_transfer *transfer)
970 struct usbi_transfer *itransfer;
974 if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)
975 free(transfer->buffer);
977 itransfer = __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
982 * Submit a transfer. This function will fire off the USB transfer and then
983 * return immediately.
985 * It is undefined behaviour to submit a transfer that has already been
986 * submitted but has not yet completed.
988 * \param transfer the transfer to submit
989 * \returns 0 on success
990 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
991 * \returns another LIBUSB_ERROR code on other failure
993 API_EXPORTED int libusb_submit_transfer(struct libusb_transfer *transfer)
995 struct usbi_transfer *itransfer =
996 __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
999 itransfer->transferred = 0;
1000 itransfer->flags = 0;
1001 r = calculate_timeout(itransfer);
1003 return LIBUSB_ERROR_OTHER;
1005 add_to_flying_list(itransfer);
1006 r = usbi_backend->submit_transfer(itransfer);
1008 pthread_mutex_lock(&TRANSFER_CTX(transfer)->flying_transfers_lock);
1009 list_del(&itransfer->list);
1010 pthread_mutex_unlock(&TRANSFER_CTX(transfer)->flying_transfers_lock);
1016 /** \ingroup asyncio
1017 * Asynchronously cancel a previously submitted transfer.
1018 * It is undefined behaviour to call this function on a transfer that is
1019 * already being cancelled or has already completed.
1020 * This function returns immediately, but this does not indicate cancellation
1021 * is complete. Your callback function will be invoked at some later time
1022 * with a transfer status of
1023 * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED
1024 * "LIBUSB_TRANSFER_CANCELLED."
1026 * \param transfer the transfer to cancel
1027 * \returns 0 on success
1028 * \returns a LIBUSB_ERROR code on failure
1030 API_EXPORTED int libusb_cancel_transfer(struct libusb_transfer *transfer)
1032 struct usbi_transfer *itransfer =
1033 __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1037 r = usbi_backend->cancel_transfer(itransfer);
1039 usbi_err(TRANSFER_CTX(transfer),
1040 "cancel transfer failed error %d", r);
1044 /* Handle completion of a transfer (completion might be an error condition).
1045 * This will invoke the user-supplied callback function, which may end up
1046 * freeing the transfer. Therefore you cannot use the transfer structure
1047 * after calling this function, and you should free all backend-specific
1048 * data before calling it. */
1049 void usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
1050 enum libusb_transfer_status status)
1052 struct libusb_transfer *transfer =
1053 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1054 struct libusb_context *ctx = TRANSFER_CTX(transfer);
1057 pthread_mutex_lock(&ctx->flying_transfers_lock);
1058 list_del(&itransfer->list);
1059 pthread_mutex_unlock(&ctx->flying_transfers_lock);
1061 if (status == LIBUSB_TRANSFER_COMPLETED
1062 && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1063 int rqlen = transfer->length;
1064 if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL)
1065 rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
1066 if (rqlen != itransfer->transferred) {
1067 usbi_dbg("interpreting short transfer as error");
1068 status = LIBUSB_TRANSFER_ERROR;
1072 flags = transfer->flags;
1073 transfer->status = status;
1074 transfer->actual_length = itransfer->transferred;
1075 if (transfer->callback)
1076 transfer->callback(transfer);
1077 /* transfer might have been freed by the above call, do not use from
1079 if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
1080 libusb_free_transfer(transfer);
1081 pthread_mutex_lock(&ctx->event_waiters_lock);
1082 pthread_cond_broadcast(&ctx->event_waiters_cond);
1083 pthread_mutex_unlock(&ctx->event_waiters_lock);
1086 /* Similar to usbi_handle_transfer_completion() but exclusively for transfers
1087 * that were asynchronously cancelled. The same concerns w.r.t. freeing of
1088 * transfers exist here.
1090 void usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
1092 /* if the URB was cancelled due to timeout, report timeout to the user */
1093 if (transfer->flags & USBI_TRANSFER_TIMED_OUT) {
1094 usbi_dbg("detected timeout cancellation");
1095 usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT);
1099 /* otherwise its a normal async cancel */
1100 usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
1104 * Attempt to acquire the event handling lock. This lock is used to ensure that
1105 * only one thread is monitoring libusb event sources at any one time.
1107 * You only need to use this lock if you are developing an application
1108 * which calls poll() or select() on libusb's file descriptors directly.
1109 * If you stick to libusb's event handling loop functions (e.g.
1110 * libusb_handle_events()) then you do not need to be concerned with this
1113 * While holding this lock, you are trusted to actually be handling events.
1114 * If you are no longer handling events, you must call libusb_unlock_events()
1115 * as soon as possible.
1117 * \param ctx the context to operate on, or NULL for the default context
1118 * \returns 0 if the lock was obtained successfully
1119 * \returns 1 if the lock was not obtained (i.e. another thread holds the lock)
1122 API_EXPORTED int libusb_try_lock_events(libusb_context *ctx)
1125 USBI_GET_CONTEXT(ctx);
1127 r = pthread_mutex_trylock(&ctx->events_lock);
1131 ctx->event_handler_active = 1;
1136 * Acquire the event handling lock, blocking until successful acquisition if
1137 * it is contended. This lock is used to ensure that only one thread is
1138 * monitoring libusb event sources at any one time.
1140 * You only need to use this lock if you are developing an application
1141 * which calls poll() or select() on libusb's file descriptors directly.
1142 * If you stick to libusb's event handling loop functions (e.g.
1143 * libusb_handle_events()) then you do not need to be concerned with this
1146 * While holding this lock, you are trusted to actually be handling events.
1147 * If you are no longer handling events, you must call libusb_unlock_events()
1148 * as soon as possible.
1150 * \param ctx the context to operate on, or NULL for the default context
1153 API_EXPORTED void libusb_lock_events(libusb_context *ctx)
1155 USBI_GET_CONTEXT(ctx);
1156 pthread_mutex_lock(&ctx->events_lock);
1157 ctx->event_handler_active = 1;
1161 * Release the lock previously acquired with libusb_try_lock_events() or
1162 * libusb_lock_events(). Releasing this lock will wake up any threads blocked
1163 * on libusb_wait_for_event().
1165 * \param ctx the context to operate on, or NULL for the default context
1168 API_EXPORTED void libusb_unlock_events(libusb_context *ctx)
1170 USBI_GET_CONTEXT(ctx);
1171 ctx->event_handler_active = 0;
1172 pthread_mutex_unlock(&ctx->events_lock);
1174 pthread_mutex_lock(&ctx->event_waiters_lock);
1175 pthread_cond_broadcast(&ctx->event_waiters_cond);
1176 pthread_mutex_unlock(&ctx->event_waiters_lock);
1180 * Determine if an active thread is handling events (i.e. if anyone is holding
1181 * the event handling lock).
1183 * \param ctx the context to operate on, or NULL for the default context
1184 * \returns 1 if a thread is handling events
1185 * \returns 0 if there are no threads currently handling events
1188 API_EXPORTED int libusb_event_handler_active(libusb_context *ctx)
1190 USBI_GET_CONTEXT(ctx);
1191 return ctx->event_handler_active;
1195 * Acquire the event waiters lock. This lock is designed to be obtained under
1196 * the situation where you want to be aware when events are completed, but
1197 * some other thread is event handling so calling libusb_handle_events() is not
1200 * You then obtain this lock, re-check that another thread is still handling
1201 * events, then call libusb_wait_for_event().
1203 * You only need to use this lock if you are developing an application
1204 * which calls poll() or select() on libusb's file descriptors directly,
1205 * <b>and</b> may potentially be handling events from 2 threads simultaenously.
1206 * If you stick to libusb's event handling loop functions (e.g.
1207 * libusb_handle_events()) then you do not need to be concerned with this
1210 * \param ctx the context to operate on, or NULL for the default context
1213 API_EXPORTED void libusb_lock_event_waiters(libusb_context *ctx)
1215 USBI_GET_CONTEXT(ctx);
1216 pthread_mutex_lock(&ctx->event_waiters_lock);
1220 * Release the event waiters lock.
1221 * \param ctx the context to operate on, or NULL for the default context
1224 API_EXPORTED void libusb_unlock_event_waiters(libusb_context *ctx)
1226 USBI_GET_CONTEXT(ctx);
1227 pthread_mutex_unlock(&ctx->event_waiters_lock);
1231 * Wait for another thread to signal completion of an event. Must be called
1232 * with the event waiters lock held, see libusb_lock_event_waiters().
1234 * This function will block until any of the following conditions are met:
1235 * -# The timeout expires
1236 * -# A transfer completes
1237 * -# A thread releases the event handling lock through libusb_unlock_events()
1239 * Condition 1 is obvious. Condition 2 unblocks your thread <em>after</em>
1240 * the callback for the transfer has completed. Condition 3 is important
1241 * because it means that the thread that was previously handling events is no
1242 * longer doing so, so if any events are to complete, another thread needs to
1243 * step up and start event handling.
1245 * This function releases the event waiters lock before putting your thread
1246 * to sleep, and reacquires the lock as it is being woken up.
1248 * \param ctx the context to operate on, or NULL for the default context
1249 * \param tv maximum timeout for this blocking function. A NULL value
1250 * indicates unlimited timeout.
1251 * \returns 0 after a transfer completes or another thread stops event handling
1252 * \returns 1 if the timeout expired
1255 API_EXPORTED int libusb_wait_for_event(libusb_context *ctx, struct timeval *tv)
1257 struct timespec timeout;
1260 USBI_GET_CONTEXT(ctx);
1262 pthread_cond_wait(&ctx->event_waiters_cond, &ctx->event_waiters_lock);
1266 r = clock_gettime(CLOCK_REALTIME, &timeout);
1268 usbi_err(ctx, "failed to read realtime clock, error %d", errno);
1269 return LIBUSB_ERROR_OTHER;
1272 timeout.tv_sec += tv->tv_sec;
1273 timeout.tv_nsec += tv->tv_usec * 1000;
1274 if (timeout.tv_nsec > 1000000000) {
1275 timeout.tv_nsec -= 1000000000;
1279 r = pthread_cond_timedwait(&ctx->event_waiters_cond,
1280 &ctx->event_waiters_lock, &timeout);
1281 return (r == ETIMEDOUT);
1284 static void handle_timeout(struct usbi_transfer *itransfer)
1286 struct libusb_transfer *transfer =
1287 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1290 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1291 r = libusb_cancel_transfer(transfer);
1293 usbi_warn(TRANSFER_CTX(transfer),
1294 "async cancel failed %d errno=%d", r, errno);
1297 static int handle_timeouts(struct libusb_context *ctx)
1299 struct timespec systime_ts;
1300 struct timeval systime;
1301 struct usbi_transfer *transfer;
1304 USBI_GET_CONTEXT(ctx);
1305 pthread_mutex_lock(&ctx->flying_transfers_lock);
1306 if (list_empty(&ctx->flying_transfers))
1309 /* get current time */
1310 r = clock_gettime(CLOCK_MONOTONIC, &systime_ts);
1314 TIMESPEC_TO_TIMEVAL(&systime, &systime_ts);
1316 /* iterate through flying transfers list, finding all transfers that
1317 * have expired timeouts */
1318 list_for_each_entry(transfer, &ctx->flying_transfers, list) {
1319 struct timeval *cur_tv = &transfer->timeout;
1321 /* if we've reached transfers of infinite timeout, we're all done */
1322 if (!timerisset(cur_tv))
1325 /* ignore timeouts we've already handled */
1326 if (transfer->flags & USBI_TRANSFER_TIMED_OUT)
1329 /* if transfer has non-expired timeout, nothing more to do */
1330 if ((cur_tv->tv_sec > systime.tv_sec) ||
1331 (cur_tv->tv_sec == systime.tv_sec &&
1332 cur_tv->tv_usec > systime.tv_usec))
1335 /* otherwise, we've got an expired timeout to handle */
1336 handle_timeout(transfer);
1340 pthread_mutex_unlock(&ctx->flying_transfers_lock);
1344 /* do the actual event handling. assumes that no other thread is concurrently
1345 * doing the same thing. */
1346 static int handle_events(struct libusb_context *ctx, struct timeval *tv)
1349 struct usbi_pollfd *ipollfd;
1355 pthread_mutex_lock(&ctx->pollfds_lock);
1356 list_for_each_entry(ipollfd, &ctx->pollfds, list)
1359 /* TODO: malloc when number of fd's changes, not on every poll */
1360 fds = malloc(sizeof(*fds) * nfds);
1362 return LIBUSB_ERROR_NO_MEM;
1364 list_for_each_entry(ipollfd, &ctx->pollfds, list) {
1365 struct libusb_pollfd *pollfd = &ipollfd->pollfd;
1366 int fd = pollfd->fd;
1369 fds[i].events = pollfd->events;
1372 pthread_mutex_unlock(&ctx->pollfds_lock);
1374 timeout_ms = (tv->tv_sec * 1000) + (tv->tv_usec / 1000);
1376 /* round up to next millisecond */
1377 if (tv->tv_usec % 1000)
1380 usbi_dbg("poll() %d fds with timeout in %dms", nfds, timeout_ms);
1381 r = poll(fds, nfds, timeout_ms);
1382 usbi_dbg("poll() returned %d", r);
1385 return handle_timeouts(ctx);
1386 } else if (r == -1 && errno == EINTR) {
1388 return LIBUSB_ERROR_INTERRUPTED;
1391 usbi_err(ctx, "poll failed %d err=%d\n", r, errno);
1392 return LIBUSB_ERROR_IO;
1395 r = usbi_backend->handle_events(ctx, fds, nfds, r);
1397 usbi_err(ctx, "backend handle_events failed with error %d", r);
1403 /* returns the smallest of:
1404 * 1. timeout of next URB
1405 * 2. user-supplied timeout
1406 * returns 1 if there is an already-expired timeout, otherwise returns 0
1409 static int get_next_timeout(libusb_context *ctx, struct timeval *tv,
1410 struct timeval *out)
1412 struct timeval timeout;
1413 int r = libusb_get_next_timeout(ctx, &timeout);
1415 /* timeout already expired? */
1416 if (!timerisset(&timeout))
1419 /* choose the smallest of next URB timeout or user specified timeout */
1420 if (timercmp(&timeout, tv, <))
1431 * Handle any pending events.
1433 * libusb determines "pending events" by checking if any timeouts have expired
1434 * and by checking the set of file descriptors for activity.
1436 * If a zero timeval is passed, this function will handle any already-pending
1437 * events and then immediately return in non-blocking style.
1439 * If a non-zero timeval is passed and no events are currently pending, this
1440 * function will block waiting for events to handle up until the specified
1441 * timeout. If an event arrives or a signal is raised, this function will
1444 * \param ctx the context to operate on, or NULL for the default context
1445 * \param tv the maximum time to block waiting for events, or zero for
1447 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1449 API_EXPORTED int libusb_handle_events_timeout(libusb_context *ctx,
1453 struct timeval poll_timeout;
1455 USBI_GET_CONTEXT(ctx);
1456 r = get_next_timeout(ctx, tv, &poll_timeout);
1458 /* timeout already expired */
1459 return handle_timeouts(ctx);
1463 if (libusb_try_lock_events(ctx) == 0) {
1464 /* we obtained the event lock: do our own event handling */
1465 r = handle_events(ctx, &poll_timeout);
1466 libusb_unlock_events(ctx);
1470 /* another thread is doing event handling. wait for pthread events that
1471 * notify event completion. */
1472 libusb_lock_event_waiters(ctx);
1474 if (!libusb_event_handler_active(ctx)) {
1475 /* we hit a race: whoever was event handling earlier finished in the
1476 * time it took us to reach this point. try the cycle again. */
1477 libusb_unlock_event_waiters(ctx);
1478 usbi_dbg("event handler was active but went away, retrying");
1482 usbi_dbg("another thread is doing event handling");
1483 r = libusb_wait_for_event(ctx, &poll_timeout);
1484 libusb_unlock_event_waiters(ctx);
1489 return handle_timeouts(ctx);
1495 * Handle any pending events in blocking mode with a sensible timeout. This
1496 * timeout is currently hardcoded at 2 seconds but we may change this if we
1497 * decide other values are more sensible. For finer control over whether this
1498 * function is blocking or non-blocking, or the maximum timeout, use
1499 * libusb_handle_events_timeout() instead.
1501 * \param ctx the context to operate on, or NULL for the default context
1502 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1504 API_EXPORTED int libusb_handle_events(libusb_context *ctx)
1509 return libusb_handle_events_timeout(ctx, &tv);
1513 * Handle any pending events by polling file descriptors, without checking if
1514 * any other threads are already doing so. Must be called with the event lock
1515 * held, see libusb_lock_events().
1517 * This function is designed to be called under the situation where you have
1518 * taken the event lock and are calling poll()/select() directly on libusb's
1519 * file descriptors (as opposed to using libusb_handle_events() or similar).
1520 * You detect events on libusb's descriptors, so you then call this function
1521 * with a zero timeout value (while still holding the event lock).
1523 * \param ctx the context to operate on, or NULL for the default context
1524 * \param tv the maximum time to block waiting for events, or zero for
1526 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1529 API_EXPORTED int libusb_handle_events_locked(libusb_context *ctx,
1533 struct timeval poll_timeout;
1535 USBI_GET_CONTEXT(ctx);
1536 r = get_next_timeout(ctx, tv, &poll_timeout);
1538 /* timeout already expired */
1539 return handle_timeouts(ctx);
1542 return handle_events(ctx, &poll_timeout);
1546 * Determine the next internal timeout that libusb needs to handle. You only
1547 * need to use this function if you are calling poll() or select() or similar
1548 * on libusb's file descriptors yourself - you do not need to use it if you
1549 * are calling libusb_handle_events() or a variant directly.
1551 * You should call this function in your main loop in order to determine how
1552 * long to wait for select() or poll() to return results. libusb needs to be
1553 * called into at this timeout, so you should use it as an upper bound on
1554 * your select() or poll() call.
1556 * When the timeout has expired, call into libusb_handle_events_timeout()
1557 * (perhaps in non-blocking mode) so that libusb can handle the timeout.
1559 * This function may return 1 (success) and an all-zero timeval. If this is
1560 * the case, it indicates that libusb has a timeout that has already expired
1561 * so you should call libusb_handle_events_timeout() or similar immediately.
1562 * A return code of 0 indicates that there are no pending timeouts.
1564 * \param ctx the context to operate on, or NULL for the default context
1565 * \param tv output location for a relative time against the current
1566 * clock in which libusb must be called into in order to process timeout events
1567 * \returns 0 if there are no pending timeouts, 1 if a timeout was returned,
1568 * or LIBUSB_ERROR_OTHER on failure
1570 API_EXPORTED int libusb_get_next_timeout(libusb_context *ctx,
1573 struct usbi_transfer *transfer;
1574 struct timespec cur_ts;
1575 struct timeval cur_tv;
1576 struct timeval *next_timeout;
1580 USBI_GET_CONTEXT(ctx);
1581 pthread_mutex_lock(&ctx->flying_transfers_lock);
1582 if (list_empty(&ctx->flying_transfers)) {
1583 pthread_mutex_unlock(&ctx->flying_transfers_lock);
1584 usbi_dbg("no URBs, no timeout!");
1588 /* find next transfer which hasn't already been processed as timed out */
1589 list_for_each_entry(transfer, &ctx->flying_transfers, list) {
1590 if (!(transfer->flags & USBI_TRANSFER_TIMED_OUT)) {
1595 pthread_mutex_unlock(&ctx->flying_transfers_lock);
1598 usbi_dbg("all URBs have already been processed for timeouts");
1602 next_timeout = &transfer->timeout;
1604 /* no timeout for next transfer */
1605 if (!timerisset(next_timeout)) {
1606 usbi_dbg("no URBs with timeouts, no timeout!");
1610 r = clock_gettime(CLOCK_MONOTONIC, &cur_ts);
1612 usbi_err(ctx, "failed to read monotonic clock, errno=%d", errno);
1613 return LIBUSB_ERROR_OTHER;
1615 TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts);
1617 if (timercmp(&cur_tv, next_timeout, >=)) {
1618 usbi_dbg("first timeout already expired");
1621 timersub(next_timeout, &cur_tv, tv);
1622 usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec);
1629 * Register notification functions for file descriptor additions/removals.
1630 * These functions will be invoked for every new or removed file descriptor
1631 * that libusb uses as an event source.
1633 * To remove notifiers, pass NULL values for the function pointers.
1635 * \param ctx the context to operate on, or NULL for the default context
1636 * \param added_cb pointer to function for addition notifications
1637 * \param removed_cb pointer to function for removal notifications
1638 * \param user_data User data to be passed back to callbacks (useful for
1639 * passing context information)
1641 API_EXPORTED void libusb_set_pollfd_notifiers(libusb_context *ctx,
1642 libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
1645 USBI_GET_CONTEXT(ctx);
1646 ctx->fd_added_cb = added_cb;
1647 ctx->fd_removed_cb = removed_cb;
1648 ctx->fd_cb_user_data = user_data;
1651 /* Add a file descriptor to the list of file descriptors to be monitored.
1652 * events should be specified as a bitmask of events passed to poll(), e.g.
1653 * POLLIN and/or POLLOUT. */
1654 int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events)
1656 struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
1658 return LIBUSB_ERROR_NO_MEM;
1660 usbi_dbg("add fd %d events %d", fd, events);
1661 ipollfd->pollfd.fd = fd;
1662 ipollfd->pollfd.events = events;
1663 pthread_mutex_lock(&ctx->pollfds_lock);
1664 list_add(&ipollfd->list, &ctx->pollfds);
1665 pthread_mutex_unlock(&ctx->pollfds_lock);
1667 if (ctx->fd_added_cb)
1668 ctx->fd_added_cb(fd, events, ctx->fd_cb_user_data);
1672 /* Remove a file descriptor from the list of file descriptors to be polled. */
1673 void usbi_remove_pollfd(struct libusb_context *ctx, int fd)
1675 struct usbi_pollfd *ipollfd;
1678 usbi_dbg("remove fd %d", fd);
1679 pthread_mutex_lock(&ctx->pollfds_lock);
1680 list_for_each_entry(ipollfd, &ctx->pollfds, list)
1681 if (ipollfd->pollfd.fd == fd) {
1687 usbi_dbg("couldn't find fd %d to remove", fd);
1688 pthread_mutex_unlock(&ctx->pollfds_lock);
1692 list_del(&ipollfd->list);
1693 pthread_mutex_unlock(&ctx->pollfds_lock);
1695 if (ctx->fd_removed_cb)
1696 ctx->fd_removed_cb(fd, ctx->fd_cb_user_data);
1700 * Retrieve a list of file descriptors that should be polled by your main loop
1701 * as libusb event sources.
1703 * The returned list is NULL-terminated and should be freed with free() when
1704 * done. The actual list contents must not be touched.
1706 * \param ctx the context to operate on, or NULL for the default context
1707 * \returns a NULL-terminated list of libusb_pollfd structures, or NULL on
1710 API_EXPORTED const struct libusb_pollfd **libusb_get_pollfds(
1711 libusb_context *ctx)
1713 struct libusb_pollfd **ret = NULL;
1714 struct usbi_pollfd *ipollfd;
1717 USBI_GET_CONTEXT(ctx);
1719 pthread_mutex_lock(&ctx->pollfds_lock);
1720 list_for_each_entry(ipollfd, &ctx->pollfds, list)
1723 ret = calloc(cnt + 1, sizeof(struct libusb_pollfd *));
1727 list_for_each_entry(ipollfd, &ctx->pollfds, list)
1728 ret[i++] = (struct libusb_pollfd *) ipollfd;
1732 pthread_mutex_unlock(&ctx->pollfds_lock);
1733 return (const struct libusb_pollfd **) ret;
1736 /* Backends call this from handle_events to report disconnection of a device.
1737 * The transfers get cancelled appropriately.
1739 void usbi_handle_disconnect(struct libusb_device_handle *handle)
1741 struct usbi_transfer *cur;
1742 struct usbi_transfer *to_cancel;
1744 usbi_dbg("device %d.%d",
1745 handle->dev->bus_number, handle->dev->device_address);
1747 /* terminate all pending transfers with the LIBUSB_TRANSFER_NO_DEVICE
1750 * this is a bit tricky because:
1751 * 1. we can't do transfer completion while holding flying_transfers_lock
1752 * 2. the transfers list can change underneath us - if we were to build a
1753 * list of transfers to complete (while holding look), the situation
1754 * might be different by the time we come to free them
1756 * so we resort to a loop-based approach as below
1757 * FIXME: is this still potentially racy?
1761 pthread_mutex_lock(&HANDLE_CTX(handle)->flying_transfers_lock);
1763 list_for_each_entry(cur, &HANDLE_CTX(handle)->flying_transfers, list)
1764 if (__USBI_TRANSFER_TO_LIBUSB_TRANSFER(cur)->dev_handle == handle) {
1768 pthread_mutex_unlock(&HANDLE_CTX(handle)->flying_transfers_lock);
1773 usbi_backend->clear_transfer_priv(to_cancel);
1774 usbi_handle_transfer_completion(to_cancel, LIBUSB_TRANSFER_NO_DEVICE);