Update to new libusb
[bcusdk.git] / eibd / usb / io.c
blob388bd018c10cfb571a4b022f63fc7d548c64f9f9
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>
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
21 #define _GNU_SOURCE
23 #include <config.h>
24 #include <errno.h>
25 #include <poll.h>
26 #include <pthread.h>
27 #include <signal.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/time.h>
32 #include <time.h>
33 #include <unistd.h>
35 #include "libusbi.h"
37 /**
38 * \page io Synchronous and asynchronous device I/O
40 * \section intro Introduction
42 * If you're using libusb in your application, you're probably wanting to
43 * perform I/O with devices - you want to perform USB data transfers.
45 * libusb offers two separate interfaces for device I/O. This page aims to
46 * introduce the two in order to help you decide which one is more suitable
47 * for your application. You can also choose to use both interfaces in your
48 * application by considering each transfer on a case-by-case basis.
50 * Once you have read through the following discussion, you should consult the
51 * detailed API documentation pages for the details:
52 * - \ref syncio
53 * - \ref asyncio
55 * \section theory Transfers at a logical level
57 * At a logical level, USB transfers typically happen in two parts. For
58 * example, when reading data from a endpoint:
59 * -# A request for data is sent to the device
60 * -# Some time later, the incoming data is received by the host
62 * or when writing data to an endpoint:
64 * -# The data is sent to the device
65 * -# Some time later, the host receives acknowledgement from the device that
66 * the data has been transferred.
68 * There may be an indefinite delay between the two steps. Consider a
69 * fictional USB input device with a button that the user can press. In order
70 * to determine when the button is pressed, you would likely submit a request
71 * to read data on a bulk or interrupt endpoint and wait for data to arrive.
72 * Data will arrive when the button is pressed by the user, which is
73 * potentially hours later.
75 * libusb offers both a synchronous and an asynchronous interface to performing
76 * USB transfers. The main difference is that the synchronous interface
77 * combines both steps indicated above into a single function call, whereas
78 * the asynchronous interface separates them.
80 * \section sync The synchronous interface
82 * The synchronous I/O interface allows you to perform a USB transfer with
83 * a single function call. When the function call returns, the transfer has
84 * completed and you can parse the results.
86 * If you have used the libusb-0.1 before, this I/O style will seem familar to
87 * you. libusb-0.1 only offered a synchronous interface.
89 * In our input device example, to read button presses you might write code
90 * in the following style:
91 \code
92 unsigned char data[4];
93 int actual_length,
94 int r = libusb_bulk_transfer(handle, EP_IN, data, sizeof(data), &actual_length, 0);
95 if (r == 0 && actual_length == sizeof(data)) {
96 // results of the transaction can now be found in the data buffer
97 // parse them here and report button press
98 } else {
99 error();
101 \endcode
103 * The main advantage of this model is simplicity: you did everything with
104 * a single simple function call.
106 * However, this interface has its limitations. Your application will sleep
107 * inside libusb_bulk_transfer() until the transaction has completed. If it
108 * takes the user 3 hours to press the button, your application will be
109 * sleeping for that long. Execution will be tied up inside the library -
110 * the entire thread will be useless for that duration.
112 * Another issue is that by tieing up the thread with that single transaction
113 * there is no possibility of performing I/O with multiple endpoints and/or
114 * multiple devices simultaneously, unless you resort to creating one thread
115 * per transaction.
117 * Additionally, there is no opportunity to cancel the transfer after the
118 * request has been submitted.
120 * For details on how to use the synchronous API, see the
121 * \ref syncio "synchronous I/O API documentation" pages.
123 * \section async The asynchronous interface
125 * Asynchronous I/O is the most significant new feature in libusb-1.0.
126 * Although it is a more complex interface, it solves all the issues detailed
127 * above.
129 * Instead of providing which functions that block until the I/O has complete,
130 * libusb's asynchronous interface presents non-blocking functions which
131 * begin a transfer and then return immediately. Your application passes a
132 * callback function pointer to this non-blocking function, which libusb will
133 * call with the results of the transaction when it has completed.
135 * Transfers which have been submitted through the non-blocking functions
136 * can be cancelled with a separate function call.
138 * The non-blocking nature of this interface allows you to be simultaneously
139 * performing I/O to multiple endpoints on multiple devices, without having
140 * to use threads.
142 * This added flexibility does come with some complications though:
143 * - In the interest of being a lightweight library, libusb does not create
144 * threads and can only operate when your application is calling into it. Your
145 * application must call into libusb from it's main loop when events are ready
146 * to be handled, or you must use some other scheme to allow libusb to
147 * undertake whatever work needs to be done.
148 * - libusb also needs to be called into at certain fixed points in time in
149 * order to accurately handle transfer timeouts.
150 * - Memory handling becomes more complex. You cannot use stack memory unless
151 * the function with that stack is guaranteed not to return until the transfer
152 * callback has finished executing.
153 * - You generally lose some linearity from your code flow because submitting
154 * the transfer request is done in a separate function from where the transfer
155 * results are handled. This becomes particularly obvious when you want to
156 * submit a second transfer based on the results of an earlier transfer.
158 * Internally, libusb's synchronous interface is expressed in terms of function
159 * calls to the asynchronous interface.
161 * For details on how to use the asynchronous API, see the
162 * \ref asyncio "asynchronous I/O API" documentation pages.
167 * \page packetoverflow Packets and overflows
169 * \section packets Packet abstraction
171 * The USB specifications describe how data is transmitted in packets, with
172 * constraints on packet size defined by endpoint descriptors. The host must
173 * not send data payloads larger than the endpoint's maximum packet size.
175 * libusb and the underlying OS abstract out the packet concept, allowing you
176 * to request transfers of any size. Internally, the request will be divided
177 * up into correctly-sized packets. You do not have to be concerned with
178 * packet sizes, but there is one exception when considering overflows.
180 * \section overflow Bulk/interrupt transfer overflows
182 * When requesting data on a bulk endpoint, libusb requires you to supply a
183 * buffer and the maximum number of bytes of data that libusb can put in that
184 * buffer. However, the size of the buffer is not communicated to the device -
185 * the device is just asked to send any amount of data.
187 * There is no problem if the device sends an amount of data that is less than
188 * or equal to the buffer size. libusb reports this condition to you through
189 * the \ref libusb_transfer::actual_length "libusb_transfer.actual_length"
190 * field.
192 * Problems may occur if the device attempts to send more data than can fit in
193 * the buffer. libusb reports LIBUSB_TRANSFER_OVERFLOW for this condition but
194 * other behaviour is largely undefined: actual_length may or may not be
195 * accurate, the chunk of data that can fit in the buffer (before overflow)
196 * may or may not have been transferred.
198 * Overflows are nasty, but can be avoided. Even though you were told to
199 * ignore packets above, think about the lower level details: each transfer is
200 * split into packets (typically small, with a maximum size of 512 bytes).
201 * Overflows can only happen if the final packet in an incoming data transfer
202 * is smaller than the actual packet that the device wants to transfer.
203 * Therefore, you will never see an overflow if your transfer buffer size is a
204 * multiple of the endpoint's packet size: the final packet will either
205 * fill up completely or will be only partially filled.
209 * @defgroup asyncio Asynchronous device I/O
211 * This page details libusb's asynchronous (non-blocking) API for USB device
212 * I/O. This interface is very powerful but is also quite complex - you will
213 * need to read this page carefully to understand the necessary considerations
214 * and issues surrounding use of this interface. Simplistic applications
215 * may wish to consider the \ref syncio "synchronous I/O API" instead.
217 * The asynchronous interface is built around the idea of separating transfer
218 * submission and handling of transfer completion (the synchronous model
219 * combines both of these into one). There may be a long delay between
220 * submission and completion, however the asynchronous submission function
221 * is non-blocking so will return control to your application during that
222 * potentially long delay.
224 * \section asyncabstraction Transfer abstraction
226 * For the asynchronous I/O, libusb implements the concept of a generic
227 * transfer entity for all types of I/O (control, bulk, interrupt,
228 * isochronous). The generic transfer object must be treated slightly
229 * differently depending on which type of I/O you are performing with it.
231 * This is represented by the public libusb_transfer structure type.
233 * \section asynctrf Asynchronous transfers
235 * We can view asynchronous I/O as a 5 step process:
236 * -# <b>Allocation</b>: allocate a libusb_transfer
237 * -# <b>Filling</b>: populate the libusb_transfer instance with information
238 * about the transfer you wish to perform
239 * -# <b>Submission</b>: ask libusb to submit the transfer
240 * -# <b>Completion handling</b>: examine transfer results in the
241 * libusb_transfer structure
242 * -# <b>Deallocation</b>: clean up resources
245 * \subsection asyncalloc Allocation
247 * This step involves allocating memory for a USB transfer. This is the
248 * generic transfer object mentioned above. At this stage, the transfer
249 * is "blank" with no details about what type of I/O it will be used for.
251 * Allocation is done with the libusb_alloc_transfer() function. You must use
252 * this function rather than allocating your own transfers.
254 * \subsection asyncfill Filling
256 * This step is where you take a previously allocated transfer and fill it
257 * with information to determine the message type and direction, data buffer,
258 * callback function, etc.
260 * You can either fill the required fields yourself or you can use the
261 * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer()
262 * and libusb_fill_interrupt_transfer().
264 * \subsection asyncsubmit Submission
266 * When you have allocated a transfer and filled it, you can submit it using
267 * libusb_submit_transfer(). This function returns immediately but can be
268 * regarded as firing off the I/O request in the background.
270 * \subsection asynccomplete Completion handling
272 * After a transfer has been submitted, one of four things can happen to it:
274 * - The transfer completes (i.e. some data was transferred)
275 * - The transfer has a timeout and the timeout expires before all data is
276 * transferred
277 * - The transfer fails due to an error
278 * - The transfer is cancelled
280 * Each of these will cause the user-specified transfer callback function to
281 * be invoked. It is up to the callback function to determine which of the
282 * above actually happened and to act accordingly.
284 * The user-specified callback is passed a pointer to the libusb_transfer
285 * structure which was used to setup and submit the transfer. At completion
286 * time, libusb has populated this structure with results of the transfer:
287 * success or failure reason, number of bytes of data transferred, etc. See
288 * the libusb_transfer structure documentation for more information.
290 * \subsection Deallocation
292 * When a transfer has completed (i.e. the callback function has been invoked),
293 * you are advised to free the transfer (unless you wish to resubmit it, see
294 * below). Transfers are deallocated with libusb_free_transfer().
296 * It is undefined behaviour to free a transfer which has not completed.
298 * \section asyncresubmit Resubmission
300 * You may be wondering why allocation, filling, and submission are all
301 * separated above where they could reasonably be combined into a single
302 * operation.
304 * The reason for separation is to allow you to resubmit transfers without
305 * having to allocate new ones every time. This is especially useful for
306 * common situations dealing with interrupt endpoints - you allocate one
307 * transfer, fill and submit it, and when it returns with results you just
308 * resubmit it for the next interrupt.
310 * \section asynccancel Cancellation
312 * Another advantage of using the asynchronous interface is that you have
313 * the ability to cancel transfers which have not yet completed. This is
314 * done by calling the libusb_cancel_transfer() function.
316 * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the
317 * cancellation actually completes, the transfer's callback function will
318 * be invoked, and the callback function should check the transfer status to
319 * determine that it was cancelled.
321 * Freeing the transfer after it has been cancelled but before cancellation
322 * has completed will result in undefined behaviour.
324 * \section bulk_overflows Overflows on device-to-host bulk/interrupt endpoints
326 * If your device does not have predictable transfer sizes (or it misbehaves),
327 * your application may submit a request for data on an IN endpoint which is
328 * smaller than the data that the device wishes to send. In some circumstances
329 * this will cause an overflow, which is a nasty condition to deal with. See
330 * the \ref packetoverflow page for discussion.
332 * \section asyncctrl Considerations for control transfers
334 * The <tt>libusb_transfer</tt> structure is generic and hence does not
335 * include specific fields for the control-specific setup packet structure.
337 * In order to perform a control transfer, you must place the 8-byte setup
338 * packet at the start of the data buffer. To simplify this, you could
339 * cast the buffer pointer to type struct libusb_control_setup, or you can
340 * use the helper function libusb_fill_control_setup().
342 * The wLength field placed in the setup packet must be the length you would
343 * expect to be sent in the setup packet: the length of the payload that
344 * follows (or the expected maximum number of bytes to receive). However,
345 * the length field of the libusb_transfer object must be the length of
346 * the data buffer - i.e. it should be wLength <em>plus</em> the size of
347 * the setup packet (LIBUSB_CONTROL_SETUP_SIZE).
349 * If you use the helper functions, this is simplified for you:
350 * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the
351 * data you are sending/requesting.
352 * -# Call libusb_fill_control_setup() on the data buffer, using the transfer
353 * request size as the wLength value (i.e. do not include the extra space you
354 * allocated for the control setup).
355 * -# If this is a host-to-device transfer, place the data to be transferred
356 * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE.
357 * -# Call libusb_fill_control_transfer() to associate the data buffer with
358 * the transfer (and to set the remaining details such as callback and timeout).
359 * - Note that there is no parameter to set the length field of the transfer.
360 * The length is automatically inferred from the wLength field of the setup
361 * packet.
362 * -# Submit the transfer.
364 * The multi-byte control setup fields (wValue, wIndex and wLength) must
365 * be given in little-endian byte order (the endianness of the USB bus).
366 * Endianness conversion is transparently handled by
367 * libusb_fill_control_setup() which is documented to accept host-endian
368 * values.
370 * Further considerations are needed when handling transfer completion in
371 * your callback function:
372 * - As you might expect, the setup packet will still be sitting at the start
373 * of the data buffer.
374 * - If this was a device-to-host transfer, the received data will be sitting
375 * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer.
376 * - The actual_length field of the transfer structure is relative to the
377 * wLength of the setup packet, rather than the size of the data buffer. So,
378 * if your wLength was 4, your transfer's <tt>length</tt> was 12, then you
379 * should expect an <tt>actual_length</tt> of 4 to indicate that the data was
380 * transferred in entirity.
382 * To simplify parsing of setup packets and obtaining the data from the
383 * correct offset, you may wish to use the libusb_control_transfer_get_data()
384 * and libusb_control_transfer_get_setup() functions within your transfer
385 * callback.
387 * Even though control endpoints do not halt, a completed control transfer
388 * may have a LIBUSB_TRANSFER_STALL status code. This indicates the control
389 * request was not supported.
391 * \section asyncintr Considerations for interrupt transfers
393 * All interrupt transfers are performed using the polling interval presented
394 * by the bInterval value of the endpoint descriptor.
396 * \section asynciso Considerations for isochronous transfers
398 * Isochronous transfers are more complicated than transfers to
399 * non-isochronous endpoints.
401 * To perform I/O to an isochronous endpoint, allocate the transfer by calling
402 * libusb_alloc_transfer() with an appropriate number of isochronous packets.
404 * During filling, set \ref libusb_transfer::type "type" to
405 * \ref libusb_transfer_type::LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
406 * "LIBUSB_TRANSFER_TYPE_ISOCHRONOUS", and set
407 * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than
408 * or equal to the number of packets you requested during allocation.
409 * libusb_alloc_transfer() does not set either of these fields for you, given
410 * that you might not even use the transfer on an isochronous endpoint.
412 * Next, populate the length field for the first num_iso_packets entries in
413 * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section
414 * 5.6.3 of the USB2 specifications describe how the maximum isochronous
415 * packet length is determined by wMaxPacketSize field in the endpoint
416 * descriptor. Two functions can help you here:
418 * - libusb_get_max_packet_size() is an easy way to determine the max
419 * packet size for an endpoint.
420 * - libusb_set_iso_packet_lengths() assigns the same length to all packets
421 * within a transfer, which is usually what you want.
423 * For outgoing transfers, you'll obviously fill the buffer and populate the
424 * packet descriptors in hope that all the data gets transferred. For incoming
425 * transfers, you must ensure the buffer has sufficient capacity for
426 * the situation where all packets transfer the full amount of requested data.
428 * Completion handling requires some extra consideration. The
429 * \ref libusb_transfer::actual_length "actual_length" field of the transfer
430 * is meaningless and should not be examined; instead you must refer to the
431 * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of
432 * each individual packet.
434 * The \ref libusb_transfer::status "status" field of the transfer is also a
435 * little misleading:
436 * - If the packets were submitted and the isochronous data microframes
437 * completed normally, status will have value
438 * \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED
439 * "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred
440 * delays are not counted as transfer errors; the transfer.status field may
441 * indicate COMPLETED even if some or all of the packets failed. Refer to
442 * the \ref libusb_iso_packet_descriptor::status "status" field of each
443 * individual packet to determine packet failures.
444 * - The status field will have value
445 * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR
446 * "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered.
447 * - Other transfer status codes occur with normal behaviour.
449 * The data for each packet will be found at an offset into the buffer that
450 * can be calculated as if each prior packet completed in full. The
451 * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple()
452 * functions may help you here.
454 * \section asyncmem Memory caveats
456 * In most circumstances, it is not safe to use stack memory for transfer
457 * buffers. This is because the function that fired off the asynchronous
458 * transfer may return before libusb has finished using the buffer, and when
459 * the function returns it's stack gets destroyed. This is true for both
460 * host-to-device and device-to-host transfers.
462 * The only case in which it is safe to use stack memory is where you can
463 * guarantee that the function owning the stack space for the buffer does not
464 * return until after the transfer's callback function has completed. In every
465 * other case, you need to use heap memory instead.
467 * \section asyncflags Fine control
469 * Through using this asynchronous interface, you may find yourself repeating
470 * a few simple operations many times. You can apply a bitwise OR of certain
471 * flags to a transfer to simplify certain things:
472 * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK
473 * "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred
474 * less than the requested amount of data being marked with status
475 * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR"
476 * (they would normally be regarded as COMPLETED)
477 * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
478 * "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer
479 * buffer when freeing the transfer.
480 * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER
481 * "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the
482 * transfer after the transfer callback returns.
484 * \section asyncevent Event handling
486 * In accordance of the aim of being a lightweight library, libusb does not
487 * create threads internally. This means that libusb code does not execute
488 * at any time other than when your application is calling a libusb function.
489 * However, an asynchronous model requires that libusb perform work at various
490 * points in time - namely processing the results of previously-submitted
491 * transfers and invoking the user-supplied callback function.
493 * This gives rise to the libusb_handle_events() function which your
494 * application must call into when libusb has work do to. This gives libusb
495 * the opportunity to reap pending transfers, invoke callbacks, etc.
497 * The first issue to discuss here is how your application can figure out
498 * when libusb has work to do. In fact, there are two naive options which
499 * do not actually require your application to know this:
500 * -# Periodically call libusb_handle_events() in non-blocking mode at fixed
501 * short intervals from your main loop
502 * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated
503 * thread.
505 * The first option is plainly not very nice, and will cause unnecessary
506 * CPU wakeups leading to increased power usage and decreased battery life.
507 * The second option is not very nice either, but may be the nicest option
508 * available to you if the "proper" approach can not be applied to your
509 * application (read on...).
511 * The recommended option is to integrate libusb with your application main
512 * event loop. libusb exposes a set of file descriptors which allow you to do
513 * this. Your main loop is probably already calling poll() or select() or a
514 * variant on a set of file descriptors for other event sources (e.g. keyboard
515 * button presses, mouse movements, network sockets, etc). You then add
516 * libusb's file descriptors to your poll()/select() calls, and when activity
517 * is detected on such descriptors you know it is time to call
518 * libusb_handle_events().
520 * There is one final event handling complication. libusb supports
521 * asynchronous transfers which time out after a specified time period, and
522 * this requires that libusb is called into at or after the timeout so that
523 * the timeout can be handled. So, in addition to considering libusb's file
524 * descriptors in your main event loop, you must also consider that libusb
525 * sometimes needs to be called into at fixed points in time even when there
526 * is no file descriptor activity.
528 * For the details on retrieving the set of file descriptors and determining
529 * the next timeout, see the \ref poll "polling and timing" API documentation.
533 * @defgroup poll Polling and timing
535 * This page documents libusb's functions for polling events and timing.
536 * These functions are only necessary for users of the
537 * \ref asyncio "asynchronous API". If you are only using the simpler
538 * \ref syncio "synchronous API" then you do not need to ever call these
539 * functions.
541 * The justification for the functionality described here has already been
542 * discussed in the \ref asyncevent "event handling" section of the
543 * asynchronous API documentation. In summary, libusb does not create internal
544 * threads for event processing and hence relies on your application calling
545 * into libusb at certain points in time so that pending events can be handled.
546 * In order to know precisely when libusb needs to be called into, libusb
547 * offers you a set of pollable file descriptors and information about when
548 * the next timeout expires.
550 * If you are using the asynchronous I/O API, you must take one of the two
551 * following options, otherwise your I/O will not complete.
553 * \section pollsimple The simple option
555 * If your application revolves solely around libusb and does not need to
556 * handle other event sources, you can have a program structure as follows:
557 \code
558 // initialize libusb
559 // find and open device
560 // maybe fire off some initial async I/O
562 while (user_has_not_requested_exit)
563 libusb_handle_events(ctx);
565 // clean up and exit
566 \endcode
568 * With such a simple main loop, you do not have to worry about managing
569 * sets of file descriptors or handling timeouts. libusb_handle_events() will
570 * handle those details internally.
572 * \section pollmain The more advanced option
574 * In more advanced applications, you will already have a main loop which
575 * is monitoring other event sources: network sockets, X11 events, mouse
576 * movements, etc. Through exposing a set of file descriptors, libusb is
577 * designed to cleanly integrate into such main loops.
579 * In addition to polling file descriptors for the other event sources, you
580 * take a set of file descriptors from libusb and monitor those too. When you
581 * detect activity on libusb's file descriptors, you call
582 * libusb_handle_events_timeout() in non-blocking mode.
584 * You must also consider the fact that libusb sometimes has to handle events
585 * at certain known times which do not generate activity on file descriptors.
586 * Your main loop must also consider these times, modify it's poll()/select()
587 * timeout accordingly, and track time so that libusb_handle_events_timeout()
588 * is called in non-blocking mode when timeouts expire.
590 * In pseudo-code, you want something that looks like:
591 \code
592 // initialise libusb
594 libusb_get_pollfds(ctx)
595 while (user has not requested application exit) {
596 libusb_get_next_timeout(ctx);
597 select(on libusb file descriptors plus any other event sources of interest,
598 using a timeout no larger than the value libusb just suggested)
599 if (select() indicated activity on libusb file descriptors)
600 libusb_handle_events_timeout(ctx, 0);
601 if (time has elapsed to or beyond the libusb timeout)
602 libusb_handle_events_timeout(ctx, 0);
605 // clean up and exit
606 \endcode
608 * The set of file descriptors that libusb uses as event sources may change
609 * during the life of your application. Rather than having to repeatedly
610 * call libusb_get_pollfds(), you can set up notification functions for when
611 * the file descriptor set changes using libusb_set_pollfd_notifiers().
613 * \section mtissues Multi-threaded considerations
615 * Unfortunately, the situation is complicated further when multiple threads
616 * come into play. If two threads are monitoring the same file descriptors,
617 * the fact that only one thread will be woken up when an event occurs causes
618 * some headaches.
620 * The events lock, event waiters lock, and libusb_handle_events_locked()
621 * entities are added to solve these problems. You do not need to be concerned
622 * with these entities otherwise.
624 * See the extra documentation: \ref mtasync
627 /** \page mtasync Multi-threaded applications and asynchronous I/O
629 * libusb is a thread-safe library, but extra considerations must be applied
630 * to applications which interact with libusb from multiple threads.
632 * The underlying issue that must be addressed is that all libusb I/O
633 * revolves around monitoring file descriptors through the poll()/select()
634 * system calls. This is directly exposed at the
635 * \ref asyncio "asynchronous interface" but it is important to note that the
636 * \ref syncio "synchronous interface" is implemented on top of the
637 * asynchonrous interface, therefore the same considerations apply.
639 * The issue is that if two or more threads are concurrently calling poll()
640 * or select() on libusb's file descriptors then only one of those threads
641 * will be woken up when an event arrives. The others will be completely
642 * oblivious that anything has happened.
644 * Consider the following pseudo-code, which submits an asynchronous transfer
645 * then waits for its completion. This style is one way you could implement a
646 * synchronous interface on top of the asynchronous interface (and libusb
647 * does something similar, albeit more advanced due to the complications
648 * explained on this page).
650 \code
651 void cb(struct libusb_transfer *transfer)
653 int *completed = transfer->user_data;
654 *completed = 1;
657 void myfunc() {
658 struct libusb_transfer *transfer;
659 unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE];
660 int completed = 0;
662 transfer = libusb_alloc_transfer(0);
663 libusb_fill_control_setup(buffer,
664 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x04, 0x01, 0, 0);
665 libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000);
666 libusb_submit_transfer(transfer);
668 while (!completed) {
669 poll(libusb file descriptors, 120*1000);
670 if (poll indicates activity)
671 libusb_handle_events_timeout(ctx, 0);
673 printf("completed!");
674 // other code here
676 \endcode
678 * Here we are <em>serializing</em> completion of an asynchronous event
679 * against a condition - the condition being completion of a specific transfer.
680 * The poll() loop has a long timeout to minimize CPU usage during situations
681 * when nothing is happening (it could reasonably be unlimited).
683 * If this is the only thread that is polling libusb's file descriptors, there
684 * is no problem: there is no danger that another thread will swallow up the
685 * event that we are interested in. On the other hand, if there is another
686 * thread polling the same descriptors, there is a chance that it will receive
687 * the event that we were interested in. In this situation, <tt>myfunc()</tt>
688 * will only realise that the transfer has completed on the next iteration of
689 * the loop, <em>up to 120 seconds later.</em> Clearly a two-minute delay is
690 * undesirable, and don't even think about using short timeouts to circumvent
691 * this issue!
693 * The solution here is to ensure that no two threads are ever polling the
694 * file descriptors at the same time. A naive implementation of this would
695 * impact the capabilities of the library, so libusb offers the scheme
696 * documented below to ensure no loss of functionality.
698 * Before we go any further, it is worth mentioning that all libusb-wrapped
699 * event handling procedures fully adhere to the scheme documented below.
700 * This includes libusb_handle_events() and all the synchronous I/O functions -
701 * libusb hides this headache from you. You do not need to worry about any
702 * of these issues if you stick to that level.
704 * The problem is when we consider the fact that libusb exposes file
705 * descriptors to allow for you to integrate asynchronous USB I/O into
706 * existing main loops, effectively allowing you to do some work behind
707 * libusb's back. If you do take libusb's file descriptors and pass them to
708 * poll()/select() yourself, you need to be aware of the associated issues.
710 * \section eventlock The events lock
712 * The first concept to be introduced is the events lock. The events lock
713 * is used to serialize threads that want to handle events, such that only
714 * one thread is handling events at any one time.
716 * You must take the events lock before polling libusb file descriptors,
717 * using libusb_lock_events(). You must release the lock as soon as you have
718 * aborted your poll()/select() loop, using libusb_unlock_events().
720 * \section threadwait Letting other threads do the work for you
722 * Although the events lock is a critical part of the solution, it is not
723 * enough on it's own. You might wonder if the following is sufficient...
724 \code
725 libusb_lock_events(ctx);
726 while (!completed) {
727 poll(libusb file descriptors, 120*1000);
728 if (poll indicates activity)
729 libusb_handle_events_timeout(ctx, 0);
731 libusb_unlock_events(ctx);
732 \endcode
733 * ...and the answer is that it is not. This is because the transfer in the
734 * code shown above may take a long time (say 30 seconds) to complete, and
735 * the lock is not released until the transfer is completed.
737 * Another thread with similar code that wants to do event handling may be
738 * working with a transfer that completes after a few milliseconds. Despite
739 * having such a quick completion time, the other thread cannot check that
740 * status of its transfer until the code above has finished (30 seconds later)
741 * due to contention on the lock.
743 * To solve this, libusb offers you a mechanism to determine when another
744 * thread is handling events. It also offers a mechanism to block your thread
745 * until the event handling thread has completed an event (and this mechanism
746 * does not involve polling of file descriptors).
748 * After determining that another thread is currently handling events, you
749 * obtain the <em>event waiters</em> lock using libusb_lock_event_waiters().
750 * You then re-check that some other thread is still handling events, and if
751 * so, you call libusb_wait_for_event().
753 * libusb_wait_for_event() puts your application to sleep until an event
754 * occurs, or until a thread releases the events lock. When either of these
755 * things happen, your thread is woken up, and should re-check the condition
756 * it was waiting on. It should also re-check that another thread is handling
757 * events, and if not, it should start handling events itself.
759 * This looks like the following, as pseudo-code:
760 \code
761 retry:
762 if (libusb_try_lock_events(ctx) == 0) {
763 // we obtained the event lock: do our own event handling
764 while (!completed) {
765 if (!libusb_event_handling_ok(ctx)) {
766 libusb_unlock_events(ctx);
767 goto retry;
769 poll(libusb file descriptors, 120*1000);
770 if (poll indicates activity)
771 libusb_handle_events_locked(ctx, 0);
773 libusb_unlock_events(ctx);
774 } else {
775 // another thread is doing event handling. wait for it to signal us that
776 // an event has completed
777 libusb_lock_event_waiters(ctx);
779 while (!completed) {
780 // now that we have the event waiters lock, double check that another
781 // thread is still handling events for us. (it may have ceased handling
782 // events in the time it took us to reach this point)
783 if (!libusb_event_handler_active(ctx)) {
784 // whoever was handling events is no longer doing so, try again
785 libusb_unlock_event_waiters(ctx);
786 goto retry;
789 libusb_wait_for_event(ctx);
791 libusb_unlock_event_waiters(ctx);
793 printf("completed!\n");
794 \endcode
796 * A naive look at the above code may suggest that this can only support
797 * one event waiter (hence a total of 2 competing threads, the other doing
798 * event handling), because the event waiter seems to have taken the event
799 * waiters lock while waiting for an event. However, the system does support
800 * multiple event waiters, because libusb_wait_for_event() actually drops
801 * the lock while waiting, and reaquires it before continuing.
803 * We have now implemented code which can dynamically handle situations where
804 * nobody is handling events (so we should do it ourselves), and it can also
805 * handle situations where another thread is doing event handling (so we can
806 * piggyback onto them). It is also equipped to handle a combination of
807 * the two, for example, another thread is doing event handling, but for
808 * whatever reason it stops doing so before our condition is met, so we take
809 * over the event handling.
811 * Four functions were introduced in the above pseudo-code. Their importance
812 * should be apparent from the code shown above.
813 * -# libusb_try_lock_events() is a non-blocking function which attempts
814 * to acquire the events lock but returns a failure code if it is contended.
815 * -# libusb_event_handling_ok() checks that libusb is still happy for your
816 * thread to be performing event handling. Sometimes, libusb needs to
817 * interrupt the event handler, and this is how you can check if you have
818 * been interrupted. If this function returns 0, the correct behaviour is
819 * for you to give up the event handling lock, and then to repeat the cycle.
820 * The following libusb_try_lock_events() will fail, so you will become an
821 * events waiter. For more information on this, read \ref fullstory below.
822 * -# libusb_handle_events_locked() is a variant of
823 * libusb_handle_events_timeout() that you can call while holding the
824 * events lock. libusb_handle_events_timeout() itself implements similar
825 * logic to the above, so be sure not to call it when you are
826 * "working behind libusb's back", as is the case here.
827 * -# libusb_event_handler_active() determines if someone is currently
828 * holding the events lock
830 * You might be wondering why there is no function to wake up all threads
831 * blocked on libusb_wait_for_event(). This is because libusb can do this
832 * internally: it will wake up all such threads when someone calls
833 * libusb_unlock_events() or when a transfer completes (at the point after its
834 * callback has returned).
836 * \subsection fullstory The full story
838 * The above explanation should be enough to get you going, but if you're
839 * really thinking through the issues then you may be left with some more
840 * questions regarding libusb's internals. If you're curious, read on, and if
841 * not, skip to the next section to avoid confusing yourself!
843 * The immediate question that may spring to mind is: what if one thread
844 * modifies the set of file descriptors that need to be polled while another
845 * thread is doing event handling?
847 * There are 2 situations in which this may happen.
848 * -# libusb_open() will add another file descriptor to the poll set,
849 * therefore it is desirable to interrupt the event handler so that it
850 * restarts, picking up the new descriptor.
851 * -# libusb_close() will remove a file descriptor from the poll set. There
852 * are all kinds of race conditions that could arise here, so it is
853 * important that nobody is doing event handling at this time.
855 * libusb handles these issues internally, so application developers do not
856 * have to stop their event handlers while opening/closing devices. Here's how
857 * it works, focusing on the libusb_close() situation first:
859 * -# During initialization, libusb opens an internal pipe, and it adds the read
860 * end of this pipe to the set of file descriptors to be polled.
861 * -# During libusb_close(), libusb writes some dummy data on this control pipe.
862 * This immediately interrupts the event handler. libusb also records
863 * internally that it is trying to interrupt event handlers for this
864 * high-priority event.
865 * -# At this point, some of the functions described above start behaving
866 * differently:
867 * - libusb_event_handling_ok() starts returning 1, indicating that it is NOT
868 * OK for event handling to continue.
869 * - libusb_try_lock_events() starts returning 1, indicating that another
870 * thread holds the event handling lock, even if the lock is uncontended.
871 * - libusb_event_handler_active() starts returning 1, indicating that
872 * another thread is doing event handling, even if that is not true.
873 * -# The above changes in behaviour result in the event handler stopping and
874 * giving up the events lock very quickly, giving the high-priority
875 * libusb_close() operation a "free ride" to acquire the events lock. All
876 * threads that are competing to do event handling become event waiters.
877 * -# With the events lock held inside libusb_close(), libusb can safely remove
878 * a file descriptor from the poll set, in the safety of knowledge that
879 * nobody is polling those descriptors or trying to access the poll set.
880 * -# After obtaining the events lock, the close operation completes very
881 * quickly (usually a matter of milliseconds) and then immediately releases
882 * the events lock.
883 * -# At the same time, the behaviour of libusb_event_handling_ok() and friends
884 * reverts to the original, documented behaviour.
885 * -# The release of the events lock causes the threads that are waiting for
886 * events to be woken up and to start competing to become event handlers
887 * again. One of them will succeed; it will then re-obtain the list of poll
888 * descriptors, and USB I/O will then continue as normal.
890 * libusb_open() is similar, and is actually a more simplistic case. Upon a
891 * call to libusb_open():
893 * -# The device is opened and a file descriptor is added to the poll set.
894 * -# libusb sends some dummy data on the control pipe, and records that it
895 * is trying to modify the poll descriptor set.
896 * -# The event handler is interrupted, and the same behaviour change as for
897 * libusb_close() takes effect, causing all event handling threads to become
898 * event waiters.
899 * -# The libusb_open() implementation takes its free ride to the events lock.
900 * -# Happy that it has successfully paused the events handler, libusb_open()
901 * releases the events lock.
902 * -# The event waiter threads are all woken up and compete to become event
903 * handlers again. The one that succeeds will obtain the list of poll
904 * descriptors again, which will include the addition of the new device.
906 * \subsection concl Closing remarks
908 * The above may seem a little complicated, but hopefully I have made it clear
909 * why such complications are necessary. Also, do not forget that this only
910 * applies to applications that take libusb's file descriptors and integrate
911 * them into their own polling loops.
913 * You may decide that it is OK for your multi-threaded application to ignore
914 * some of the rules and locks detailed above, because you don't think that
915 * two threads can ever be polling the descriptors at the same time. If that
916 * is the case, then that's good news for you because you don't have to worry.
917 * But be careful here; remember that the synchronous I/O functions do event
918 * handling internally. If you have one thread doing event handling in a loop
919 * (without implementing the rules and locking semantics documented above)
920 * and another trying to send a synchronous USB transfer, you will end up with
921 * two threads monitoring the same descriptors, and the above-described
922 * undesirable behaviour occuring. The solution is for your polling thread to
923 * play by the rules; the synchronous I/O functions do so, and this will result
924 * in them getting along in perfect harmony.
926 * If you do have a dedicated thread doing event handling, it is perfectly
927 * legal for it to take the event handling lock for long periods of time. Any
928 * synchronous I/O functions you call from other threads will transparently
929 * fall back to the "event waiters" mechanism detailed above. The only
930 * consideration that your event handling thread must apply is the one related
931 * to libusb_event_handling_ok(): you must call this before every poll(), and
932 * give up the events lock if instructed.
935 int usbi_io_init(struct libusb_context *ctx)
937 int r;
939 pthread_mutex_init(&ctx->flying_transfers_lock, NULL);
940 pthread_mutex_init(&ctx->pollfds_lock, NULL);
941 pthread_mutex_init(&ctx->pollfd_modify_lock, NULL);
942 pthread_mutex_init(&ctx->events_lock, NULL);
943 pthread_mutex_init(&ctx->event_waiters_lock, NULL);
944 pthread_cond_init(&ctx->event_waiters_cond, NULL);
945 list_init(&ctx->flying_transfers);
946 list_init(&ctx->pollfds);
948 /* FIXME should use an eventfd on kernels that support it */
949 r = pipe(ctx->ctrl_pipe);
950 if (r < 0)
951 return LIBUSB_ERROR_OTHER;
953 r = usbi_add_pollfd(ctx, ctx->ctrl_pipe[0], POLLIN);
954 if (r < 0)
955 return r;
957 return 0;
960 void usbi_io_exit(struct libusb_context *ctx)
962 usbi_remove_pollfd(ctx, ctx->ctrl_pipe[0]);
963 close(ctx->ctrl_pipe[0]);
964 close(ctx->ctrl_pipe[1]);
967 static int calculate_timeout(struct usbi_transfer *transfer)
969 int r;
970 struct timespec current_time;
971 unsigned int timeout =
972 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout;
974 if (!timeout)
975 return 0;
977 r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, &current_time);
978 if (r < 0) {
979 usbi_err(ITRANSFER_CTX(transfer),
980 "failed to read monotonic clock, errno=%d", errno);
981 return r;
984 current_time.tv_sec += timeout / 1000;
985 current_time.tv_nsec += (timeout % 1000) * 1000000;
987 if (current_time.tv_nsec > 1000000000) {
988 current_time.tv_nsec -= 1000000000;
989 current_time.tv_sec++;
992 TIMESPEC_TO_TIMEVAL(&transfer->timeout, &current_time);
993 return 0;
996 static void add_to_flying_list(struct usbi_transfer *transfer)
998 struct usbi_transfer *cur;
999 struct timeval *timeout = &transfer->timeout;
1000 struct libusb_context *ctx = ITRANSFER_CTX(transfer);
1002 pthread_mutex_lock(&ctx->flying_transfers_lock);
1004 /* if we have no other flying transfers, start the list with this one */
1005 if (list_empty(&ctx->flying_transfers)) {
1006 list_add(&transfer->list, &ctx->flying_transfers);
1007 goto out;
1010 /* if we have infinite timeout, append to end of list */
1011 if (!timerisset(timeout)) {
1012 list_add_tail(&transfer->list, &ctx->flying_transfers);
1013 goto out;
1016 /* otherwise, find appropriate place in list */
1017 list_for_each_entry(cur, &ctx->flying_transfers, list) {
1018 /* find first timeout that occurs after the transfer in question */
1019 struct timeval *cur_tv = &cur->timeout;
1021 if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
1022 (cur_tv->tv_sec == timeout->tv_sec &&
1023 cur_tv->tv_usec > timeout->tv_usec)) {
1024 list_add_tail(&transfer->list, &cur->list);
1025 goto out;
1029 /* otherwise we need to be inserted at the end */
1030 list_add_tail(&transfer->list, &ctx->flying_transfers);
1031 out:
1032 pthread_mutex_unlock(&ctx->flying_transfers_lock);
1035 /** \ingroup asyncio
1036 * Allocate a libusb transfer with a specified number of isochronous packet
1037 * descriptors. The returned transfer is pre-initialized for you. When the new
1038 * transfer is no longer needed, it should be freed with
1039 * libusb_free_transfer().
1041 * Transfers intended for non-isochronous endpoints (e.g. control, bulk,
1042 * interrupt) should specify an iso_packets count of zero.
1044 * For transfers intended for isochronous endpoints, specify an appropriate
1045 * number of packet descriptors to be allocated as part of the transfer.
1046 * The returned transfer is not specially initialized for isochronous I/O;
1047 * you are still required to set the
1048 * \ref libusb_transfer::num_iso_packets "num_iso_packets" and
1049 * \ref libusb_transfer::type "type" fields accordingly.
1051 * It is safe to allocate a transfer with some isochronous packets and then
1052 * use it on a non-isochronous endpoint. If you do this, ensure that at time
1053 * of submission, num_iso_packets is 0 and that type is set appropriately.
1055 * \param iso_packets number of isochronous packet descriptors to allocate
1056 * \returns a newly allocated transfer, or NULL on error
1058 API_EXPORTED struct libusb_transfer *libusb_alloc_transfer(int iso_packets)
1060 size_t os_alloc_size = usbi_backend->transfer_priv_size
1061 + (usbi_backend->add_iso_packet_size * iso_packets);
1062 int alloc_size = sizeof(struct usbi_transfer)
1063 + sizeof(struct libusb_transfer)
1064 + (sizeof(struct libusb_iso_packet_descriptor) * iso_packets)
1065 + os_alloc_size;
1066 struct usbi_transfer *itransfer = malloc(alloc_size);
1067 if (!itransfer)
1068 return NULL;
1070 memset(itransfer, 0, alloc_size);
1071 itransfer->num_iso_packets = iso_packets;
1072 return __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1075 /** \ingroup asyncio
1076 * Free a transfer structure. This should be called for all transfers
1077 * allocated with libusb_alloc_transfer().
1079 * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
1080 * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is
1081 * non-NULL, this function will also free the transfer buffer using the
1082 * standard system memory allocator (e.g. free()).
1084 * It is legal to call this function with a NULL transfer. In this case,
1085 * the function will simply return safely.
1087 * \param transfer the transfer to free
1089 API_EXPORTED void libusb_free_transfer(struct libusb_transfer *transfer)
1091 struct usbi_transfer *itransfer;
1092 if (!transfer)
1093 return;
1095 if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)
1096 free(transfer->buffer);
1098 itransfer = __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1099 free(itransfer);
1102 /** \ingroup asyncio
1103 * Submit a transfer. This function will fire off the USB transfer and then
1104 * return immediately.
1106 * \param transfer the transfer to submit
1107 * \returns 0 on success
1108 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1109 * \returns LIBUSB_ERROR_BUSY if the transfer has already been submitted.
1110 * \returns another LIBUSB_ERROR code on other failure
1112 API_EXPORTED int libusb_submit_transfer(struct libusb_transfer *transfer)
1114 struct usbi_transfer *itransfer =
1115 __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1116 int r;
1118 itransfer->transferred = 0;
1119 itransfer->flags = 0;
1120 r = calculate_timeout(itransfer);
1121 if (r < 0)
1122 return LIBUSB_ERROR_OTHER;
1124 add_to_flying_list(itransfer);
1125 r = usbi_backend->submit_transfer(itransfer);
1126 if (r) {
1127 pthread_mutex_lock(&TRANSFER_CTX(transfer)->flying_transfers_lock);
1128 list_del(&itransfer->list);
1129 pthread_mutex_unlock(&TRANSFER_CTX(transfer)->flying_transfers_lock);
1132 return r;
1135 /** \ingroup asyncio
1136 * Asynchronously cancel a previously submitted transfer.
1137 * This function returns immediately, but this does not indicate cancellation
1138 * is complete. Your callback function will be invoked at some later time
1139 * with a transfer status of
1140 * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED
1141 * "LIBUSB_TRANSFER_CANCELLED."
1143 * \param transfer the transfer to cancel
1144 * \returns 0 on success
1145 * \returns LIBUSB_ERROR_NOT_FOUND if the transfer is already complete or
1146 * cancelled.
1147 * \returns a LIBUSB_ERROR code on failure
1149 API_EXPORTED int libusb_cancel_transfer(struct libusb_transfer *transfer)
1151 struct usbi_transfer *itransfer =
1152 __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
1153 int r;
1155 usbi_dbg("");
1156 r = usbi_backend->cancel_transfer(itransfer);
1157 if (r < 0)
1158 usbi_err(TRANSFER_CTX(transfer),
1159 "cancel transfer failed error %d", r);
1160 return r;
1163 /* Handle completion of a transfer (completion might be an error condition).
1164 * This will invoke the user-supplied callback function, which may end up
1165 * freeing the transfer. Therefore you cannot use the transfer structure
1166 * after calling this function, and you should free all backend-specific
1167 * data before calling it. */
1168 void usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
1169 enum libusb_transfer_status status)
1171 struct libusb_transfer *transfer =
1172 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1173 struct libusb_context *ctx = TRANSFER_CTX(transfer);
1174 uint8_t flags;
1176 pthread_mutex_lock(&ctx->flying_transfers_lock);
1177 list_del(&itransfer->list);
1178 pthread_mutex_unlock(&ctx->flying_transfers_lock);
1180 if (status == LIBUSB_TRANSFER_COMPLETED
1181 && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
1182 int rqlen = transfer->length;
1183 if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL)
1184 rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
1185 if (rqlen != itransfer->transferred) {
1186 usbi_dbg("interpreting short transfer as error");
1187 status = LIBUSB_TRANSFER_ERROR;
1191 flags = transfer->flags;
1192 transfer->status = status;
1193 transfer->actual_length = itransfer->transferred;
1194 if (transfer->callback)
1195 transfer->callback(transfer);
1196 /* transfer might have been freed by the above call, do not use from
1197 * this point. */
1198 if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
1199 libusb_free_transfer(transfer);
1200 pthread_mutex_lock(&ctx->event_waiters_lock);
1201 pthread_cond_broadcast(&ctx->event_waiters_cond);
1202 pthread_mutex_unlock(&ctx->event_waiters_lock);
1205 /* Similar to usbi_handle_transfer_completion() but exclusively for transfers
1206 * that were asynchronously cancelled. The same concerns w.r.t. freeing of
1207 * transfers exist here.
1209 void usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
1211 /* if the URB was cancelled due to timeout, report timeout to the user */
1212 if (transfer->flags & USBI_TRANSFER_TIMED_OUT) {
1213 usbi_dbg("detected timeout cancellation");
1214 usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT);
1215 return;
1218 /* otherwise its a normal async cancel */
1219 usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
1222 /** \ingroup poll
1223 * Attempt to acquire the event handling lock. This lock is used to ensure that
1224 * only one thread is monitoring libusb event sources at any one time.
1226 * You only need to use this lock if you are developing an application
1227 * which calls poll() or select() on libusb's file descriptors directly.
1228 * If you stick to libusb's event handling loop functions (e.g.
1229 * libusb_handle_events()) then you do not need to be concerned with this
1230 * locking.
1232 * While holding this lock, you are trusted to actually be handling events.
1233 * If you are no longer handling events, you must call libusb_unlock_events()
1234 * as soon as possible.
1236 * \param ctx the context to operate on, or NULL for the default context
1237 * \returns 0 if the lock was obtained successfully
1238 * \returns 1 if the lock was not obtained (i.e. another thread holds the lock)
1239 * \see \ref mtasync
1241 API_EXPORTED int libusb_try_lock_events(libusb_context *ctx)
1243 int r;
1244 USBI_GET_CONTEXT(ctx);
1246 /* is someone else waiting to modify poll fds? if so, don't let this thread
1247 * start event handling */
1248 pthread_mutex_lock(&ctx->pollfd_modify_lock);
1249 r = ctx->pollfd_modify;
1250 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
1251 if (r) {
1252 usbi_dbg("someone else is modifying poll fds");
1253 return 1;
1256 r = pthread_mutex_trylock(&ctx->events_lock);
1257 if (r)
1258 return 1;
1260 ctx->event_handler_active = 1;
1261 return 0;
1264 /** \ingroup poll
1265 * Acquire the event handling lock, blocking until successful acquisition if
1266 * it is contended. This lock is used to ensure that only one thread is
1267 * monitoring libusb event sources at any one time.
1269 * You only need to use this lock if you are developing an application
1270 * which calls poll() or select() on libusb's file descriptors directly.
1271 * If you stick to libusb's event handling loop functions (e.g.
1272 * libusb_handle_events()) then you do not need to be concerned with this
1273 * locking.
1275 * While holding this lock, you are trusted to actually be handling events.
1276 * If you are no longer handling events, you must call libusb_unlock_events()
1277 * as soon as possible.
1279 * \param ctx the context to operate on, or NULL for the default context
1280 * \see \ref mtasync
1282 API_EXPORTED void libusb_lock_events(libusb_context *ctx)
1284 USBI_GET_CONTEXT(ctx);
1285 pthread_mutex_lock(&ctx->events_lock);
1286 ctx->event_handler_active = 1;
1289 /** \ingroup poll
1290 * Release the lock previously acquired with libusb_try_lock_events() or
1291 * libusb_lock_events(). Releasing this lock will wake up any threads blocked
1292 * on libusb_wait_for_event().
1294 * \param ctx the context to operate on, or NULL for the default context
1295 * \see \ref mtasync
1297 API_EXPORTED void libusb_unlock_events(libusb_context *ctx)
1299 USBI_GET_CONTEXT(ctx);
1300 ctx->event_handler_active = 0;
1301 pthread_mutex_unlock(&ctx->events_lock);
1303 /* FIXME: perhaps we should be a bit more efficient by not broadcasting
1304 * the availability of the events lock when we are modifying pollfds
1305 * (check ctx->pollfd_modify)? */
1306 pthread_mutex_lock(&ctx->event_waiters_lock);
1307 pthread_cond_broadcast(&ctx->event_waiters_cond);
1308 pthread_mutex_unlock(&ctx->event_waiters_lock);
1311 /** \ingroup poll
1312 * Determine if it is still OK for this thread to be doing event handling.
1314 * Sometimes, libusb needs to temporarily pause all event handlers, and this
1315 * is the function you should use before polling file descriptors to see if
1316 * this is the case.
1318 * If this function instructs your thread to give up the events lock, you
1319 * should just continue the usual logic that is documented in \ref mtasync.
1320 * On the next iteration, your thread will fail to obtain the events lock,
1321 * and will hence become an event waiter.
1323 * This function should be called while the events lock is held: you don't
1324 * need to worry about the results of this function if your thread is not
1325 * the current event handler.
1327 * \param ctx the context to operate on, or NULL for the default context
1328 * \returns 1 if event handling can start or continue
1329 * \returns 0 if this thread must give up the events lock
1330 * \see \ref fullstory "Multi-threaded I/O: the full story"
1332 API_EXPORTED int libusb_event_handling_ok(libusb_context *ctx)
1334 int r;
1335 USBI_GET_CONTEXT(ctx);
1337 /* is someone else waiting to modify poll fds? if so, don't let this thread
1338 * continue event handling */
1339 pthread_mutex_lock(&ctx->pollfd_modify_lock);
1340 r = ctx->pollfd_modify;
1341 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
1342 if (r) {
1343 usbi_dbg("someone else is modifying poll fds");
1344 return 0;
1347 return 1;
1351 /** \ingroup poll
1352 * Determine if an active thread is handling events (i.e. if anyone is holding
1353 * the event handling lock).
1355 * \param ctx the context to operate on, or NULL for the default context
1356 * \returns 1 if a thread is handling events
1357 * \returns 0 if there are no threads currently handling events
1358 * \see \ref mtasync
1360 API_EXPORTED int libusb_event_handler_active(libusb_context *ctx)
1362 int r;
1363 USBI_GET_CONTEXT(ctx);
1365 /* is someone else waiting to modify poll fds? if so, don't let this thread
1366 * start event handling -- indicate that event handling is happening */
1367 pthread_mutex_lock(&ctx->pollfd_modify_lock);
1368 r = ctx->pollfd_modify;
1369 pthread_mutex_unlock(&ctx->pollfd_modify_lock);
1370 if (r) {
1371 usbi_dbg("someone else is modifying poll fds");
1372 return 1;
1375 return ctx->event_handler_active;
1378 /** \ingroup poll
1379 * Acquire the event waiters lock. This lock is designed to be obtained under
1380 * the situation where you want to be aware when events are completed, but
1381 * some other thread is event handling so calling libusb_handle_events() is not
1382 * allowed.
1384 * You then obtain this lock, re-check that another thread is still handling
1385 * events, then call libusb_wait_for_event().
1387 * You only need to use this lock if you are developing an application
1388 * which calls poll() or select() on libusb's file descriptors directly,
1389 * <b>and</b> may potentially be handling events from 2 threads simultaenously.
1390 * If you stick to libusb's event handling loop functions (e.g.
1391 * libusb_handle_events()) then you do not need to be concerned with this
1392 * locking.
1394 * \param ctx the context to operate on, or NULL for the default context
1395 * \see \ref mtasync
1397 API_EXPORTED void libusb_lock_event_waiters(libusb_context *ctx)
1399 USBI_GET_CONTEXT(ctx);
1400 pthread_mutex_lock(&ctx->event_waiters_lock);
1403 /** \ingroup poll
1404 * Release the event waiters lock.
1405 * \param ctx the context to operate on, or NULL for the default context
1406 * \see \ref mtasync
1408 API_EXPORTED void libusb_unlock_event_waiters(libusb_context *ctx)
1410 USBI_GET_CONTEXT(ctx);
1411 pthread_mutex_unlock(&ctx->event_waiters_lock);
1414 /** \ingroup poll
1415 * Wait for another thread to signal completion of an event. Must be called
1416 * with the event waiters lock held, see libusb_lock_event_waiters().
1418 * This function will block until any of the following conditions are met:
1419 * -# The timeout expires
1420 * -# A transfer completes
1421 * -# A thread releases the event handling lock through libusb_unlock_events()
1423 * Condition 1 is obvious. Condition 2 unblocks your thread <em>after</em>
1424 * the callback for the transfer has completed. Condition 3 is important
1425 * because it means that the thread that was previously handling events is no
1426 * longer doing so, so if any events are to complete, another thread needs to
1427 * step up and start event handling.
1429 * This function releases the event waiters lock before putting your thread
1430 * to sleep, and reacquires the lock as it is being woken up.
1432 * \param ctx the context to operate on, or NULL for the default context
1433 * \param tv maximum timeout for this blocking function. A NULL value
1434 * indicates unlimited timeout.
1435 * \returns 0 after a transfer completes or another thread stops event handling
1436 * \returns 1 if the timeout expired
1437 * \see \ref mtasync
1439 API_EXPORTED int libusb_wait_for_event(libusb_context *ctx, struct timeval *tv)
1441 struct timespec timeout;
1442 int r;
1444 USBI_GET_CONTEXT(ctx);
1445 if (tv == NULL) {
1446 pthread_cond_wait(&ctx->event_waiters_cond, &ctx->event_waiters_lock);
1447 return 0;
1450 r = usbi_backend->clock_gettime(USBI_CLOCK_REALTIME, &timeout);
1451 if (r < 0) {
1452 usbi_err(ctx, "failed to read realtime clock, error %d", errno);
1453 return LIBUSB_ERROR_OTHER;
1456 timeout.tv_sec += tv->tv_sec;
1457 timeout.tv_nsec += tv->tv_usec * 1000;
1458 if (timeout.tv_nsec > 1000000000) {
1459 timeout.tv_nsec -= 1000000000;
1460 timeout.tv_sec++;
1463 r = pthread_cond_timedwait(&ctx->event_waiters_cond,
1464 &ctx->event_waiters_lock, &timeout);
1465 return (r == ETIMEDOUT);
1468 static void handle_timeout(struct usbi_transfer *itransfer)
1470 struct libusb_transfer *transfer =
1471 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1472 int r;
1474 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1475 r = libusb_cancel_transfer(transfer);
1476 if (r < 0)
1477 usbi_warn(TRANSFER_CTX(transfer),
1478 "async cancel failed %d errno=%d", r, errno);
1481 static int handle_timeouts(struct libusb_context *ctx)
1483 struct timespec systime_ts;
1484 struct timeval systime;
1485 struct usbi_transfer *transfer;
1486 int r = 0;
1488 USBI_GET_CONTEXT(ctx);
1489 pthread_mutex_lock(&ctx->flying_transfers_lock);
1490 if (list_empty(&ctx->flying_transfers))
1491 goto out;
1493 /* get current time */
1494 r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, &systime_ts);
1495 if (r < 0)
1496 goto out;
1498 TIMESPEC_TO_TIMEVAL(&systime, &systime_ts);
1500 /* iterate through flying transfers list, finding all transfers that
1501 * have expired timeouts */
1502 list_for_each_entry(transfer, &ctx->flying_transfers, list) {
1503 struct timeval *cur_tv = &transfer->timeout;
1505 /* if we've reached transfers of infinite timeout, we're all done */
1506 if (!timerisset(cur_tv))
1507 goto out;
1509 /* ignore timeouts we've already handled */
1510 if (transfer->flags & USBI_TRANSFER_TIMED_OUT)
1511 continue;
1513 /* if transfer has non-expired timeout, nothing more to do */
1514 if ((cur_tv->tv_sec > systime.tv_sec) ||
1515 (cur_tv->tv_sec == systime.tv_sec &&
1516 cur_tv->tv_usec > systime.tv_usec))
1517 goto out;
1519 /* otherwise, we've got an expired timeout to handle */
1520 handle_timeout(transfer);
1523 out:
1524 pthread_mutex_unlock(&ctx->flying_transfers_lock);
1525 return r;
1528 /* do the actual event handling. assumes that no other thread is concurrently
1529 * doing the same thing. */
1530 static int handle_events(struct libusb_context *ctx, struct timeval *tv)
1532 int r;
1533 struct usbi_pollfd *ipollfd;
1534 nfds_t nfds = 0;
1535 struct pollfd *fds;
1536 int i = -1;
1537 int timeout_ms;
1539 pthread_mutex_lock(&ctx->pollfds_lock);
1540 list_for_each_entry(ipollfd, &ctx->pollfds, list)
1541 nfds++;
1543 /* TODO: malloc when number of fd's changes, not on every poll */
1544 fds = malloc(sizeof(*fds) * nfds);
1545 if (!fds)
1546 return LIBUSB_ERROR_NO_MEM;
1548 list_for_each_entry(ipollfd, &ctx->pollfds, list) {
1549 struct libusb_pollfd *pollfd = &ipollfd->pollfd;
1550 int fd = pollfd->fd;
1551 i++;
1552 fds[i].fd = fd;
1553 fds[i].events = pollfd->events;
1554 fds[i].revents = 0;
1556 pthread_mutex_unlock(&ctx->pollfds_lock);
1558 timeout_ms = (tv->tv_sec * 1000) + (tv->tv_usec / 1000);
1560 /* round up to next millisecond */
1561 if (tv->tv_usec % 1000)
1562 timeout_ms++;
1564 usbi_dbg("poll() %d fds with timeout in %dms", nfds, timeout_ms);
1565 r = poll(fds, nfds, timeout_ms);
1566 usbi_dbg("poll() returned %d", r);
1567 if (r == 0) {
1568 free(fds);
1569 return handle_timeouts(ctx);
1570 } else if (r == -1 && errno == EINTR) {
1571 free(fds);
1572 return LIBUSB_ERROR_INTERRUPTED;
1573 } else if (r < 0) {
1574 free(fds);
1575 usbi_err(ctx, "poll failed %d err=%d\n", r, errno);
1576 return LIBUSB_ERROR_IO;
1579 /* fd[0] is always the ctrl pipe */
1580 if (fds[0].revents) {
1581 /* another thread wanted to interrupt event handling, and it succeeded!
1582 * handle any other events that cropped up at the same time, and
1583 * simply return */
1584 usbi_dbg("caught a fish on the control pipe");
1586 if (r == 1) {
1587 r = 0;
1588 goto handled;
1589 } else {
1590 /* prevent OS backend from trying to handle events on ctrl pipe */
1591 fds[0].revents = 0;
1592 r--;
1596 r = usbi_backend->handle_events(ctx, fds, nfds, r);
1597 if (r)
1598 usbi_err(ctx, "backend handle_events failed with error %d", r);
1600 handled:
1601 free(fds);
1602 return r;
1605 /* returns the smallest of:
1606 * 1. timeout of next URB
1607 * 2. user-supplied timeout
1608 * returns 1 if there is an already-expired timeout, otherwise returns 0
1609 * and populates out
1611 static int get_next_timeout(libusb_context *ctx, struct timeval *tv,
1612 struct timeval *out)
1614 struct timeval timeout;
1615 int r = libusb_get_next_timeout(ctx, &timeout);
1616 if (r) {
1617 /* timeout already expired? */
1618 if (!timerisset(&timeout))
1619 return 1;
1621 /* choose the smallest of next URB timeout or user specified timeout */
1622 if (timercmp(&timeout, tv, <))
1623 *out = timeout;
1624 else
1625 *out = *tv;
1626 } else {
1627 *out = *tv;
1629 return 0;
1632 /** \ingroup poll
1633 * Handle any pending events.
1635 * libusb determines "pending events" by checking if any timeouts have expired
1636 * and by checking the set of file descriptors for activity.
1638 * If a zero timeval is passed, this function will handle any already-pending
1639 * events and then immediately return in non-blocking style.
1641 * If a non-zero timeval is passed and no events are currently pending, this
1642 * function will block waiting for events to handle up until the specified
1643 * timeout. If an event arrives or a signal is raised, this function will
1644 * return early.
1646 * \param ctx the context to operate on, or NULL for the default context
1647 * \param tv the maximum time to block waiting for events, or zero for
1648 * non-blocking mode
1649 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1651 API_EXPORTED int libusb_handle_events_timeout(libusb_context *ctx,
1652 struct timeval *tv)
1654 int r;
1655 struct timeval poll_timeout;
1657 USBI_GET_CONTEXT(ctx);
1658 r = get_next_timeout(ctx, tv, &poll_timeout);
1659 if (r) {
1660 /* timeout already expired */
1661 return handle_timeouts(ctx);
1664 retry:
1665 if (libusb_try_lock_events(ctx) == 0) {
1666 /* we obtained the event lock: do our own event handling */
1667 r = handle_events(ctx, &poll_timeout);
1668 libusb_unlock_events(ctx);
1669 return r;
1672 /* another thread is doing event handling. wait for pthread events that
1673 * notify event completion. */
1674 libusb_lock_event_waiters(ctx);
1676 if (!libusb_event_handler_active(ctx)) {
1677 /* we hit a race: whoever was event handling earlier finished in the
1678 * time it took us to reach this point. try the cycle again. */
1679 libusb_unlock_event_waiters(ctx);
1680 usbi_dbg("event handler was active but went away, retrying");
1681 goto retry;
1684 usbi_dbg("another thread is doing event handling");
1685 r = libusb_wait_for_event(ctx, &poll_timeout);
1686 libusb_unlock_event_waiters(ctx);
1688 if (r < 0)
1689 return r;
1690 else if (r == 1)
1691 return handle_timeouts(ctx);
1692 else
1693 return 0;
1696 /** \ingroup poll
1697 * Handle any pending events in blocking mode with a sensible timeout. This
1698 * timeout is currently hardcoded at 2 seconds but we may change this if we
1699 * decide other values are more sensible. For finer control over whether this
1700 * function is blocking or non-blocking, or the maximum timeout, use
1701 * libusb_handle_events_timeout() instead.
1703 * \param ctx the context to operate on, or NULL for the default context
1704 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1706 API_EXPORTED int libusb_handle_events(libusb_context *ctx)
1708 struct timeval tv;
1709 tv.tv_sec = 2;
1710 tv.tv_usec = 0;
1711 return libusb_handle_events_timeout(ctx, &tv);
1714 /** \ingroup poll
1715 * Handle any pending events by polling file descriptors, without checking if
1716 * any other threads are already doing so. Must be called with the event lock
1717 * held, see libusb_lock_events().
1719 * This function is designed to be called under the situation where you have
1720 * taken the event lock and are calling poll()/select() directly on libusb's
1721 * file descriptors (as opposed to using libusb_handle_events() or similar).
1722 * You detect events on libusb's descriptors, so you then call this function
1723 * with a zero timeout value (while still holding the event lock).
1725 * \param ctx the context to operate on, or NULL for the default context
1726 * \param tv the maximum time to block waiting for events, or zero for
1727 * non-blocking mode
1728 * \returns 0 on success, or a LIBUSB_ERROR code on failure
1729 * \see \ref mtasync
1731 API_EXPORTED int libusb_handle_events_locked(libusb_context *ctx,
1732 struct timeval *tv)
1734 int r;
1735 struct timeval poll_timeout;
1737 USBI_GET_CONTEXT(ctx);
1738 r = get_next_timeout(ctx, tv, &poll_timeout);
1739 if (r) {
1740 /* timeout already expired */
1741 return handle_timeouts(ctx);
1744 return handle_events(ctx, &poll_timeout);
1747 /** \ingroup poll
1748 * Determine the next internal timeout that libusb needs to handle. You only
1749 * need to use this function if you are calling poll() or select() or similar
1750 * on libusb's file descriptors yourself - you do not need to use it if you
1751 * are calling libusb_handle_events() or a variant directly.
1753 * You should call this function in your main loop in order to determine how
1754 * long to wait for select() or poll() to return results. libusb needs to be
1755 * called into at this timeout, so you should use it as an upper bound on
1756 * your select() or poll() call.
1758 * When the timeout has expired, call into libusb_handle_events_timeout()
1759 * (perhaps in non-blocking mode) so that libusb can handle the timeout.
1761 * This function may return 1 (success) and an all-zero timeval. If this is
1762 * the case, it indicates that libusb has a timeout that has already expired
1763 * so you should call libusb_handle_events_timeout() or similar immediately.
1764 * A return code of 0 indicates that there are no pending timeouts.
1766 * \param ctx the context to operate on, or NULL for the default context
1767 * \param tv output location for a relative time against the current
1768 * clock in which libusb must be called into in order to process timeout events
1769 * \returns 0 if there are no pending timeouts, 1 if a timeout was returned,
1770 * or LIBUSB_ERROR_OTHER on failure
1772 API_EXPORTED int libusb_get_next_timeout(libusb_context *ctx,
1773 struct timeval *tv)
1775 struct usbi_transfer *transfer;
1776 struct timespec cur_ts;
1777 struct timeval cur_tv;
1778 struct timeval *next_timeout;
1779 int r;
1780 int found = 0;
1782 USBI_GET_CONTEXT(ctx);
1783 pthread_mutex_lock(&ctx->flying_transfers_lock);
1784 if (list_empty(&ctx->flying_transfers)) {
1785 pthread_mutex_unlock(&ctx->flying_transfers_lock);
1786 usbi_dbg("no URBs, no timeout!");
1787 return 0;
1790 /* find next transfer which hasn't already been processed as timed out */
1791 list_for_each_entry(transfer, &ctx->flying_transfers, list) {
1792 if (!(transfer->flags & USBI_TRANSFER_TIMED_OUT)) {
1793 found = 1;
1794 break;
1797 pthread_mutex_unlock(&ctx->flying_transfers_lock);
1799 if (!found) {
1800 usbi_dbg("all URBs have already been processed for timeouts");
1801 return 0;
1804 next_timeout = &transfer->timeout;
1806 /* no timeout for next transfer */
1807 if (!timerisset(next_timeout)) {
1808 usbi_dbg("no URBs with timeouts, no timeout!");
1809 return 0;
1812 r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, &cur_ts);
1813 if (r < 0) {
1814 usbi_err(ctx, "failed to read monotonic clock, errno=%d", errno);
1815 return LIBUSB_ERROR_OTHER;
1817 TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts);
1819 if (timercmp(&cur_tv, next_timeout, >=)) {
1820 usbi_dbg("first timeout already expired");
1821 timerclear(tv);
1822 } else {
1823 timersub(next_timeout, &cur_tv, tv);
1824 usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec);
1827 return 1;
1830 /** \ingroup poll
1831 * Register notification functions for file descriptor additions/removals.
1832 * These functions will be invoked for every new or removed file descriptor
1833 * that libusb uses as an event source.
1835 * To remove notifiers, pass NULL values for the function pointers.
1837 * Note that file descriptors may have been added even before you register
1838 * these notifiers (e.g. at libusb_init() time).
1840 * Additionally, note that the removal notifier may be called during
1841 * libusb_exit() (e.g. when it is closing file descriptors that were opened
1842 * and added to the poll set at libusb_init() time). If you don't want this,
1843 * remove the notifiers immediately before calling libusb_exit().
1845 * \param ctx the context to operate on, or NULL for the default context
1846 * \param added_cb pointer to function for addition notifications
1847 * \param removed_cb pointer to function for removal notifications
1848 * \param user_data User data to be passed back to callbacks (useful for
1849 * passing context information)
1851 API_EXPORTED void libusb_set_pollfd_notifiers(libusb_context *ctx,
1852 libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
1853 void *user_data)
1855 USBI_GET_CONTEXT(ctx);
1856 ctx->fd_added_cb = added_cb;
1857 ctx->fd_removed_cb = removed_cb;
1858 ctx->fd_cb_user_data = user_data;
1861 /* Add a file descriptor to the list of file descriptors to be monitored.
1862 * events should be specified as a bitmask of events passed to poll(), e.g.
1863 * POLLIN and/or POLLOUT. */
1864 int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events)
1866 struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
1867 if (!ipollfd)
1868 return LIBUSB_ERROR_NO_MEM;
1870 usbi_dbg("add fd %d events %d", fd, events);
1871 ipollfd->pollfd.fd = fd;
1872 ipollfd->pollfd.events = events;
1873 pthread_mutex_lock(&ctx->pollfds_lock);
1874 list_add_tail(&ipollfd->list, &ctx->pollfds);
1875 pthread_mutex_unlock(&ctx->pollfds_lock);
1877 if (ctx->fd_added_cb)
1878 ctx->fd_added_cb(fd, events, ctx->fd_cb_user_data);
1879 return 0;
1882 /* Remove a file descriptor from the list of file descriptors to be polled. */
1883 void usbi_remove_pollfd(struct libusb_context *ctx, int fd)
1885 struct usbi_pollfd *ipollfd;
1886 int found = 0;
1888 usbi_dbg("remove fd %d", fd);
1889 pthread_mutex_lock(&ctx->pollfds_lock);
1890 list_for_each_entry(ipollfd, &ctx->pollfds, list)
1891 if (ipollfd->pollfd.fd == fd) {
1892 found = 1;
1893 break;
1896 if (!found) {
1897 usbi_dbg("couldn't find fd %d to remove", fd);
1898 pthread_mutex_unlock(&ctx->pollfds_lock);
1899 return;
1902 list_del(&ipollfd->list);
1903 pthread_mutex_unlock(&ctx->pollfds_lock);
1904 free(ipollfd);
1905 if (ctx->fd_removed_cb)
1906 ctx->fd_removed_cb(fd, ctx->fd_cb_user_data);
1909 /** \ingroup poll
1910 * Retrieve a list of file descriptors that should be polled by your main loop
1911 * as libusb event sources.
1913 * The returned list is NULL-terminated and should be freed with free() when
1914 * done. The actual list contents must not be touched.
1916 * \param ctx the context to operate on, or NULL for the default context
1917 * \returns a NULL-terminated list of libusb_pollfd structures, or NULL on
1918 * error
1920 API_EXPORTED const struct libusb_pollfd **libusb_get_pollfds(
1921 libusb_context *ctx)
1923 struct libusb_pollfd **ret = NULL;
1924 struct usbi_pollfd *ipollfd;
1925 size_t i = 0;
1926 size_t cnt = 0;
1927 USBI_GET_CONTEXT(ctx);
1929 pthread_mutex_lock(&ctx->pollfds_lock);
1930 list_for_each_entry(ipollfd, &ctx->pollfds, list)
1931 cnt++;
1933 ret = calloc(cnt + 1, sizeof(struct libusb_pollfd *));
1934 if (!ret)
1935 goto out;
1937 list_for_each_entry(ipollfd, &ctx->pollfds, list)
1938 ret[i++] = (struct libusb_pollfd *) ipollfd;
1939 ret[cnt] = NULL;
1941 out:
1942 pthread_mutex_unlock(&ctx->pollfds_lock);
1943 return (const struct libusb_pollfd **) ret;
1946 /* Backends call this from handle_events to report disconnection of a device.
1947 * The transfers get cancelled appropriately.
1949 void usbi_handle_disconnect(struct libusb_device_handle *handle)
1951 struct usbi_transfer *cur;
1952 struct usbi_transfer *to_cancel;
1954 usbi_dbg("device %d.%d",
1955 handle->dev->bus_number, handle->dev->device_address);
1957 /* terminate all pending transfers with the LIBUSB_TRANSFER_NO_DEVICE
1958 * status code.
1960 * this is a bit tricky because:
1961 * 1. we can't do transfer completion while holding flying_transfers_lock
1962 * 2. the transfers list can change underneath us - if we were to build a
1963 * list of transfers to complete (while holding look), the situation
1964 * might be different by the time we come to free them
1966 * so we resort to a loop-based approach as below
1967 * FIXME: is this still potentially racy?
1970 while (1) {
1971 pthread_mutex_lock(&HANDLE_CTX(handle)->flying_transfers_lock);
1972 to_cancel = NULL;
1973 list_for_each_entry(cur, &HANDLE_CTX(handle)->flying_transfers, list)
1974 if (__USBI_TRANSFER_TO_LIBUSB_TRANSFER(cur)->dev_handle == handle) {
1975 to_cancel = cur;
1976 break;
1978 pthread_mutex_unlock(&HANDLE_CTX(handle)->flying_transfers_lock);
1980 if (!to_cancel)
1981 break;
1983 usbi_backend->clear_transfer_priv(to_cancel);
1984 usbi_handle_transfer_completion(to_cancel, LIBUSB_TRANSFER_NO_DEVICE);