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))
86 /* Internal abstractions for event handling and thread synchronization */
87 #if defined(PLATFORM_POSIX)
88 #include "os/events_posix.h"
89 #include "os/threads_posix.h"
90 #elif defined(PLATFORM_WINDOWS)
91 #include "os/events_windows.h"
92 #include "os/threads_windows.h"
95 /* Inside the libusb code, mark all public functions as follows:
96 * return_type API_EXPORTED function_name(params) { ... }
97 * But if the function returns a pointer, mark it as follows:
98 * DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
99 * In the libusb public header, mark all declarations as:
100 * return_type LIBUSB_CALL function_name(params);
102 #define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
108 #define USB_MAXENDPOINTS 32
109 #define USB_MAXINTERFACES 32
110 #define USB_MAXCONFIG 8
112 /* Backend specific capabilities */
113 #define USBI_CAP_HAS_HID_ACCESS 0x00010000
114 #define USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER 0x00020000
116 /* Maximum number of bytes in a log line */
117 #define USBI_MAX_LOG_LEN 1024
118 /* Terminator for log lines */
119 #define USBI_LOG_LINE_END "\n"
122 struct list_head *prev, *next;
125 /* Get an entry from the list
126 * ptr - the address of this list_head element in "type"
127 * type - the data type that contains "member"
128 * member - the list_head element in "type"
130 #define list_entry(ptr, type, member) \
131 container_of(ptr, type, member)
133 #define list_first_entry(ptr, type, member) \
134 list_entry((ptr)->next, type, member)
136 #define list_next_entry(ptr, type, member) \
137 list_entry((ptr)->member.next, type, member)
139 /* Get each entry from a list
140 * pos - A structure pointer has a "member" element
142 * member - the list_head element in "pos"
143 * type - the type of the first parameter
145 #define list_for_each_entry(pos, head, member, type) \
146 for (pos = list_first_entry(head, type, member); \
147 &pos->member != (head); \
148 pos = list_next_entry(pos, type, member))
150 #define list_for_each_entry_safe(pos, n, head, member, type) \
151 for (pos = list_first_entry(head, type, member), \
152 n = list_next_entry(pos, type, member); \
153 &pos->member != (head); \
154 pos = n, n = list_next_entry(n, type, member))
156 /* Helper macros to iterate over a list. The structure pointed
157 * to by "pos" must have a list_head member named "list".
159 #define for_each_helper(pos, head, type) \
160 list_for_each_entry(pos, head, list, type)
162 #define for_each_safe_helper(pos, n, head, type) \
163 list_for_each_entry_safe(pos, n, head, list, type)
165 #define list_empty(entry) ((entry)->next == (entry))
167 static inline void list_init(struct list_head *entry)
169 entry->prev = entry->next = entry;
172 static inline void list_add(struct list_head *entry, struct list_head *head)
174 entry->next = head->next;
177 head->next->prev = entry;
181 static inline void list_add_tail(struct list_head *entry,
182 struct list_head *head)
185 entry->prev = head->prev;
187 head->prev->next = entry;
191 static inline void list_del(struct list_head *entry)
193 entry->next->prev = entry->prev;
194 entry->prev->next = entry->next;
195 entry->next = entry->prev = NULL;
198 static inline void list_cut(struct list_head *list, struct list_head *head)
200 if (list_empty(head)) {
205 list->next = head->next;
206 list->next->prev = list;
207 list->prev = head->prev;
208 list->prev->next = list;
213 static inline void list_splice_front(struct list_head *list, struct list_head *head)
215 list->next->prev = head;
216 list->prev->next = head->next;
217 head->next->prev = list->prev;
218 head->next = list->next;
221 static inline void *usbi_reallocf(void *ptr, size_t size)
223 void *ret = realloc(ptr, size);
230 #if !defined(USEC_PER_SEC)
231 #define USEC_PER_SEC 1000000L
234 #if !defined(NSEC_PER_SEC)
235 #define NSEC_PER_SEC 1000000000L
238 #define TIMEVAL_IS_VALID(tv) \
239 ((tv)->tv_sec >= 0 && \
240 (tv)->tv_usec >= 0 && (tv)->tv_usec < USEC_PER_SEC)
242 #define TIMESPEC_IS_SET(ts) ((ts)->tv_sec || (ts)->tv_nsec)
243 #define TIMESPEC_CLEAR(ts) (ts)->tv_sec = (ts)->tv_nsec = 0
244 #define TIMESPEC_CMP(a, b, CMP) \
245 (((a)->tv_sec == (b)->tv_sec) \
246 ? ((a)->tv_nsec CMP (b)->tv_nsec) \
247 : ((a)->tv_sec CMP (b)->tv_sec))
248 #define TIMESPEC_SUB(a, b, result) \
250 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
251 (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \
252 if ((result)->tv_nsec < 0L) { \
253 --(result)->tv_sec; \
254 (result)->tv_nsec += NSEC_PER_SEC; \
258 #if defined(PLATFORM_WINDOWS)
259 #define TIMEVAL_TV_SEC_TYPE long
261 #define TIMEVAL_TV_SEC_TYPE time_t
264 /* Some platforms don't have this define */
265 #ifndef TIMESPEC_TO_TIMEVAL
266 #define TIMESPEC_TO_TIMEVAL(tv, ts) \
268 (tv)->tv_sec = (TIMEVAL_TV_SEC_TYPE) (ts)->tv_sec; \
269 (tv)->tv_usec = (ts)->tv_nsec / 1000L; \
273 #ifdef ENABLE_LOGGING
275 #if defined(_MSC_VER) && (_MSC_VER < 1900)
277 #define snprintf usbi_snprintf
278 #define vsnprintf usbi_vsnprintf
279 int usbi_snprintf(char *dst, size_t size, const char *format, ...);
280 int usbi_vsnprintf(char *dst, size_t size, const char *format, va_list args);
281 #define LIBUSB_PRINTF_WIN32
282 #endif /* defined(_MSC_VER) && (_MSC_VER < 1900) */
284 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
285 const char *function, const char *format, ...) PRINTF_FORMAT(4, 5);
287 #define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __func__, __VA_ARGS__)
289 #define usbi_err(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
290 #define usbi_warn(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
291 #define usbi_info(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
292 #define usbi_dbg(...) _usbi_log(NULL, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
294 #else /* ENABLE_LOGGING */
296 #define usbi_err(ctx, ...) UNUSED(ctx)
297 #define usbi_warn(ctx, ...) UNUSED(ctx)
298 #define usbi_info(ctx, ...) UNUSED(ctx)
299 #define usbi_dbg(...) do {} while (0)
301 #endif /* ENABLE_LOGGING */
303 #define DEVICE_CTX(dev) ((dev)->ctx)
304 #define HANDLE_CTX(handle) (DEVICE_CTX((handle)->dev))
305 #define TRANSFER_CTX(transfer) (HANDLE_CTX((transfer)->dev_handle))
306 #define ITRANSFER_CTX(itransfer) \
307 (TRANSFER_CTX(USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)))
309 #define IS_EPIN(ep) (0 != ((ep) & LIBUSB_ENDPOINT_IN))
310 #define IS_EPOUT(ep) (!IS_EPIN(ep))
311 #define IS_XFERIN(xfer) (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
312 #define IS_XFEROUT(xfer) (!IS_XFERIN(xfer))
314 struct libusb_context {
315 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
316 enum libusb_log_level debug;
318 libusb_log_cb log_handler;
321 /* used for signalling occurrence of an internal event. */
325 /* used for timeout handling, if supported by OS.
326 * this timer is maintained to trigger on the next pending timeout */
330 struct list_head usb_devs;
331 usbi_mutex_t usb_devs_lock;
333 /* A list of open handles. Backends are free to traverse this if required.
335 struct list_head open_devs;
336 usbi_mutex_t open_devs_lock;
338 /* A list of registered hotplug callbacks */
339 struct list_head hotplug_cbs;
340 libusb_hotplug_callback_handle next_hotplug_cb_handle;
341 usbi_mutex_t hotplug_cbs_lock;
343 /* this is a list of in-flight transfer handles, sorted by timeout
344 * expiration. URBs to timeout the soonest are placed at the beginning of
345 * the list, URBs that will time out later are placed after, and urbs with
346 * infinite timeout are always placed at the very end. */
347 struct list_head flying_transfers;
348 /* Note paths taking both this and usbi_transfer->lock must always
349 * take this lock first */
350 usbi_mutex_t flying_transfers_lock;
352 #if !defined(PLATFORM_WINDOWS)
353 /* user callbacks for pollfd changes */
354 libusb_pollfd_added_cb fd_added_cb;
355 libusb_pollfd_removed_cb fd_removed_cb;
356 void *fd_cb_user_data;
359 /* ensures that only one thread is handling events at any one time */
360 usbi_mutex_t events_lock;
362 /* used to see if there is an active thread doing event handling */
363 int event_handler_active;
365 /* A thread-local storage key to track which thread is performing event
367 usbi_tls_key_t event_handling_key;
369 /* used to wait for event completion in threads other than the one that is
371 usbi_mutex_t event_waiters_lock;
372 usbi_cond_t event_waiters_cond;
374 /* A lock to protect internal context event data. */
375 usbi_mutex_t event_data_lock;
377 /* A bitmask of flags that are set to indicate specific events that need to
378 * be handled. Protected by event_data_lock. */
379 unsigned int event_flags;
381 /* A counter that is set when we want to interrupt and prevent event handling,
382 * in order to safely close a device. Protected by event_data_lock. */
383 unsigned int device_close;
385 /* A list of currently active event sources. Protected by event_data_lock. */
386 struct list_head event_sources;
388 /* A list of event sources that have been removed since the last time
389 * event sources were waited on. Protected by event_data_lock. */
390 struct list_head removed_event_sources;
392 /* A pointer and count to platform-specific data used for monitoring event
393 * sources. Only accessed during event handling. */
395 unsigned int event_data_cnt;
397 /* A list of pending hotplug messages. Protected by event_data_lock. */
398 struct list_head hotplug_msgs;
400 /* A list of pending completed transfers. Protected by event_data_lock. */
401 struct list_head completed_transfers;
403 struct list_head list;
406 extern struct libusb_context *usbi_default_context;
408 extern struct list_head active_contexts_list;
409 extern usbi_mutex_static_t active_contexts_lock;
411 static inline struct libusb_context *usbi_get_context(struct libusb_context *ctx)
413 return ctx ? ctx : usbi_default_context;
416 enum usbi_event_flags {
417 /* The list of event sources has been modified */
418 USBI_EVENT_EVENT_SOURCES_MODIFIED = 1U << 0,
420 /* The user has interrupted the event handler */
421 USBI_EVENT_USER_INTERRUPT = 1U << 1,
423 /* A hotplug callback deregistration is pending */
424 USBI_EVENT_HOTPLUG_CB_DEREGISTERED = 1U << 2,
426 /* One or more hotplug messages are pending */
427 USBI_EVENT_HOTPLUG_MSG_PENDING = 1U << 3,
429 /* One or more completed transfers are pending */
430 USBI_EVENT_TRANSFER_COMPLETED = 1U << 4,
432 /* A device is in the process of being closed */
433 USBI_EVENT_DEVICE_CLOSE = 1U << 5,
436 /* Macros for managing event handling state */
437 static inline int usbi_handling_events(struct libusb_context *ctx)
439 return usbi_tls_key_get(ctx->event_handling_key) != NULL;
442 static inline void usbi_start_event_handling(struct libusb_context *ctx)
444 usbi_tls_key_set(ctx->event_handling_key, ctx);
447 static inline void usbi_end_event_handling(struct libusb_context *ctx)
449 usbi_tls_key_set(ctx->event_handling_key, NULL);
452 struct libusb_device {
453 /* lock protects refcnt, everything else is finalized at initialization
458 struct libusb_context *ctx;
459 struct libusb_device *parent_dev;
463 uint8_t device_address;
464 enum libusb_speed speed;
466 struct list_head list;
467 unsigned long session_data;
469 struct libusb_device_descriptor device_descriptor;
473 struct libusb_device_handle {
474 /* lock protects claimed_interfaces */
476 unsigned long claimed_interfaces;
478 struct list_head list;
479 struct libusb_device *dev;
480 int auto_detach_kernel_driver;
483 /* Function called by backend during device initialization to convert
484 * multi-byte fields in the device descriptor to host-endian format.
486 static inline void usbi_localize_device_descriptor(struct libusb_device_descriptor *desc)
488 desc->bcdUSB = libusb_le16_to_cpu(desc->bcdUSB);
489 desc->idVendor = libusb_le16_to_cpu(desc->idVendor);
490 desc->idProduct = libusb_le16_to_cpu(desc->idProduct);
491 desc->bcdDevice = libusb_le16_to_cpu(desc->bcdDevice);
494 #ifdef HAVE_CLOCK_GETTIME
495 static inline void usbi_get_monotonic_time(struct timespec *tp)
497 ASSERT_EQ(clock_gettime(CLOCK_MONOTONIC, tp), 0);
499 static inline void usbi_get_real_time(struct timespec *tp)
501 ASSERT_EQ(clock_gettime(CLOCK_REALTIME, tp), 0);
504 /* If the platform doesn't provide the clock_gettime() function, the backend
505 * must provide its own clock implementations. Two clock functions are
508 * usbi_get_monotonic_time(): returns the time since an unspecified starting
509 * point (usually boot) that is monotonically
511 * usbi_get_real_time(): returns the time since system epoch.
513 void usbi_get_monotonic_time(struct timespec *tp);
514 void usbi_get_real_time(struct timespec *tp);
517 /* in-memory transfer layout:
520 * 2. struct usbi_transfer
521 * 3. struct libusb_transfer (which includes iso packets) [variable size]
523 * from a libusb_transfer, you can get the usbi_transfer by rewinding the
524 * appropriate number of bytes.
527 struct usbi_transfer {
529 struct list_head list;
530 struct list_head completed_list;
531 struct timespec timeout;
534 uint32_t state_flags; /* Protected by usbi_transfer->lock */
535 uint32_t timeout_flags; /* Protected by the flying_stransfers_lock */
537 /* this lock is held during libusb_submit_transfer() and
538 * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
539 * cancellation, submission-during-cancellation, etc). the OS backend
540 * should also take this lock in the handle_events path, to prevent the user
541 * cancelling the transfer from another thread while you are processing
542 * its completion (presumably there would be races within your OS backend
543 * if this were possible).
544 * Note paths taking both this and the flying_transfers_lock must
545 * always take the flying_transfers_lock first */
551 enum usbi_transfer_state_flags {
552 /* Transfer successfully submitted by backend */
553 USBI_TRANSFER_IN_FLIGHT = 1U << 0,
555 /* Cancellation was requested via libusb_cancel_transfer() */
556 USBI_TRANSFER_CANCELLING = 1U << 1,
558 /* Operation on the transfer failed because the device disappeared */
559 USBI_TRANSFER_DEVICE_DISAPPEARED = 1U << 2,
562 enum usbi_transfer_timeout_flags {
563 /* Set by backend submit_transfer() if the OS handles timeout */
564 USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1U << 0,
566 /* The transfer timeout has been handled */
567 USBI_TRANSFER_TIMEOUT_HANDLED = 1U << 1,
569 /* The transfer timeout was successfully processed */
570 USBI_TRANSFER_TIMED_OUT = 1U << 2,
573 #define USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer) \
574 ((struct libusb_transfer *) \
575 ((unsigned char *)(itransfer) \
576 + PTR_ALIGN(sizeof(struct usbi_transfer))))
577 #define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \
578 ((struct usbi_transfer *) \
579 ((unsigned char *)(transfer) \
580 - PTR_ALIGN(sizeof(struct usbi_transfer))))
583 #pragma pack(push, 1)
586 /* All standard descriptors have these 2 fields in common */
587 struct usbi_descriptor_header {
589 uint8_t bDescriptorType;
592 struct usbi_device_descriptor {
594 uint8_t bDescriptorType;
596 uint8_t bDeviceClass;
597 uint8_t bDeviceSubClass;
598 uint8_t bDeviceProtocol;
599 uint8_t bMaxPacketSize0;
603 uint8_t iManufacturer;
605 uint8_t iSerialNumber;
606 uint8_t bNumConfigurations;
609 struct usbi_configuration_descriptor {
611 uint8_t bDescriptorType;
612 uint16_t wTotalLength;
613 uint8_t bNumInterfaces;
614 uint8_t bConfigurationValue;
615 uint8_t iConfiguration;
616 uint8_t bmAttributes;
620 struct usbi_interface_descriptor {
622 uint8_t bDescriptorType;
623 uint8_t bInterfaceNumber;
624 uint8_t bAlternateSetting;
625 uint8_t bNumEndpoints;
626 uint8_t bInterfaceClass;
627 uint8_t bInterfaceSubClass;
628 uint8_t bInterfaceProtocol;
632 struct usbi_string_descriptor {
634 uint8_t bDescriptorType;
635 uint16_t wData[ZERO_SIZED_ARRAY];
638 struct usbi_bos_descriptor {
640 uint8_t bDescriptorType;
641 uint16_t wTotalLength;
642 uint8_t bNumDeviceCaps;
649 union usbi_config_desc_buf {
650 struct usbi_configuration_descriptor desc;
651 uint8_t buf[LIBUSB_DT_CONFIG_SIZE];
652 uint16_t align; /* Force 2-byte alignment */
655 union usbi_string_desc_buf {
656 struct usbi_string_descriptor desc;
657 uint8_t buf[255]; /* Some devices choke on size > 255 */
658 uint16_t align; /* Force 2-byte alignment */
661 union usbi_bos_desc_buf {
662 struct usbi_bos_descriptor desc;
663 uint8_t buf[LIBUSB_DT_BOS_SIZE];
664 uint16_t align; /* Force 2-byte alignment */
667 /* shared data and functions */
669 int usbi_io_init(struct libusb_context *ctx);
670 void usbi_io_exit(struct libusb_context *ctx);
672 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
673 unsigned long session_id);
674 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
675 unsigned long session_id);
676 int usbi_sanitize_device(struct libusb_device *dev);
677 void usbi_handle_disconnect(struct libusb_device_handle *dev_handle);
679 int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
680 enum libusb_transfer_status status);
681 int usbi_handle_transfer_cancellation(struct usbi_transfer *itransfer);
682 void usbi_signal_transfer_completion(struct usbi_transfer *itransfer);
684 void usbi_connect_device(struct libusb_device *dev);
685 void usbi_disconnect_device(struct libusb_device *dev);
687 struct usbi_event_source {
688 struct usbi_event_source_data {
689 usbi_os_handle_t os_handle;
692 struct list_head list;
695 int usbi_add_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle,
697 void usbi_remove_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle);
699 /* OS event abstraction */
701 int usbi_create_event(usbi_event_t *event);
702 void usbi_destroy_event(usbi_event_t *event);
703 void usbi_signal_event(usbi_event_t *event);
704 void usbi_clear_event(usbi_event_t *event);
707 int usbi_create_timer(usbi_timer_t *timer);
708 void usbi_destroy_timer(usbi_timer_t *timer);
709 int usbi_arm_timer(usbi_timer_t *timer, const struct timespec *timeout);
710 int usbi_disarm_timer(usbi_timer_t *timer);
713 static inline int usbi_using_timer(struct libusb_context *ctx)
716 return usbi_timer_valid(&ctx->timer);
723 struct usbi_reported_events {
726 unsigned int event_triggered:1;
728 unsigned int timer_triggered:1;
731 unsigned int event_bits;
734 unsigned int event_data_count;
735 unsigned int num_ready;
738 int usbi_alloc_event_data(struct libusb_context *ctx);
739 int usbi_wait_for_events(struct libusb_context *ctx,
740 struct usbi_reported_events *reported_events, int timeout_ms);
742 /* accessor functions for structure private data */
744 static inline void *usbi_get_context_priv(struct libusb_context *ctx)
746 return (unsigned char *)ctx + PTR_ALIGN(sizeof(*ctx));
749 static inline void *usbi_get_device_priv(struct libusb_device *dev)
751 return (unsigned char *)dev + PTR_ALIGN(sizeof(*dev));
754 static inline void *usbi_get_device_handle_priv(struct libusb_device_handle *dev_handle)
756 return (unsigned char *)dev_handle + PTR_ALIGN(sizeof(*dev_handle));
759 static inline void *usbi_get_transfer_priv(struct usbi_transfer *itransfer)
761 return itransfer->priv;
764 /* device discovery */
766 /* we traverse usbfs without knowing how many devices we are going to find.
767 * so we create this discovered_devs model which is similar to a linked-list
768 * which grows when required. it can be freed once discovery has completed,
769 * eliminating the need for a list node in the libusb_device structure
771 struct discovered_devs {
774 struct libusb_device *devices[ZERO_SIZED_ARRAY];
777 struct discovered_devs *discovered_devs_append(
778 struct discovered_devs *discdevs, struct libusb_device *dev);
782 /* This is the interface that OS backends need to implement.
783 * All fields are mandatory, except ones explicitly noted as optional. */
784 struct usbi_os_backend {
785 /* A human-readable name for your backend, e.g. "Linux usbfs" */
788 /* Binary mask for backend specific capabilities */
791 /* Perform initialization of your backend. You might use this function
792 * to determine specific capabilities of the system, allocate required
793 * data structures for later, etc.
795 * This function is called when a libusb user initializes the library
798 * Return 0 on success, or a LIBUSB_ERROR code on failure.
800 int (*init)(struct libusb_context *ctx);
802 /* Deinitialization. Optional. This function should destroy anything
803 * that was set up by init.
805 * This function is called when the user deinitializes the library.
807 void (*exit)(struct libusb_context *ctx);
809 /* Set a backend-specific option. Optional.
811 * This function is called when the user calls libusb_set_option() and
812 * the option is not handled by the core library.
814 * Return 0 on success, or a LIBUSB_ERROR code on failure.
816 int (*set_option)(struct libusb_context *ctx, enum libusb_option option,
819 /* Enumerate all the USB devices on the system, returning them in a list
820 * of discovered devices.
822 * Your implementation should enumerate all devices on the system,
823 * regardless of whether they have been seen before or not.
825 * When you have found a device, compute a session ID for it. The session
826 * ID should uniquely represent that particular device for that particular
827 * connection session since boot (i.e. if you disconnect and reconnect a
828 * device immediately after, it should be assigned a different session ID).
829 * If your OS cannot provide a unique session ID as described above,
830 * presenting a session ID of (bus_number << 8 | device_address) should
831 * be sufficient. Bus numbers and device addresses wrap and get reused,
832 * but that is an unlikely case.
834 * After computing a session ID for a device, call
835 * usbi_get_device_by_session_id(). This function checks if libusb already
836 * knows about the device, and if so, it provides you with a reference
837 * to a libusb_device structure for it.
839 * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
840 * a new device structure for the device. Call usbi_alloc_device() to
841 * obtain a new libusb_device structure with reference count 1. Populate
842 * the bus_number and device_address attributes of the new device, and
843 * perform any other internal backend initialization you need to do. At
844 * this point, you should be ready to provide device descriptors and so
845 * on through the get_*_descriptor functions. Finally, call
846 * usbi_sanitize_device() to perform some final sanity checks on the
847 * device. Assuming all of the above succeeded, we can now continue.
848 * If any of the above failed, remember to unreference the device that
849 * was returned by usbi_alloc_device().
851 * At this stage we have a populated libusb_device structure (either one
852 * that was found earlier, or one that we have just allocated and
853 * populated). This can now be added to the discovered devices list
854 * using discovered_devs_append(). Note that discovered_devs_append()
855 * may reallocate the list, returning a new location for it, and also
856 * note that reallocation can fail. Your backend should handle these
857 * error conditions appropriately.
859 * This function should not generate any bus I/O and should not block.
860 * If I/O is required (e.g. reading the active configuration value), it is
861 * OK to ignore these suggestions :)
863 * This function is executed when the user wishes to retrieve a list
864 * of USB devices connected to the system.
866 * If the backend has hotplug support, this function is not used!
868 * Return 0 on success, or a LIBUSB_ERROR code on failure.
870 int (*get_device_list)(struct libusb_context *ctx,
871 struct discovered_devs **discdevs);
873 /* Apps which were written before hotplug support, may listen for
874 * hotplug events on their own and call libusb_get_device_list on
875 * device addition. In this case libusb_get_device_list will likely
876 * return a list without the new device in there, as the hotplug
877 * event thread will still be busy enumerating the device, which may
878 * take a while, or may not even have seen the event yet.
880 * To avoid this libusb_get_device_list will call this optional
881 * function for backends with hotplug support before copying
882 * ctx->usb_devs to the user. In this function the backend should
883 * ensure any pending hotplug events are fully processed before
886 * Optional, should be implemented by backends with hotplug support.
888 void (*hotplug_poll)(void);
890 /* Wrap a platform-specific device handle for I/O and other USB
891 * operations. The device handle is preallocated for you.
893 * Your backend should allocate any internal resources required for I/O
894 * and other operations so that those operations can happen (hopefully)
895 * without hiccup. This is also a good place to inform libusb that it
896 * should monitor certain file descriptors related to this device -
897 * see the usbi_add_event_source() function.
899 * Your backend should also initialize the device structure
900 * (dev_handle->dev), which is NULL at the beginning of the call.
902 * This function should not generate any bus I/O and should not block.
904 * This function is called when the user attempts to wrap an existing
905 * platform-specific device handle for a device.
909 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
910 * - another LIBUSB_ERROR code on other failure
912 * Do not worry about freeing the handle on failed open, the upper layers
915 int (*wrap_sys_device)(struct libusb_context *ctx,
916 struct libusb_device_handle *dev_handle, intptr_t sys_dev);
918 /* Open a device for I/O and other USB operations. The device handle
919 * is preallocated for you, you can retrieve the device in question
920 * through handle->dev.
922 * Your backend should allocate any internal resources required for I/O
923 * and other operations so that those operations can happen (hopefully)
924 * without hiccup. This is also a good place to inform libusb that it
925 * should monitor certain file descriptors related to this device -
926 * see the usbi_add_event_source() function.
928 * This function should not generate any bus I/O and should not block.
930 * This function is called when the user attempts to obtain a device
931 * handle for a device.
935 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
936 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
938 * - another LIBUSB_ERROR code on other failure
940 * Do not worry about freeing the handle on failed open, the upper layers
943 int (*open)(struct libusb_device_handle *dev_handle);
945 /* Close a device such that the handle cannot be used again. Your backend
946 * should destroy any resources that were allocated in the open path.
947 * This may also be a good place to call usbi_remove_event_source() to
948 * inform libusb of any event sources associated with this device that
949 * should no longer be monitored.
951 * This function is called when the user closes a device handle.
953 void (*close)(struct libusb_device_handle *dev_handle);
955 /* Get the ACTIVE configuration descriptor for a device.
957 * The descriptor should be retrieved from memory, NOT via bus I/O to the
958 * device. This means that you may have to cache it in a private structure
959 * during get_device_list enumeration. You may also have to keep track
960 * of which configuration is active when the user changes it.
962 * This function is expected to write len bytes of data into buffer, which
963 * is guaranteed to be big enough. If you can only do a partial write,
964 * return an error code.
966 * This function is expected to return the descriptor in bus-endian format
971 * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
972 * - another LIBUSB_ERROR code on other failure
974 int (*get_active_config_descriptor)(struct libusb_device *device,
975 void *buffer, size_t len);
977 /* Get a specific configuration descriptor for a device.
979 * The descriptor should be retrieved from memory, NOT via bus I/O to the
980 * device. This means that you may have to cache it in a private structure
981 * during get_device_list enumeration.
983 * The requested descriptor is expressed as a zero-based index (i.e. 0
984 * indicates that we are requesting the first descriptor). The index does
985 * not (necessarily) equal the bConfigurationValue of the configuration
988 * This function is expected to write len bytes of data into buffer, which
989 * is guaranteed to be big enough. If you can only do a partial write,
990 * return an error code.
992 * This function is expected to return the descriptor in bus-endian format
995 * Return the length read on success or a LIBUSB_ERROR code on failure.
997 int (*get_config_descriptor)(struct libusb_device *device,
998 uint8_t config_index, void *buffer, size_t len);
1000 /* Like get_config_descriptor but then by bConfigurationValue instead
1003 * Optional, if not present the core will call get_config_descriptor
1004 * for all configs until it finds the desired bConfigurationValue.
1006 * Returns a pointer to the raw-descriptor in *buffer, this memory
1007 * is valid as long as device is valid.
1009 * Returns the length of the returned raw-descriptor on success,
1010 * or a LIBUSB_ERROR code on failure.
1012 int (*get_config_descriptor_by_value)(struct libusb_device *device,
1013 uint8_t bConfigurationValue, void **buffer);
1015 /* Get the bConfigurationValue for the active configuration for a device.
1016 * Optional. This should only be implemented if you can retrieve it from
1017 * cache (don't generate I/O).
1019 * If you cannot retrieve this from cache, either do not implement this
1020 * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
1021 * libusb to retrieve the information through a standard control transfer.
1023 * This function must be non-blocking.
1026 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1028 * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
1030 * - another LIBUSB_ERROR code on other failure.
1032 int (*get_configuration)(struct libusb_device_handle *dev_handle, uint8_t *config);
1034 /* Set the active configuration for a device.
1036 * A configuration value of -1 should put the device in unconfigured state.
1038 * This function can block.
1042 * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
1043 * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
1044 * configuration cannot be changed)
1045 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1047 * - another LIBUSB_ERROR code on other failure.
1049 int (*set_configuration)(struct libusb_device_handle *dev_handle, int config);
1051 /* Claim an interface. When claimed, the application can then perform
1052 * I/O to an interface's endpoints.
1054 * This function should not generate any bus I/O and should not block.
1055 * Interface claiming is a logical operation that simply ensures that
1056 * no other drivers/applications are using the interface, and after
1057 * claiming, no other drivers/applications can use the interface because
1062 * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
1063 * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
1064 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1066 * - another LIBUSB_ERROR code on other failure
1068 int (*claim_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
1070 /* Release a previously claimed interface.
1072 * This function should also generate a SET_INTERFACE control request,
1073 * resetting the alternate setting of that interface to 0. It's OK for
1074 * this function to block as a result.
1076 * You will only ever be asked to release an interface which was
1077 * successfully claimed earlier.
1081 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1083 * - another LIBUSB_ERROR code on other failure
1085 int (*release_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
1087 /* Set the alternate setting for an interface.
1089 * You will only ever be asked to set the alternate setting for an
1090 * interface which was successfully claimed earlier.
1092 * It's OK for this function to block.
1096 * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
1097 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1099 * - another LIBUSB_ERROR code on other failure
1101 int (*set_interface_altsetting)(struct libusb_device_handle *dev_handle,
1102 uint8_t interface_number, uint8_t altsetting);
1104 /* Clear a halt/stall condition on an endpoint.
1106 * It's OK for this function to block.
1110 * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1111 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1113 * - another LIBUSB_ERROR code on other failure
1115 int (*clear_halt)(struct libusb_device_handle *dev_handle,
1116 unsigned char endpoint);
1118 /* Perform a USB port reset to reinitialize a device. Optional.
1120 * If possible, the device handle should still be usable after the reset
1121 * completes, assuming that the device descriptors did not change during
1122 * reset and all previous interface state can be restored.
1124 * If something changes, or you cannot easily locate/verify the reset
1125 * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
1126 * to close the old handle and re-enumerate the device.
1130 * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
1131 * has been disconnected since it was opened
1132 * - another LIBUSB_ERROR code on other failure
1134 int (*reset_device)(struct libusb_device_handle *dev_handle);
1136 /* Alloc num_streams usb3 bulk streams on the passed in endpoints */
1137 int (*alloc_streams)(struct libusb_device_handle *dev_handle,
1138 uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
1140 /* Free usb3 bulk streams allocated with alloc_streams */
1141 int (*free_streams)(struct libusb_device_handle *dev_handle,
1142 unsigned char *endpoints, int num_endpoints);
1144 /* Allocate persistent DMA memory for the given device, suitable for
1145 * zerocopy. May return NULL on failure. Optional to implement.
1147 void *(*dev_mem_alloc)(struct libusb_device_handle *handle, size_t len);
1149 /* Free memory allocated by dev_mem_alloc. */
1150 int (*dev_mem_free)(struct libusb_device_handle *handle, void *buffer,
1153 /* Determine if a kernel driver is active on an interface. Optional.
1155 * The presence of a kernel driver on an interface indicates that any
1156 * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
1159 * - 0 if no driver is active
1160 * - 1 if a driver is active
1161 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1163 * - another LIBUSB_ERROR code on other failure
1165 int (*kernel_driver_active)(struct libusb_device_handle *dev_handle,
1166 uint8_t interface_number);
1168 /* Detach a kernel driver from an interface. Optional.
1170 * After detaching a kernel driver, the interface should be available
1175 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1176 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1177 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1179 * - another LIBUSB_ERROR code on other failure
1181 int (*detach_kernel_driver)(struct libusb_device_handle *dev_handle,
1182 uint8_t interface_number);
1184 /* Attach a kernel driver to an interface. Optional.
1186 * Reattach a kernel driver to the device.
1190 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1191 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1192 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1194 * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
1195 * preventing reattachment
1196 * - another LIBUSB_ERROR code on other failure
1198 int (*attach_kernel_driver)(struct libusb_device_handle *dev_handle,
1199 uint8_t interface_number);
1201 /* Destroy a device. Optional.
1203 * This function is called when the last reference to a device is
1204 * destroyed. It should free any resources allocated in the get_device_list
1207 void (*destroy_device)(struct libusb_device *dev);
1209 /* Submit a transfer. Your implementation should take the transfer,
1210 * morph it into whatever form your platform requires, and submit it
1213 * This function must not block.
1215 * This function gets called with the flying_transfers_lock locked!
1219 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1220 * - another LIBUSB_ERROR code on other failure
1222 int (*submit_transfer)(struct usbi_transfer *itransfer);
1224 /* Cancel a previously submitted transfer.
1226 * This function must not block. The transfer cancellation must complete
1227 * later, resulting in a call to usbi_handle_transfer_cancellation()
1228 * from the context of handle_events.
1230 int (*cancel_transfer)(struct usbi_transfer *itransfer);
1232 /* Clear a transfer as if it has completed or cancelled, but do not
1233 * report any completion/cancellation to the library. You should free
1234 * all private data from the transfer as if you were just about to report
1235 * completion or cancellation.
1237 * This function might seem a bit out of place. It is used when libusb
1238 * detects a disconnected device - it calls this function for all pending
1239 * transfers before reporting completion (with the disconnect code) to
1240 * the user. Maybe we can improve upon this internal interface in future.
1242 void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
1244 /* Handle any pending events on event sources. Optional.
1246 * Provide this function when event sources directly indicate device
1247 * or transfer activity. If your backend does not have such event sources,
1248 * implement the handle_transfer_completion function below.
1250 * This involves monitoring any active transfers and processing their
1251 * completion or cancellation.
1253 * The function is passed a pointer that represents platform-specific
1254 * data for monitoring event sources (size count). This data is to be
1255 * (re)allocated as necessary when event sources are modified.
1256 * The num_ready parameter indicates the number of event sources that
1257 * have reported events. This should be enough information for you to
1258 * determine which actions need to be taken on the currently active
1261 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1262 * For completed transfers, call usbi_handle_transfer_completion().
1263 * For control/bulk/interrupt transfers, populate the "transferred"
1264 * element of the appropriate usbi_transfer structure before calling the
1265 * above functions. For isochronous transfers, populate the status and
1266 * transferred fields of the iso packet descriptors of the transfer.
1268 * This function should also be able to detect disconnection of the
1269 * device, reporting that situation with usbi_handle_disconnect().
1271 * When processing an event related to a transfer, you probably want to
1272 * take usbi_transfer.lock to prevent races. See the documentation for
1273 * the usbi_transfer structure.
1275 * Return 0 on success, or a LIBUSB_ERROR code on failure.
1277 int (*handle_events)(struct libusb_context *ctx,
1278 void *event_data, unsigned int count, unsigned int num_ready);
1280 /* Handle transfer completion. Optional.
1282 * Provide this function when there are no event sources available that
1283 * directly indicate device or transfer activity. If your backend does
1284 * have such event sources, implement the handle_events function above.
1286 * Your backend must tell the library when a transfer has completed by
1287 * calling usbi_signal_transfer_completion(). You should store any private
1288 * information about the transfer and its completion status in the transfer's
1289 * private backend data.
1291 * During event handling, this function will be called on each transfer for
1292 * which usbi_signal_transfer_completion() was called.
1294 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1295 * For completed transfers, call usbi_handle_transfer_completion().
1296 * For control/bulk/interrupt transfers, populate the "transferred"
1297 * element of the appropriate usbi_transfer structure before calling the
1298 * above functions. For isochronous transfers, populate the status and
1299 * transferred fields of the iso packet descriptors of the transfer.
1301 * Return 0 on success, or a LIBUSB_ERROR code on failure.
1303 int (*handle_transfer_completion)(struct usbi_transfer *itransfer);
1305 /* Number of bytes to reserve for per-context private backend data.
1306 * This private data area is accessible by calling
1307 * usbi_get_context_priv() on the libusb_context instance.
1309 size_t context_priv_size;
1311 /* Number of bytes to reserve for per-device private backend data.
1312 * This private data area is accessible by calling
1313 * usbi_get_device_priv() on the libusb_device instance.
1315 size_t device_priv_size;
1317 /* Number of bytes to reserve for per-handle private backend data.
1318 * This private data area is accessible by calling
1319 * usbi_get_device_handle_priv() on the libusb_device_handle instance.
1321 size_t device_handle_priv_size;
1323 /* Number of bytes to reserve for per-transfer private backend data.
1324 * This private data area is accessible by calling
1325 * usbi_get_transfer_priv() on the usbi_transfer instance.
1327 size_t transfer_priv_size;
1330 extern const struct usbi_os_backend usbi_backend;
1332 #define for_each_context(c) \
1333 for_each_helper(c, &active_contexts_list, struct libusb_context)
1335 #define for_each_device(ctx, d) \
1336 for_each_helper(d, &(ctx)->usb_devs, struct libusb_device)
1338 #define for_each_device_safe(ctx, d, n) \
1339 for_each_safe_helper(d, n, &(ctx)->usb_devs, struct libusb_device)
1341 #define for_each_open_device(ctx, h) \
1342 for_each_helper(h, &(ctx)->open_devs, struct libusb_device_handle)
1344 #define __for_each_transfer(list, t) \
1345 for_each_helper(t, (list), struct usbi_transfer)
1347 #define for_each_transfer(ctx, t) \
1348 __for_each_transfer(&(ctx)->flying_transfers, t)
1350 #define __for_each_transfer_safe(list, t, n) \
1351 for_each_safe_helper(t, n, (list), struct usbi_transfer)
1353 #define for_each_transfer_safe(ctx, t, n) \
1354 __for_each_transfer_safe(&(ctx)->flying_transfers, t, n)
1356 #define __for_each_completed_transfer_safe(list, t, n) \
1357 list_for_each_entry_safe(t, n, (list), completed_list, struct usbi_transfer)
1359 #define for_each_event_source(ctx, e) \
1360 for_each_helper(e, &(ctx)->event_sources, struct usbi_event_source)
1362 #define for_each_removed_event_source(ctx, e) \
1363 for_each_helper(e, &(ctx)->removed_event_sources, struct usbi_event_source)
1365 #define for_each_removed_event_source_safe(ctx, e, n) \
1366 for_each_safe_helper(e, n, &(ctx)->removed_event_sources, struct usbi_event_source)