2 * Internal header for libusb
3 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
5 * Copyright © 2019 Nathan Hjelm <hjelmn@cs.umm.edu>
6 * Copyright © 2019-2020 Google LLC. All rights reserved.
7 * Copyright © 2020 Chris Dickens <christopher.a.dickens@gmail.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #ifdef HAVE_SYS_TIME_H
40 /* Not all C standard library headers define static_assert in assert.h
41 * Additionally, Visual Studio treats static_assert as a keyword.
43 #if !defined(__cplusplus) && !defined(static_assert) && !defined(_MSC_VER)
44 #define static_assert(cond, msg) _Static_assert(cond, msg)
48 #define ASSERT_EQ(expression, value) (void)expression
49 #define ASSERT_NE(expression, value) (void)expression
51 #define ASSERT_EQ(expression, value) assert(expression == value)
52 #define ASSERT_NE(expression, value) assert(expression != value)
55 #define container_of(ptr, type, member) \
56 ((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
59 #define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))
63 #define CLAMP(val, min, max) \
64 ((val) < (min) ? (min) : ((val) > (max) ? (max) : (val)))
68 #define MIN(a, b) ((a) < (b) ? (a) : (b))
72 #define MAX(a, b) ((a) > (b) ? (a) : (b))
75 /* The following is used to silence warnings for unused variables */
76 #if defined(UNREFERENCED_PARAMETER)
77 #define UNUSED(var) UNREFERENCED_PARAMETER(var)
79 #define UNUSED(var) do { (void)(var); } while(0)
82 /* Macro to align a value up to the next multiple of the size of a pointer */
83 #define PTR_ALIGN(v) \
84 (((v) + (sizeof(void *) - 1)) & ~(sizeof(void *) - 1))
88 * Useful for reference counting or when accessing a value without a lock
90 * The following atomic operations are defined:
91 * usbi_atomic_load() - Atomically read a variable's value
92 * usbi_atomic_store() - Atomically write a new value value to a variable
93 * usbi_atomic_inc() - Atomically increment a variable's value and return the new value
94 * usbi_atomic_dec() - Atomically decrement a variable's value and return the new value
96 * All of these operations are ordered with each other, thus the effects of
97 * any one operation is guaranteed to be seen by any other operation.
100 typedef volatile LONG usbi_atomic_t;
101 #define usbi_atomic_load(a) (*(a))
102 #define usbi_atomic_store(a, v) (*(a)) = (v)
103 #define usbi_atomic_inc(a) InterlockedIncrement((a))
104 #define usbi_atomic_dec(a) InterlockedDecrement((a))
106 #include <stdatomic.h>
107 typedef atomic_long usbi_atomic_t;
108 #define usbi_atomic_load(a) atomic_load((a))
109 #define usbi_atomic_store(a, v) atomic_store((a), (v))
110 #define usbi_atomic_inc(a) (atomic_fetch_add((a), 1) + 1)
111 #define usbi_atomic_dec(a) (atomic_fetch_add((a), -1) - 1)
114 /* Internal abstractions for event handling and thread synchronization */
115 #if defined(PLATFORM_POSIX)
116 #include "os/events_posix.h"
117 #include "os/threads_posix.h"
118 #elif defined(PLATFORM_WINDOWS)
119 #include "os/events_windows.h"
120 #include "os/threads_windows.h"
123 /* Inside the libusb code, mark all public functions as follows:
124 * return_type API_EXPORTED function_name(params) { ... }
125 * But if the function returns a pointer, mark it as follows:
126 * DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
127 * In the libusb public header, mark all declarations as:
128 * return_type LIBUSB_CALL function_name(params);
130 #define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
136 #define USB_MAXENDPOINTS 32
137 #define USB_MAXINTERFACES 32
138 #define USB_MAXCONFIG 8
140 /* Backend specific capabilities */
141 #define USBI_CAP_HAS_HID_ACCESS 0x00010000
142 #define USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER 0x00020000
144 /* Maximum number of bytes in a log line */
145 #define USBI_MAX_LOG_LEN 1024
146 /* Terminator for log lines */
147 #define USBI_LOG_LINE_END "\n"
150 struct list_head *prev, *next;
153 /* Get an entry from the list
154 * ptr - the address of this list_head element in "type"
155 * type - the data type that contains "member"
156 * member - the list_head element in "type"
158 #define list_entry(ptr, type, member) \
159 container_of(ptr, type, member)
161 #define list_first_entry(ptr, type, member) \
162 list_entry((ptr)->next, type, member)
164 #define list_next_entry(ptr, type, member) \
165 list_entry((ptr)->member.next, type, member)
167 /* Get each entry from a list
168 * pos - A structure pointer has a "member" element
170 * member - the list_head element in "pos"
171 * type - the type of the first parameter
173 #define list_for_each_entry(pos, head, member, type) \
174 for (pos = list_first_entry(head, type, member); \
175 &pos->member != (head); \
176 pos = list_next_entry(pos, type, member))
178 #define list_for_each_entry_safe(pos, n, head, member, type) \
179 for (pos = list_first_entry(head, type, member), \
180 n = list_next_entry(pos, type, member); \
181 &pos->member != (head); \
182 pos = n, n = list_next_entry(n, type, member))
184 /* Helper macros to iterate over a list. The structure pointed
185 * to by "pos" must have a list_head member named "list".
187 #define for_each_helper(pos, head, type) \
188 list_for_each_entry(pos, head, list, type)
190 #define for_each_safe_helper(pos, n, head, type) \
191 list_for_each_entry_safe(pos, n, head, list, type)
193 #define list_empty(entry) ((entry)->next == (entry))
195 static inline void list_init(struct list_head *entry)
197 entry->prev = entry->next = entry;
200 static inline void list_add(struct list_head *entry, struct list_head *head)
202 entry->next = head->next;
205 head->next->prev = entry;
209 static inline void list_add_tail(struct list_head *entry,
210 struct list_head *head)
213 entry->prev = head->prev;
215 head->prev->next = entry;
219 static inline void list_del(struct list_head *entry)
221 entry->next->prev = entry->prev;
222 entry->prev->next = entry->next;
223 entry->next = entry->prev = NULL;
226 static inline void list_cut(struct list_head *list, struct list_head *head)
228 if (list_empty(head)) {
233 list->next = head->next;
234 list->next->prev = list;
235 list->prev = head->prev;
236 list->prev->next = list;
241 static inline void list_splice_front(struct list_head *list, struct list_head *head)
243 list->next->prev = head;
244 list->prev->next = head->next;
245 head->next->prev = list->prev;
246 head->next = list->next;
249 static inline void *usbi_reallocf(void *ptr, size_t size)
251 void *ret = realloc(ptr, size);
258 #if !defined(USEC_PER_SEC)
259 #define USEC_PER_SEC 1000000L
262 #if !defined(NSEC_PER_SEC)
263 #define NSEC_PER_SEC 1000000000L
266 #define TIMEVAL_IS_VALID(tv) \
267 ((tv)->tv_sec >= 0 && \
268 (tv)->tv_usec >= 0 && (tv)->tv_usec < USEC_PER_SEC)
270 #define TIMESPEC_IS_SET(ts) ((ts)->tv_sec || (ts)->tv_nsec)
271 #define TIMESPEC_CLEAR(ts) (ts)->tv_sec = (ts)->tv_nsec = 0
272 #define TIMESPEC_CMP(a, b, CMP) \
273 (((a)->tv_sec == (b)->tv_sec) \
274 ? ((a)->tv_nsec CMP (b)->tv_nsec) \
275 : ((a)->tv_sec CMP (b)->tv_sec))
276 #define TIMESPEC_SUB(a, b, result) \
278 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
279 (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \
280 if ((result)->tv_nsec < 0L) { \
281 --(result)->tv_sec; \
282 (result)->tv_nsec += NSEC_PER_SEC; \
286 #if defined(PLATFORM_WINDOWS)
287 #define TIMEVAL_TV_SEC_TYPE long
289 #define TIMEVAL_TV_SEC_TYPE time_t
292 /* Some platforms don't have this define */
293 #ifndef TIMESPEC_TO_TIMEVAL
294 #define TIMESPEC_TO_TIMEVAL(tv, ts) \
296 (tv)->tv_sec = (TIMEVAL_TV_SEC_TYPE) (ts)->tv_sec; \
297 (tv)->tv_usec = (ts)->tv_nsec / 1000L; \
301 #ifdef ENABLE_LOGGING
303 #if defined(_MSC_VER) && (_MSC_VER < 1900)
305 #define snprintf usbi_snprintf
306 #define vsnprintf usbi_vsnprintf
307 int usbi_snprintf(char *dst, size_t size, const char *format, ...);
308 int usbi_vsnprintf(char *dst, size_t size, const char *format, va_list args);
309 #define LIBUSB_PRINTF_WIN32
310 #endif /* defined(_MSC_VER) && (_MSC_VER < 1900) */
312 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
313 const char *function, const char *format, ...) PRINTF_FORMAT(4, 5);
315 #define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __func__, __VA_ARGS__)
317 #define usbi_err(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
318 #define usbi_warn(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
319 #define usbi_info(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
320 #define usbi_dbg(ctx ,...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
322 #else /* ENABLE_LOGGING */
324 #define usbi_err(ctx, ...) UNUSED(ctx)
325 #define usbi_warn(ctx, ...) UNUSED(ctx)
326 #define usbi_info(ctx, ...) UNUSED(ctx)
327 #define usbi_dbg(ctx, ...) do {} while (0)
329 #endif /* ENABLE_LOGGING */
331 #define DEVICE_CTX(dev) ((dev)->ctx)
332 #define HANDLE_CTX(handle) ((handle) ? DEVICE_CTX((handle)->dev) : NULL)
333 #define ITRANSFER_CTX(itransfer) \
334 ((itransfer)->dev ? DEVICE_CTX((itransfer)->dev) : NULL)
335 #define TRANSFER_CTX(transfer) \
336 (ITRANSFER_CTX(LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)))
338 #define IS_EPIN(ep) (0 != ((ep) & LIBUSB_ENDPOINT_IN))
339 #define IS_EPOUT(ep) (!IS_EPIN(ep))
340 #define IS_XFERIN(xfer) (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
341 #define IS_XFEROUT(xfer) (!IS_XFERIN(xfer))
343 struct libusb_context {
344 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
345 enum libusb_log_level debug;
347 libusb_log_cb log_handler;
350 /* used for signalling occurrence of an internal event. */
354 /* used for timeout handling, if supported by OS.
355 * this timer is maintained to trigger on the next pending timeout */
359 struct list_head usb_devs;
360 usbi_mutex_t usb_devs_lock;
362 /* A list of open handles. Backends are free to traverse this if required.
364 struct list_head open_devs;
365 usbi_mutex_t open_devs_lock;
367 /* A list of registered hotplug callbacks */
368 struct list_head hotplug_cbs;
369 libusb_hotplug_callback_handle next_hotplug_cb_handle;
370 usbi_mutex_t hotplug_cbs_lock;
372 /* A flag to indicate that the context is ready for hotplug notifications */
373 usbi_atomic_t hotplug_ready;
375 /* this is a list of in-flight transfer handles, sorted by timeout
376 * expiration. URBs to timeout the soonest are placed at the beginning of
377 * the list, URBs that will time out later are placed after, and urbs with
378 * infinite timeout are always placed at the very end. */
379 struct list_head flying_transfers;
380 /* Note paths taking both this and usbi_transfer->lock must always
381 * take this lock first */
382 usbi_mutex_t flying_transfers_lock;
384 #if !defined(PLATFORM_WINDOWS)
385 /* user callbacks for pollfd changes */
386 libusb_pollfd_added_cb fd_added_cb;
387 libusb_pollfd_removed_cb fd_removed_cb;
388 void *fd_cb_user_data;
391 /* ensures that only one thread is handling events at any one time */
392 usbi_mutex_t events_lock;
394 /* used to see if there is an active thread doing event handling */
395 int event_handler_active;
397 /* A thread-local storage key to track which thread is performing event
399 usbi_tls_key_t event_handling_key;
401 /* used to wait for event completion in threads other than the one that is
403 usbi_mutex_t event_waiters_lock;
404 usbi_cond_t event_waiters_cond;
406 /* A lock to protect internal context event data. */
407 usbi_mutex_t event_data_lock;
409 /* A bitmask of flags that are set to indicate specific events that need to
410 * be handled. Protected by event_data_lock. */
411 unsigned int event_flags;
413 /* A counter that is set when we want to interrupt and prevent event handling,
414 * in order to safely close a device. Protected by event_data_lock. */
415 unsigned int device_close;
417 /* A list of currently active event sources. Protected by event_data_lock. */
418 struct list_head event_sources;
420 /* A list of event sources that have been removed since the last time
421 * event sources were waited on. Protected by event_data_lock. */
422 struct list_head removed_event_sources;
424 /* A pointer and count to platform-specific data used for monitoring event
425 * sources. Only accessed during event handling. */
427 unsigned int event_data_cnt;
429 /* A list of pending hotplug messages. Protected by event_data_lock. */
430 struct list_head hotplug_msgs;
432 /* A list of pending completed transfers. Protected by event_data_lock. */
433 struct list_head completed_transfers;
435 struct list_head list;
438 extern struct libusb_context *usbi_default_context;
440 extern struct list_head active_contexts_list;
441 extern usbi_mutex_static_t active_contexts_lock;
443 static inline struct libusb_context *usbi_get_context(struct libusb_context *ctx)
445 return ctx ? ctx : usbi_default_context;
448 enum usbi_event_flags {
449 /* The list of event sources has been modified */
450 USBI_EVENT_EVENT_SOURCES_MODIFIED = 1U << 0,
452 /* The user has interrupted the event handler */
453 USBI_EVENT_USER_INTERRUPT = 1U << 1,
455 /* A hotplug callback deregistration is pending */
456 USBI_EVENT_HOTPLUG_CB_DEREGISTERED = 1U << 2,
458 /* One or more hotplug messages are pending */
459 USBI_EVENT_HOTPLUG_MSG_PENDING = 1U << 3,
461 /* One or more completed transfers are pending */
462 USBI_EVENT_TRANSFER_COMPLETED = 1U << 4,
464 /* A device is in the process of being closed */
465 USBI_EVENT_DEVICE_CLOSE = 1U << 5,
468 /* Macros for managing event handling state */
469 static inline int usbi_handling_events(struct libusb_context *ctx)
471 return usbi_tls_key_get(ctx->event_handling_key) != NULL;
474 static inline void usbi_start_event_handling(struct libusb_context *ctx)
476 usbi_tls_key_set(ctx->event_handling_key, ctx);
479 static inline void usbi_end_event_handling(struct libusb_context *ctx)
481 usbi_tls_key_set(ctx->event_handling_key, NULL);
484 struct libusb_device {
485 usbi_atomic_t refcnt;
487 struct libusb_context *ctx;
488 struct libusb_device *parent_dev;
492 uint8_t device_address;
493 enum libusb_speed speed;
495 struct list_head list;
496 unsigned long session_data;
498 struct libusb_device_descriptor device_descriptor;
499 usbi_atomic_t attached;
502 struct libusb_device_handle {
503 /* lock protects claimed_interfaces */
505 unsigned long claimed_interfaces;
507 struct list_head list;
508 struct libusb_device *dev;
509 int auto_detach_kernel_driver;
512 /* Function called by backend during device initialization to convert
513 * multi-byte fields in the device descriptor to host-endian format.
515 static inline void usbi_localize_device_descriptor(struct libusb_device_descriptor *desc)
517 desc->bcdUSB = libusb_le16_to_cpu(desc->bcdUSB);
518 desc->idVendor = libusb_le16_to_cpu(desc->idVendor);
519 desc->idProduct = libusb_le16_to_cpu(desc->idProduct);
520 desc->bcdDevice = libusb_le16_to_cpu(desc->bcdDevice);
523 #ifdef HAVE_CLOCK_GETTIME
524 static inline void usbi_get_monotonic_time(struct timespec *tp)
526 ASSERT_EQ(clock_gettime(CLOCK_MONOTONIC, tp), 0);
528 static inline void usbi_get_real_time(struct timespec *tp)
530 ASSERT_EQ(clock_gettime(CLOCK_REALTIME, tp), 0);
533 /* If the platform doesn't provide the clock_gettime() function, the backend
534 * must provide its own clock implementations. Two clock functions are
537 * usbi_get_monotonic_time(): returns the time since an unspecified starting
538 * point (usually boot) that is monotonically
540 * usbi_get_real_time(): returns the time since system epoch.
542 void usbi_get_monotonic_time(struct timespec *tp);
543 void usbi_get_real_time(struct timespec *tp);
546 /* in-memory transfer layout:
549 * 2. struct usbi_transfer
550 * 3. struct libusb_transfer (which includes iso packets) [variable size]
552 * from a libusb_transfer, you can get the usbi_transfer by rewinding the
553 * appropriate number of bytes.
556 struct usbi_transfer {
558 struct list_head list;
559 struct list_head completed_list;
560 struct timespec timeout;
563 uint32_t state_flags; /* Protected by usbi_transfer->lock */
564 uint32_t timeout_flags; /* Protected by the flying_stransfers_lock */
566 /* The device reference is held until destruction for logging
567 * even after dev_handle is set to NULL. */
568 struct libusb_device *dev;
570 /* this lock is held during libusb_submit_transfer() and
571 * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
572 * cancellation, submission-during-cancellation, etc). the OS backend
573 * should also take this lock in the handle_events path, to prevent the user
574 * cancelling the transfer from another thread while you are processing
575 * its completion (presumably there would be races within your OS backend
576 * if this were possible).
577 * Note paths taking both this and the flying_transfers_lock must
578 * always take the flying_transfers_lock first */
584 enum usbi_transfer_state_flags {
585 /* Transfer successfully submitted by backend */
586 USBI_TRANSFER_IN_FLIGHT = 1U << 0,
588 /* Cancellation was requested via libusb_cancel_transfer() */
589 USBI_TRANSFER_CANCELLING = 1U << 1,
591 /* Operation on the transfer failed because the device disappeared */
592 USBI_TRANSFER_DEVICE_DISAPPEARED = 1U << 2,
595 enum usbi_transfer_timeout_flags {
596 /* Set by backend submit_transfer() if the OS handles timeout */
597 USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1U << 0,
599 /* The transfer timeout has been handled */
600 USBI_TRANSFER_TIMEOUT_HANDLED = 1U << 1,
602 /* The transfer timeout was successfully processed */
603 USBI_TRANSFER_TIMED_OUT = 1U << 2,
606 #define USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer) \
607 ((struct libusb_transfer *) \
608 ((unsigned char *)(itransfer) \
609 + PTR_ALIGN(sizeof(struct usbi_transfer))))
610 #define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \
611 ((struct usbi_transfer *) \
612 ((unsigned char *)(transfer) \
613 - PTR_ALIGN(sizeof(struct usbi_transfer))))
616 #pragma pack(push, 1)
619 /* All standard descriptors have these 2 fields in common */
620 struct usbi_descriptor_header {
622 uint8_t bDescriptorType;
625 struct usbi_device_descriptor {
627 uint8_t bDescriptorType;
629 uint8_t bDeviceClass;
630 uint8_t bDeviceSubClass;
631 uint8_t bDeviceProtocol;
632 uint8_t bMaxPacketSize0;
636 uint8_t iManufacturer;
638 uint8_t iSerialNumber;
639 uint8_t bNumConfigurations;
642 struct usbi_configuration_descriptor {
644 uint8_t bDescriptorType;
645 uint16_t wTotalLength;
646 uint8_t bNumInterfaces;
647 uint8_t bConfigurationValue;
648 uint8_t iConfiguration;
649 uint8_t bmAttributes;
653 struct usbi_interface_descriptor {
655 uint8_t bDescriptorType;
656 uint8_t bInterfaceNumber;
657 uint8_t bAlternateSetting;
658 uint8_t bNumEndpoints;
659 uint8_t bInterfaceClass;
660 uint8_t bInterfaceSubClass;
661 uint8_t bInterfaceProtocol;
665 struct usbi_string_descriptor {
667 uint8_t bDescriptorType;
668 uint16_t wData[ZERO_SIZED_ARRAY];
671 struct usbi_bos_descriptor {
673 uint8_t bDescriptorType;
674 uint16_t wTotalLength;
675 uint8_t bNumDeviceCaps;
682 union usbi_config_desc_buf {
683 struct usbi_configuration_descriptor desc;
684 uint8_t buf[LIBUSB_DT_CONFIG_SIZE];
685 uint16_t align; /* Force 2-byte alignment */
688 union usbi_string_desc_buf {
689 struct usbi_string_descriptor desc;
690 uint8_t buf[255]; /* Some devices choke on size > 255 */
691 uint16_t align; /* Force 2-byte alignment */
694 union usbi_bos_desc_buf {
695 struct usbi_bos_descriptor desc;
696 uint8_t buf[LIBUSB_DT_BOS_SIZE];
697 uint16_t align; /* Force 2-byte alignment */
700 enum usbi_hotplug_flags {
701 /* This callback is interested in device arrivals */
702 USBI_HOTPLUG_DEVICE_ARRIVED = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
704 /* This callback is interested in device removals */
705 USBI_HOTPLUG_DEVICE_LEFT = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT,
707 /* IMPORTANT: The values for the below entries must start *after*
708 * the highest value of the above entries!!!
711 /* The vendor_id field is valid for matching */
712 USBI_HOTPLUG_VENDOR_ID_VALID = (1U << 3),
714 /* The product_id field is valid for matching */
715 USBI_HOTPLUG_PRODUCT_ID_VALID = (1U << 4),
717 /* The dev_class field is valid for matching */
718 USBI_HOTPLUG_DEV_CLASS_VALID = (1U << 5),
720 /* This callback has been unregistered and needs to be freed */
721 USBI_HOTPLUG_NEEDS_FREE = (1U << 6),
724 struct usbi_hotplug_callback {
725 /* Flags that control how this callback behaves */
728 /* Vendor ID to match (if flags says this is valid) */
731 /* Product ID to match (if flags says this is valid) */
734 /* Device class to match (if flags says this is valid) */
737 /* Callback function to invoke for matching event/device */
738 libusb_hotplug_callback_fn cb;
740 /* Handle for this callback (used to match on deregister) */
741 libusb_hotplug_callback_handle handle;
743 /* User data that will be passed to the callback function */
746 /* List this callback is registered in (ctx->hotplug_cbs) */
747 struct list_head list;
750 struct usbi_hotplug_message {
751 /* The hotplug event that occurred */
752 libusb_hotplug_event event;
754 /* The device for which this hotplug event occurred */
755 struct libusb_device *device;
757 /* List this message is contained in (ctx->hotplug_msgs) */
758 struct list_head list;
761 /* shared data and functions */
763 void usbi_hotplug_init(struct libusb_context *ctx);
764 void usbi_hotplug_exit(struct libusb_context *ctx);
765 void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
766 libusb_hotplug_event event);
767 void usbi_hotplug_process(struct libusb_context *ctx, struct list_head *hotplug_msgs);
769 int usbi_io_init(struct libusb_context *ctx);
770 void usbi_io_exit(struct libusb_context *ctx);
772 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
773 unsigned long session_id);
774 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
775 unsigned long session_id);
776 int usbi_sanitize_device(struct libusb_device *dev);
777 void usbi_handle_disconnect(struct libusb_device_handle *dev_handle);
779 int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
780 enum libusb_transfer_status status);
781 int usbi_handle_transfer_cancellation(struct usbi_transfer *itransfer);
782 void usbi_signal_transfer_completion(struct usbi_transfer *itransfer);
784 void usbi_connect_device(struct libusb_device *dev);
785 void usbi_disconnect_device(struct libusb_device *dev);
787 struct usbi_event_source {
788 struct usbi_event_source_data {
789 usbi_os_handle_t os_handle;
792 struct list_head list;
795 int usbi_add_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle,
797 void usbi_remove_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle);
806 /* OS event abstraction */
808 int usbi_create_event(usbi_event_t *event);
809 void usbi_destroy_event(usbi_event_t *event);
810 void usbi_signal_event(usbi_event_t *event);
811 void usbi_clear_event(usbi_event_t *event);
814 int usbi_create_timer(usbi_timer_t *timer);
815 void usbi_destroy_timer(usbi_timer_t *timer);
816 int usbi_arm_timer(usbi_timer_t *timer, const struct timespec *timeout);
817 int usbi_disarm_timer(usbi_timer_t *timer);
820 static inline int usbi_using_timer(struct libusb_context *ctx)
823 return usbi_timer_valid(&ctx->timer);
830 struct usbi_reported_events {
833 unsigned int event_triggered:1;
835 unsigned int timer_triggered:1;
838 unsigned int event_bits;
841 unsigned int event_data_count;
842 unsigned int num_ready;
845 int usbi_alloc_event_data(struct libusb_context *ctx);
846 int usbi_wait_for_events(struct libusb_context *ctx,
847 struct usbi_reported_events *reported_events, int timeout_ms);
849 /* accessor functions for structure private data */
851 static inline void *usbi_get_context_priv(struct libusb_context *ctx)
853 return (unsigned char *)ctx + PTR_ALIGN(sizeof(*ctx));
856 static inline void *usbi_get_device_priv(struct libusb_device *dev)
858 return (unsigned char *)dev + PTR_ALIGN(sizeof(*dev));
861 static inline void *usbi_get_device_handle_priv(struct libusb_device_handle *dev_handle)
863 return (unsigned char *)dev_handle + PTR_ALIGN(sizeof(*dev_handle));
866 static inline void *usbi_get_transfer_priv(struct usbi_transfer *itransfer)
868 return itransfer->priv;
871 /* device discovery */
873 /* we traverse usbfs without knowing how many devices we are going to find.
874 * so we create this discovered_devs model which is similar to a linked-list
875 * which grows when required. it can be freed once discovery has completed,
876 * eliminating the need for a list node in the libusb_device structure
878 struct discovered_devs {
881 struct libusb_device *devices[ZERO_SIZED_ARRAY];
884 struct discovered_devs *discovered_devs_append(
885 struct discovered_devs *discdevs, struct libusb_device *dev);
889 /* This is the interface that OS backends need to implement.
890 * All fields are mandatory, except ones explicitly noted as optional. */
891 struct usbi_os_backend {
892 /* A human-readable name for your backend, e.g. "Linux usbfs" */
895 /* Binary mask for backend specific capabilities */
898 /* Perform initialization of your backend. You might use this function
899 * to determine specific capabilities of the system, allocate required
900 * data structures for later, etc.
902 * This function is called when a libusb user initializes the library
903 * prior to use. Mutual exclusion with other init and exit calls is
904 * guaranteed when this function is called.
906 * Return 0 on success, or a LIBUSB_ERROR code on failure.
908 int (*init)(struct libusb_context *ctx);
910 /* Deinitialization. Optional. This function should destroy anything
911 * that was set up by init.
913 * This function is called when the user deinitializes the library.
914 * Mutual exclusion with other init and exit calls is guaranteed when
915 * this function is called.
917 void (*exit)(struct libusb_context *ctx);
919 /* Set a backend-specific option. Optional.
921 * This function is called when the user calls libusb_set_option() and
922 * the option is not handled by the core library.
924 * Return 0 on success, or a LIBUSB_ERROR code on failure.
926 int (*set_option)(struct libusb_context *ctx, enum libusb_option option,
929 /* Enumerate all the USB devices on the system, returning them in a list
930 * of discovered devices.
932 * Your implementation should enumerate all devices on the system,
933 * regardless of whether they have been seen before or not.
935 * When you have found a device, compute a session ID for it. The session
936 * ID should uniquely represent that particular device for that particular
937 * connection session since boot (i.e. if you disconnect and reconnect a
938 * device immediately after, it should be assigned a different session ID).
939 * If your OS cannot provide a unique session ID as described above,
940 * presenting a session ID of (bus_number << 8 | device_address) should
941 * be sufficient. Bus numbers and device addresses wrap and get reused,
942 * but that is an unlikely case.
944 * After computing a session ID for a device, call
945 * usbi_get_device_by_session_id(). This function checks if libusb already
946 * knows about the device, and if so, it provides you with a reference
947 * to a libusb_device structure for it.
949 * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
950 * a new device structure for the device. Call usbi_alloc_device() to
951 * obtain a new libusb_device structure with reference count 1. Populate
952 * the bus_number and device_address attributes of the new device, and
953 * perform any other internal backend initialization you need to do. At
954 * this point, you should be ready to provide device descriptors and so
955 * on through the get_*_descriptor functions. Finally, call
956 * usbi_sanitize_device() to perform some final sanity checks on the
957 * device. Assuming all of the above succeeded, we can now continue.
958 * If any of the above failed, remember to unreference the device that
959 * was returned by usbi_alloc_device().
961 * At this stage we have a populated libusb_device structure (either one
962 * that was found earlier, or one that we have just allocated and
963 * populated). This can now be added to the discovered devices list
964 * using discovered_devs_append(). Note that discovered_devs_append()
965 * may reallocate the list, returning a new location for it, and also
966 * note that reallocation can fail. Your backend should handle these
967 * error conditions appropriately.
969 * This function should not generate any bus I/O and should not block.
970 * If I/O is required (e.g. reading the active configuration value), it is
971 * OK to ignore these suggestions :)
973 * This function is executed when the user wishes to retrieve a list
974 * of USB devices connected to the system.
976 * If the backend has hotplug support, this function is not used!
978 * Return 0 on success, or a LIBUSB_ERROR code on failure.
980 int (*get_device_list)(struct libusb_context *ctx,
981 struct discovered_devs **discdevs);
983 /* Apps which were written before hotplug support, may listen for
984 * hotplug events on their own and call libusb_get_device_list on
985 * device addition. In this case libusb_get_device_list will likely
986 * return a list without the new device in there, as the hotplug
987 * event thread will still be busy enumerating the device, which may
988 * take a while, or may not even have seen the event yet.
990 * To avoid this libusb_get_device_list will call this optional
991 * function for backends with hotplug support before copying
992 * ctx->usb_devs to the user. In this function the backend should
993 * ensure any pending hotplug events are fully processed before
996 * Optional, should be implemented by backends with hotplug support.
998 void (*hotplug_poll)(void);
1000 /* Wrap a platform-specific device handle for I/O and other USB
1001 * operations. The device handle is preallocated for you.
1003 * Your backend should allocate any internal resources required for I/O
1004 * and other operations so that those operations can happen (hopefully)
1005 * without hiccup. This is also a good place to inform libusb that it
1006 * should monitor certain file descriptors related to this device -
1007 * see the usbi_add_event_source() function.
1009 * Your backend should also initialize the device structure
1010 * (dev_handle->dev), which is NULL at the beginning of the call.
1012 * This function should not generate any bus I/O and should not block.
1014 * This function is called when the user attempts to wrap an existing
1015 * platform-specific device handle for a device.
1019 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1020 * - another LIBUSB_ERROR code on other failure
1022 * Do not worry about freeing the handle on failed open, the upper layers
1025 int (*wrap_sys_device)(struct libusb_context *ctx,
1026 struct libusb_device_handle *dev_handle, intptr_t sys_dev);
1028 /* Open a device for I/O and other USB operations. The device handle
1029 * is preallocated for you, you can retrieve the device in question
1030 * through handle->dev.
1032 * Your backend should allocate any internal resources required for I/O
1033 * and other operations so that those operations can happen (hopefully)
1034 * without hiccup. This is also a good place to inform libusb that it
1035 * should monitor certain file descriptors related to this device -
1036 * see the usbi_add_event_source() function.
1038 * This function should not generate any bus I/O and should not block.
1040 * This function is called when the user attempts to obtain a device
1041 * handle for a device.
1045 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1046 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
1048 * - another LIBUSB_ERROR code on other failure
1050 * Do not worry about freeing the handle on failed open, the upper layers
1053 int (*open)(struct libusb_device_handle *dev_handle);
1055 /* Close a device such that the handle cannot be used again. Your backend
1056 * should destroy any resources that were allocated in the open path.
1057 * This may also be a good place to call usbi_remove_event_source() to
1058 * inform libusb of any event sources associated with this device that
1059 * should no longer be monitored.
1061 * This function is called when the user closes a device handle.
1063 void (*close)(struct libusb_device_handle *dev_handle);
1065 /* Get the ACTIVE configuration descriptor for a device.
1067 * The descriptor should be retrieved from memory, NOT via bus I/O to the
1068 * device. This means that you may have to cache it in a private structure
1069 * during get_device_list enumeration. You may also have to keep track
1070 * of which configuration is active when the user changes it.
1072 * This function is expected to write len bytes of data into buffer, which
1073 * is guaranteed to be big enough. If you can only do a partial write,
1074 * return an error code.
1076 * This function is expected to return the descriptor in bus-endian format
1081 * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
1082 * - another LIBUSB_ERROR code on other failure
1084 int (*get_active_config_descriptor)(struct libusb_device *device,
1085 void *buffer, size_t len);
1087 /* Get a specific configuration descriptor for a device.
1089 * The descriptor should be retrieved from memory, NOT via bus I/O to the
1090 * device. This means that you may have to cache it in a private structure
1091 * during get_device_list enumeration.
1093 * The requested descriptor is expressed as a zero-based index (i.e. 0
1094 * indicates that we are requesting the first descriptor). The index does
1095 * not (necessarily) equal the bConfigurationValue of the configuration
1098 * This function is expected to write len bytes of data into buffer, which
1099 * is guaranteed to be big enough. If you can only do a partial write,
1100 * return an error code.
1102 * This function is expected to return the descriptor in bus-endian format
1105 * Return the length read on success or a LIBUSB_ERROR code on failure.
1107 int (*get_config_descriptor)(struct libusb_device *device,
1108 uint8_t config_index, void *buffer, size_t len);
1110 /* Like get_config_descriptor but then by bConfigurationValue instead
1113 * Optional, if not present the core will call get_config_descriptor
1114 * for all configs until it finds the desired bConfigurationValue.
1116 * Returns a pointer to the raw-descriptor in *buffer, this memory
1117 * is valid as long as device is valid.
1119 * Returns the length of the returned raw-descriptor on success,
1120 * or a LIBUSB_ERROR code on failure.
1122 int (*get_config_descriptor_by_value)(struct libusb_device *device,
1123 uint8_t bConfigurationValue, void **buffer);
1125 /* Get the bConfigurationValue for the active configuration for a device.
1126 * Optional. This should only be implemented if you can retrieve it from
1127 * cache (don't generate I/O).
1129 * If you cannot retrieve this from cache, either do not implement this
1130 * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
1131 * libusb to retrieve the information through a standard control transfer.
1133 * This function must be non-blocking.
1136 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1138 * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
1140 * - another LIBUSB_ERROR code on other failure.
1142 int (*get_configuration)(struct libusb_device_handle *dev_handle, uint8_t *config);
1144 /* Set the active configuration for a device.
1146 * A configuration value of -1 should put the device in unconfigured state.
1148 * This function can block.
1152 * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
1153 * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
1154 * configuration cannot be changed)
1155 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1157 * - another LIBUSB_ERROR code on other failure.
1159 int (*set_configuration)(struct libusb_device_handle *dev_handle, int config);
1161 /* Claim an interface. When claimed, the application can then perform
1162 * I/O to an interface's endpoints.
1164 * This function should not generate any bus I/O and should not block.
1165 * Interface claiming is a logical operation that simply ensures that
1166 * no other drivers/applications are using the interface, and after
1167 * claiming, no other drivers/applications can use the interface because
1172 * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
1173 * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
1174 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1176 * - another LIBUSB_ERROR code on other failure
1178 int (*claim_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
1180 /* Release a previously claimed interface.
1182 * This function should also generate a SET_INTERFACE control request,
1183 * resetting the alternate setting of that interface to 0. It's OK for
1184 * this function to block as a result.
1186 * You will only ever be asked to release an interface which was
1187 * successfully claimed earlier.
1191 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1193 * - another LIBUSB_ERROR code on other failure
1195 int (*release_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
1197 /* Set the alternate setting for an interface.
1199 * You will only ever be asked to set the alternate setting for an
1200 * interface which was successfully claimed earlier.
1202 * It's OK for this function to block.
1206 * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
1207 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1209 * - another LIBUSB_ERROR code on other failure
1211 int (*set_interface_altsetting)(struct libusb_device_handle *dev_handle,
1212 uint8_t interface_number, uint8_t altsetting);
1214 /* Clear a halt/stall condition on an endpoint.
1216 * It's OK for this function to block.
1220 * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1221 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1223 * - another LIBUSB_ERROR code on other failure
1225 int (*clear_halt)(struct libusb_device_handle *dev_handle,
1226 unsigned char endpoint);
1228 /* Perform a USB port reset to reinitialize a device. Optional.
1230 * If possible, the device handle should still be usable after the reset
1231 * completes, assuming that the device descriptors did not change during
1232 * reset and all previous interface state can be restored.
1234 * If something changes, or you cannot easily locate/verify the reset
1235 * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
1236 * to close the old handle and re-enumerate the device.
1240 * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
1241 * has been disconnected since it was opened
1242 * - another LIBUSB_ERROR code on other failure
1244 int (*reset_device)(struct libusb_device_handle *dev_handle);
1246 /* Alloc num_streams usb3 bulk streams on the passed in endpoints */
1247 int (*alloc_streams)(struct libusb_device_handle *dev_handle,
1248 uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
1250 /* Free usb3 bulk streams allocated with alloc_streams */
1251 int (*free_streams)(struct libusb_device_handle *dev_handle,
1252 unsigned char *endpoints, int num_endpoints);
1254 /* Allocate persistent DMA memory for the given device, suitable for
1255 * zerocopy. May return NULL on failure. Optional to implement.
1257 void *(*dev_mem_alloc)(struct libusb_device_handle *handle, size_t len);
1259 /* Free memory allocated by dev_mem_alloc. */
1260 int (*dev_mem_free)(struct libusb_device_handle *handle, void *buffer,
1263 /* Determine if a kernel driver is active on an interface. Optional.
1265 * The presence of a kernel driver on an interface indicates that any
1266 * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
1269 * - 0 if no driver is active
1270 * - 1 if a driver is active
1271 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1273 * - another LIBUSB_ERROR code on other failure
1275 int (*kernel_driver_active)(struct libusb_device_handle *dev_handle,
1276 uint8_t interface_number);
1278 /* Detach a kernel driver from an interface. Optional.
1280 * After detaching a kernel driver, the interface should be available
1285 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1286 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1287 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1289 * - another LIBUSB_ERROR code on other failure
1291 int (*detach_kernel_driver)(struct libusb_device_handle *dev_handle,
1292 uint8_t interface_number);
1294 /* Attach a kernel driver to an interface. Optional.
1296 * Reattach a kernel driver to the device.
1300 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1301 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1302 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1304 * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
1305 * preventing reattachment
1306 * - another LIBUSB_ERROR code on other failure
1308 int (*attach_kernel_driver)(struct libusb_device_handle *dev_handle,
1309 uint8_t interface_number);
1311 /* Destroy a device. Optional.
1313 * This function is called when the last reference to a device is
1314 * destroyed. It should free any resources allocated in the get_device_list
1317 void (*destroy_device)(struct libusb_device *dev);
1319 /* Submit a transfer. Your implementation should take the transfer,
1320 * morph it into whatever form your platform requires, and submit it
1323 * This function must not block.
1325 * This function gets called with the flying_transfers_lock locked!
1329 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1330 * - another LIBUSB_ERROR code on other failure
1332 int (*submit_transfer)(struct usbi_transfer *itransfer);
1334 /* Cancel a previously submitted transfer.
1336 * This function must not block. The transfer cancellation must complete
1337 * later, resulting in a call to usbi_handle_transfer_cancellation()
1338 * from the context of handle_events.
1340 int (*cancel_transfer)(struct usbi_transfer *itransfer);
1342 /* Clear a transfer as if it has completed or cancelled, but do not
1343 * report any completion/cancellation to the library. You should free
1344 * all private data from the transfer as if you were just about to report
1345 * completion or cancellation.
1347 * This function might seem a bit out of place. It is used when libusb
1348 * detects a disconnected device - it calls this function for all pending
1349 * transfers before reporting completion (with the disconnect code) to
1350 * the user. Maybe we can improve upon this internal interface in future.
1352 void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
1354 /* Handle any pending events on event sources. Optional.
1356 * Provide this function when event sources directly indicate device
1357 * or transfer activity. If your backend does not have such event sources,
1358 * implement the handle_transfer_completion function below.
1360 * This involves monitoring any active transfers and processing their
1361 * completion or cancellation.
1363 * The function is passed a pointer that represents platform-specific
1364 * data for monitoring event sources (size count). This data is to be
1365 * (re)allocated as necessary when event sources are modified.
1366 * The num_ready parameter indicates the number of event sources that
1367 * have reported events. This should be enough information for you to
1368 * determine which actions need to be taken on the currently active
1371 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1372 * For completed transfers, call usbi_handle_transfer_completion().
1373 * For control/bulk/interrupt transfers, populate the "transferred"
1374 * element of the appropriate usbi_transfer structure before calling the
1375 * above functions. For isochronous transfers, populate the status and
1376 * transferred fields of the iso packet descriptors of the transfer.
1378 * This function should also be able to detect disconnection of the
1379 * device, reporting that situation with usbi_handle_disconnect().
1381 * When processing an event related to a transfer, you probably want to
1382 * take usbi_transfer.lock to prevent races. See the documentation for
1383 * the usbi_transfer structure.
1385 * Return 0 on success, or a LIBUSB_ERROR code on failure.
1387 int (*handle_events)(struct libusb_context *ctx,
1388 void *event_data, unsigned int count, unsigned int num_ready);
1390 /* Handle transfer completion. Optional.
1392 * Provide this function when there are no event sources available that
1393 * directly indicate device or transfer activity. If your backend does
1394 * have such event sources, implement the handle_events function above.
1396 * Your backend must tell the library when a transfer has completed by
1397 * calling usbi_signal_transfer_completion(). You should store any private
1398 * information about the transfer and its completion status in the transfer's
1399 * private backend data.
1401 * During event handling, this function will be called on each transfer for
1402 * which usbi_signal_transfer_completion() was called.
1404 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1405 * For completed transfers, call usbi_handle_transfer_completion().
1406 * For control/bulk/interrupt transfers, populate the "transferred"
1407 * element of the appropriate usbi_transfer structure before calling the
1408 * above functions. For isochronous transfers, populate the status and
1409 * transferred fields of the iso packet descriptors of the transfer.
1411 * Return 0 on success, or a LIBUSB_ERROR code on failure.
1413 int (*handle_transfer_completion)(struct usbi_transfer *itransfer);
1415 /* Number of bytes to reserve for per-context private backend data.
1416 * This private data area is accessible by calling
1417 * usbi_get_context_priv() on the libusb_context instance.
1419 size_t context_priv_size;
1421 /* Number of bytes to reserve for per-device private backend data.
1422 * This private data area is accessible by calling
1423 * usbi_get_device_priv() on the libusb_device instance.
1425 size_t device_priv_size;
1427 /* Number of bytes to reserve for per-handle private backend data.
1428 * This private data area is accessible by calling
1429 * usbi_get_device_handle_priv() on the libusb_device_handle instance.
1431 size_t device_handle_priv_size;
1433 /* Number of bytes to reserve for per-transfer private backend data.
1434 * This private data area is accessible by calling
1435 * usbi_get_transfer_priv() on the usbi_transfer instance.
1437 size_t transfer_priv_size;
1440 extern const struct usbi_os_backend usbi_backend;
1442 #define for_each_context(c) \
1443 for_each_helper(c, &active_contexts_list, struct libusb_context)
1445 #define for_each_device(ctx, d) \
1446 for_each_helper(d, &(ctx)->usb_devs, struct libusb_device)
1448 #define for_each_device_safe(ctx, d, n) \
1449 for_each_safe_helper(d, n, &(ctx)->usb_devs, struct libusb_device)
1451 #define for_each_open_device(ctx, h) \
1452 for_each_helper(h, &(ctx)->open_devs, struct libusb_device_handle)
1454 #define __for_each_transfer(list, t) \
1455 for_each_helper(t, (list), struct usbi_transfer)
1457 #define for_each_transfer(ctx, t) \
1458 __for_each_transfer(&(ctx)->flying_transfers, t)
1460 #define __for_each_transfer_safe(list, t, n) \
1461 for_each_safe_helper(t, n, (list), struct usbi_transfer)
1463 #define for_each_transfer_safe(ctx, t, n) \
1464 __for_each_transfer_safe(&(ctx)->flying_transfers, t, n)
1466 #define __for_each_completed_transfer_safe(list, t, n) \
1467 list_for_each_entry_safe(t, n, (list), completed_list, struct usbi_transfer)
1469 #define for_each_event_source(ctx, e) \
1470 for_each_helper(e, &(ctx)->event_sources, struct usbi_event_source)
1472 #define for_each_removed_event_source(ctx, e) \
1473 for_each_helper(e, &(ctx)->removed_event_sources, struct usbi_event_source)
1475 #define for_each_removed_event_source_safe(ctx, e, n) \
1476 for_each_safe_helper(e, n, &(ctx)->removed_event_sources, struct usbi_event_source)
1478 #define for_each_hotplug_cb(ctx, c) \
1479 for_each_helper(c, &(ctx)->hotplug_cbs, struct usbi_hotplug_callback)
1481 #define for_each_hotplug_cb_safe(ctx, c, n) \
1482 for_each_safe_helper(c, n, &(ctx)->hotplug_cbs, struct usbi_hotplug_callback)