2 * Internal header for libusb
3 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
42 /* Inside the libusb code, mark all public functions as follows:
43 * return_type API_EXPORTED function_name(params) { ... }
44 * But if the function returns a pointer, mark it as follows:
45 * DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
46 * In the libusb public header, mark all declarations as:
47 * return_type LIBUSB_CALL function_name(params);
49 #define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
55 #define DEVICE_DESC_LENGTH 18
57 #define USB_MAXENDPOINTS 32
58 #define USB_MAXINTERFACES 32
59 #define USB_MAXCONFIG 8
61 /* Backend specific capabilities */
62 #define USBI_CAP_HAS_HID_ACCESS 0x00010000
63 #define USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER 0x00020000
65 /* Maximum number of bytes in a log line */
66 #define USBI_MAX_LOG_LEN 1024
67 /* Terminator for log lines */
68 #define USBI_LOG_LINE_END "\n"
70 /* The following is used to silence warnings for unused variables */
71 #define UNUSED(var) do { (void)(var); } while(0)
73 #if !defined(ARRAYSIZE)
74 #define ARRAYSIZE(array) (sizeof(array)/sizeof(array[0]))
78 struct list_head *prev, *next;
81 /* Get an entry from the list
82 * ptr - the address of this list_head element in "type"
83 * type - the data type that contains "member"
84 * member - the list_head element in "type"
86 #define list_entry(ptr, type, member) \
87 ((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
89 #define list_first_entry(ptr, type, member) \
90 list_entry((ptr)->next, type, member)
92 /* Get each entry from a list
93 * pos - A structure pointer has a "member" element
95 * member - the list_head element in "pos"
96 * type - the type of the first parameter
98 #define list_for_each_entry(pos, head, member, type) \
99 for (pos = list_entry((head)->next, type, member); \
100 &pos->member != (head); \
101 pos = list_entry(pos->member.next, type, member))
103 #define list_for_each_entry_safe(pos, n, head, member, type) \
104 for (pos = list_entry((head)->next, type, member), \
105 n = list_entry(pos->member.next, type, member); \
106 &pos->member != (head); \
107 pos = n, n = list_entry(n->member.next, type, member))
109 #define list_empty(entry) ((entry)->next == (entry))
111 static inline void list_init(struct list_head *entry)
113 entry->prev = entry->next = entry;
116 static inline void list_add(struct list_head *entry, struct list_head *head)
118 entry->next = head->next;
121 head->next->prev = entry;
125 static inline void list_add_tail(struct list_head *entry,
126 struct list_head *head)
129 entry->prev = head->prev;
131 head->prev->next = entry;
135 static inline void list_del(struct list_head *entry)
137 entry->next->prev = entry->prev;
138 entry->prev->next = entry->next;
139 entry->next = entry->prev = NULL;
142 static inline void *usbi_reallocf(void *ptr, size_t size)
144 void *ret = realloc(ptr, size);
150 #define container_of(ptr, type, member) ({ \
151 const typeof( ((type *)0)->member ) *mptr = (ptr); \
152 (type *)( (char *)mptr - offsetof(type,member) );})
155 #define MIN(a, b) ((a) < (b) ? (a) : (b))
158 #define MAX(a, b) ((a) > (b) ? (a) : (b))
161 #define TIMESPEC_IS_SET(ts) ((ts)->tv_sec != 0 || (ts)->tv_nsec != 0)
163 /* Some platforms don't have this define */
164 #ifndef TIMESPEC_TO_TIMEVAL
165 #define TIMESPEC_TO_TIMEVAL(tv, ts) \
167 (tv)->tv_sec = (ts)->tv_sec; \
168 (tv)->tv_usec = (ts)->tv_nsec / 1000; \
172 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
173 const char *function, const char *format, ...);
175 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
176 const char *function, const char *format, va_list args);
178 #if !defined(_MSC_VER) || _MSC_VER >= 1400
180 #ifdef ENABLE_LOGGING
181 #define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __FUNCTION__, __VA_ARGS__)
182 #define usbi_dbg(...) _usbi_log(NULL, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
184 #define _usbi_log(ctx, level, ...) do { (void)(ctx); } while(0)
185 #define usbi_dbg(...) do {} while(0)
188 #define usbi_info(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
189 #define usbi_warn(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
190 #define usbi_err(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
192 #else /* !defined(_MSC_VER) || _MSC_VER >= 1400 */
194 #ifdef ENABLE_LOGGING
195 #define LOG_BODY(ctxt, level) \
198 va_start (args, format); \
199 usbi_log_v(ctxt, level, "", format, args); \
203 #define LOG_BODY(ctxt, level) do { (void)(ctxt); } while(0)
206 static inline void usbi_info(struct libusb_context *ctx, const char *format,
208 LOG_BODY(ctx,LIBUSB_LOG_LEVEL_INFO)
209 static inline void usbi_warn(struct libusb_context *ctx, const char *format,
211 LOG_BODY(ctx,LIBUSB_LOG_LEVEL_WARNING)
212 static inline void usbi_err( struct libusb_context *ctx, const char *format,
214 LOG_BODY(ctx,LIBUSB_LOG_LEVEL_ERROR)
216 static inline void usbi_dbg(const char *format, ...)
217 LOG_BODY(NULL,LIBUSB_LOG_LEVEL_DEBUG)
219 #endif /* !defined(_MSC_VER) || _MSC_VER >= 1400 */
221 #define USBI_GET_CONTEXT(ctx) if (!(ctx)) (ctx) = usbi_default_context
222 #define DEVICE_CTX(dev) ((dev)->ctx)
223 #define HANDLE_CTX(handle) (DEVICE_CTX((handle)->dev))
224 #define TRANSFER_CTX(transfer) (HANDLE_CTX((transfer)->dev_handle))
225 #define ITRANSFER_CTX(transfer) \
226 (TRANSFER_CTX(USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)))
228 #define IS_EPIN(ep) (0 != ((ep) & LIBUSB_ENDPOINT_IN))
229 #define IS_EPOUT(ep) (!IS_EPIN(ep))
230 #define IS_XFERIN(xfer) (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
231 #define IS_XFEROUT(xfer) (!IS_XFERIN(xfer))
233 /* Internal abstraction for thread synchronization */
234 #if defined(THREADS_POSIX)
235 #include "os/threads_posix.h"
236 #elif defined(OS_WINDOWS) || defined(OS_WINCE)
237 #include <os/threads_windows.h>
240 extern struct libusb_context *usbi_default_context;
242 /* Forward declaration for use in context (fully defined inside poll abstraction) */
245 struct libusb_context {
249 /* internal event pipe, used for signalling occurrence of an internal event. */
252 struct list_head usb_devs;
253 usbi_mutex_t usb_devs_lock;
255 /* A list of open handles. Backends are free to traverse this if required.
257 struct list_head open_devs;
258 usbi_mutex_t open_devs_lock;
260 /* A list of registered hotplug callbacks */
261 struct list_head hotplug_cbs;
262 usbi_mutex_t hotplug_cbs_lock;
264 /* this is a list of in-flight transfer handles, sorted by timeout
265 * expiration. URBs to timeout the soonest are placed at the beginning of
266 * the list, URBs that will time out later are placed after, and urbs with
267 * infinite timeout are always placed at the very end. */
268 struct list_head flying_transfers;
269 usbi_mutex_t flying_transfers_lock;
271 /* user callbacks for pollfd changes */
272 libusb_pollfd_added_cb fd_added_cb;
273 libusb_pollfd_removed_cb fd_removed_cb;
274 void *fd_cb_user_data;
276 /* ensures that only one thread is handling events at any one time */
277 usbi_mutex_t events_lock;
279 /* used to see if there is an active thread doing event handling */
280 int event_handler_active;
282 /* A thread-local storage key to track which thread is performing event
284 usbi_tls_key_t event_handling_key;
286 /* used to wait for event completion in threads other than the one that is
288 usbi_mutex_t event_waiters_lock;
289 usbi_cond_t event_waiters_cond;
291 /* A lock to protect internal context event data. */
292 usbi_mutex_t event_data_lock;
294 /* A bitmask of flags that are set to indicate specific events that need to
295 * be handled. Protected by event_data_lock. */
296 unsigned int event_flags;
298 /* A counter that is set when we want to interrupt and prevent event handling,
299 * in order to safely close a device. Protected by event_data_lock. */
300 unsigned int device_close;
302 /* list and count of poll fds and an array of poll fd structures that is
303 * (re)allocated as necessary prior to polling. Protected by event_data_lock. */
304 struct list_head ipollfds;
305 struct pollfd *pollfds;
306 POLL_NFDS_TYPE pollfds_cnt;
308 /* A list of pending hotplug messages. Protected by event_data_lock. */
309 struct list_head hotplug_msgs;
311 /* A list of pending completed transfers. Protected by event_data_lock. */
312 struct list_head completed_transfers;
314 #ifdef USBI_TIMERFD_AVAILABLE
315 /* used for timeout handling, if supported by OS.
316 * this timerfd is maintained to trigger on the next pending timeout */
320 struct list_head list;
323 enum usbi_event_flags {
324 /* The list of pollfds has been modified */
325 USBI_EVENT_POLLFDS_MODIFIED = 1 << 0,
328 /* Macros for managing event handling state */
329 #define usbi_handling_events(ctx) \
330 (usbi_tls_key_get((ctx)->event_handling_key) != NULL)
332 #define usbi_start_event_handling(ctx) \
333 usbi_tls_key_set((ctx)->event_handling_key, ctx)
335 #define usbi_end_event_handling(ctx) \
336 usbi_tls_key_set((ctx)->event_handling_key, NULL)
338 /* Update the following macro if new event sources are added */
339 #define usbi_pending_events(ctx) \
340 ((ctx)->event_flags || (ctx)->device_close \
341 || !list_empty(&(ctx)->hotplug_msgs) || !list_empty(&(ctx)->completed_transfers))
343 #ifdef USBI_TIMERFD_AVAILABLE
344 #define usbi_using_timerfd(ctx) ((ctx)->timerfd >= 0)
346 #define usbi_using_timerfd(ctx) (0)
349 struct libusb_device {
350 /* lock protects refcnt, everything else is finalized at initialization
355 struct libusb_context *ctx;
359 struct libusb_device* parent_dev;
360 uint8_t device_address;
361 uint8_t num_configurations;
362 enum libusb_speed speed;
364 struct list_head list;
365 unsigned long session_data;
367 struct libusb_device_descriptor device_descriptor;
370 unsigned char os_priv
371 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
372 [] /* valid C99 code */
374 [0] /* non-standard, but usually working code */
379 struct libusb_device_handle {
380 /* lock protects claimed_interfaces */
382 unsigned long claimed_interfaces;
384 struct list_head list;
385 struct libusb_device *dev;
386 int auto_detach_kernel_driver;
387 unsigned char os_priv
388 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
389 [] /* valid C99 code */
391 [0] /* non-standard, but usually working code */
397 USBI_CLOCK_MONOTONIC,
401 /* in-memory transfer layout:
403 * 1. struct usbi_transfer
404 * 2. struct libusb_transfer (which includes iso packets) [variable size]
405 * 3. os private data [variable size]
407 * from a libusb_transfer, you can get the usbi_transfer by rewinding the
408 * appropriate number of bytes.
409 * the usbi_transfer includes the number of allocated packets, so you can
410 * determine the size of the transfer and hence the start and length of the
414 struct usbi_transfer {
416 struct list_head list;
417 struct list_head completed_list;
418 struct timeval timeout;
423 /* this lock is held during libusb_submit_transfer() and
424 * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
425 * cancellation, submission-during-cancellation, etc). the OS backend
426 * should also take this lock in the handle_events path, to prevent the user
427 * cancelling the transfer from another thread while you are processing
428 * its completion (presumably there would be races within your OS backend
429 * if this were possible). */
432 /* this lock should be held whenever viewing or modifying flags
433 * relating to the transfer state */
434 usbi_mutex_t flags_lock;
437 enum usbi_transfer_flags {
438 /* The transfer has timed out */
439 USBI_TRANSFER_TIMED_OUT = 1 << 0,
441 /* Set by backend submit_transfer() if the OS handles timeout */
442 USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1 << 1,
444 /* Cancellation was requested via libusb_cancel_transfer() */
445 USBI_TRANSFER_CANCELLING = 1 << 2,
447 /* Operation on the transfer failed because the device disappeared */
448 USBI_TRANSFER_DEVICE_DISAPPEARED = 1 << 3,
450 /* Transfer is currently being submitted */
451 USBI_TRANSFER_SUBMITTING = 1 << 4,
453 /* Transfer successfully submitted by backend */
454 USBI_TRANSFER_IN_FLIGHT = 1 << 5,
456 /* Completion handler has run */
457 USBI_TRANSFER_COMPLETED = 1 << 6,
459 /* The transfer timeout has been handled */
460 USBI_TRANSFER_TIMEOUT_HANDLED = 1 << 7,
463 #define USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer) \
464 ((struct libusb_transfer *)(((unsigned char *)(transfer)) \
465 + sizeof(struct usbi_transfer)))
466 #define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \
467 ((struct usbi_transfer *)(((unsigned char *)(transfer)) \
468 - sizeof(struct usbi_transfer)))
470 static inline void *usbi_transfer_get_os_priv(struct usbi_transfer *transfer)
472 return ((unsigned char *)transfer) + sizeof(struct usbi_transfer)
473 + sizeof(struct libusb_transfer)
474 + (transfer->num_iso_packets
475 * sizeof(struct libusb_iso_packet_descriptor));
480 /* All standard descriptors have these 2 fields in common */
481 struct usb_descriptor_header {
483 uint8_t bDescriptorType;
486 /* shared data and functions */
488 int usbi_io_init(struct libusb_context *ctx);
489 void usbi_io_exit(struct libusb_context *ctx);
491 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
492 unsigned long session_id);
493 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
494 unsigned long session_id);
495 int usbi_sanitize_device(struct libusb_device *dev);
496 void usbi_handle_disconnect(struct libusb_device_handle *handle);
498 int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
499 enum libusb_transfer_status status);
500 int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer);
501 void usbi_signal_transfer_completion(struct usbi_transfer *transfer);
503 int usbi_parse_descriptor(const unsigned char *source, const char *descriptor,
504 void *dest, int host_endian);
505 int usbi_device_cache_descriptor(libusb_device *dev);
506 int usbi_get_config_index_by_value(struct libusb_device *dev,
507 uint8_t bConfigurationValue, int *idx);
509 void usbi_connect_device (struct libusb_device *dev);
510 void usbi_disconnect_device (struct libusb_device *dev);
512 int usbi_signal_event(struct libusb_context *ctx);
513 int usbi_clear_event(struct libusb_context *ctx);
515 /* Internal abstraction for poll (needs struct usbi_transfer on Windows) */
516 #if defined(OS_LINUX) || defined(OS_DARWIN) || defined(OS_OPENBSD) || defined(OS_NETBSD) || defined(OS_HAIKU)
518 #include "os/poll_posix.h"
519 #elif defined(OS_WINDOWS) || defined(OS_WINCE)
520 #include "os/poll_windows.h"
523 #if (defined(OS_WINDOWS) || defined(OS_WINCE)) && !defined(__GNUC__)
524 #define snprintf _snprintf
525 #define vsnprintf _vsnprintf
526 int usbi_gettimeofday(struct timeval *tp, void *tzp);
527 #define LIBUSB_GETTIMEOFDAY_WIN32
528 #define HAVE_USBI_GETTIMEOFDAY
530 #ifdef HAVE_GETTIMEOFDAY
531 #define usbi_gettimeofday(tv, tz) gettimeofday((tv), (tz))
532 #define HAVE_USBI_GETTIMEOFDAY
537 /* must come first */
538 struct libusb_pollfd pollfd;
540 struct list_head list;
543 int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events);
544 void usbi_remove_pollfd(struct libusb_context *ctx, int fd);
546 /* device discovery */
548 /* we traverse usbfs without knowing how many devices we are going to find.
549 * so we create this discovered_devs model which is similar to a linked-list
550 * which grows when required. it can be freed once discovery has completed,
551 * eliminating the need for a list node in the libusb_device structure
553 struct discovered_devs {
556 struct libusb_device *devices
557 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
558 [] /* valid C99 code */
560 [0] /* non-standard, but usually working code */
565 struct discovered_devs *discovered_devs_append(
566 struct discovered_devs *discdevs, struct libusb_device *dev);
570 /* This is the interface that OS backends need to implement.
571 * All fields are mandatory, except ones explicitly noted as optional. */
572 struct usbi_os_backend {
573 /* A human-readable name for your backend, e.g. "Linux usbfs" */
576 /* Binary mask for backend specific capabilities */
579 /* Perform initialization of your backend. You might use this function
580 * to determine specific capabilities of the system, allocate required
581 * data structures for later, etc.
583 * This function is called when a libusb user initializes the library
586 * Return 0 on success, or a LIBUSB_ERROR code on failure.
588 int (*init)(struct libusb_context *ctx);
590 /* Deinitialization. Optional. This function should destroy anything
591 * that was set up by init.
593 * This function is called when the user deinitializes the library.
597 /* Enumerate all the USB devices on the system, returning them in a list
598 * of discovered devices.
600 * Your implementation should enumerate all devices on the system,
601 * regardless of whether they have been seen before or not.
603 * When you have found a device, compute a session ID for it. The session
604 * ID should uniquely represent that particular device for that particular
605 * connection session since boot (i.e. if you disconnect and reconnect a
606 * device immediately after, it should be assigned a different session ID).
607 * If your OS cannot provide a unique session ID as described above,
608 * presenting a session ID of (bus_number << 8 | device_address) should
609 * be sufficient. Bus numbers and device addresses wrap and get reused,
610 * but that is an unlikely case.
612 * After computing a session ID for a device, call
613 * usbi_get_device_by_session_id(). This function checks if libusb already
614 * knows about the device, and if so, it provides you with a reference
615 * to a libusb_device structure for it.
617 * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
618 * a new device structure for the device. Call usbi_alloc_device() to
619 * obtain a new libusb_device structure with reference count 1. Populate
620 * the bus_number and device_address attributes of the new device, and
621 * perform any other internal backend initialization you need to do. At
622 * this point, you should be ready to provide device descriptors and so
623 * on through the get_*_descriptor functions. Finally, call
624 * usbi_sanitize_device() to perform some final sanity checks on the
625 * device. Assuming all of the above succeeded, we can now continue.
626 * If any of the above failed, remember to unreference the device that
627 * was returned by usbi_alloc_device().
629 * At this stage we have a populated libusb_device structure (either one
630 * that was found earlier, or one that we have just allocated and
631 * populated). This can now be added to the discovered devices list
632 * using discovered_devs_append(). Note that discovered_devs_append()
633 * may reallocate the list, returning a new location for it, and also
634 * note that reallocation can fail. Your backend should handle these
635 * error conditions appropriately.
637 * This function should not generate any bus I/O and should not block.
638 * If I/O is required (e.g. reading the active configuration value), it is
639 * OK to ignore these suggestions :)
641 * This function is executed when the user wishes to retrieve a list
642 * of USB devices connected to the system.
644 * If the backend has hotplug support, this function is not used!
646 * Return 0 on success, or a LIBUSB_ERROR code on failure.
648 int (*get_device_list)(struct libusb_context *ctx,
649 struct discovered_devs **discdevs);
651 /* Apps which were written before hotplug support, may listen for
652 * hotplug events on their own and call libusb_get_device_list on
653 * device addition. In this case libusb_get_device_list will likely
654 * return a list without the new device in there, as the hotplug
655 * event thread will still be busy enumerating the device, which may
656 * take a while, or may not even have seen the event yet.
658 * To avoid this libusb_get_device_list will call this optional
659 * function for backends with hotplug support before copying
660 * ctx->usb_devs to the user. In this function the backend should
661 * ensure any pending hotplug events are fully processed before
664 * Optional, should be implemented by backends with hotplug support.
666 void (*hotplug_poll)(void);
668 /* Open a device for I/O and other USB operations. The device handle
669 * is preallocated for you, you can retrieve the device in question
670 * through handle->dev.
672 * Your backend should allocate any internal resources required for I/O
673 * and other operations so that those operations can happen (hopefully)
674 * without hiccup. This is also a good place to inform libusb that it
675 * should monitor certain file descriptors related to this device -
676 * see the usbi_add_pollfd() function.
678 * This function should not generate any bus I/O and should not block.
680 * This function is called when the user attempts to obtain a device
681 * handle for a device.
685 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
686 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
688 * - another LIBUSB_ERROR code on other failure
690 * Do not worry about freeing the handle on failed open, the upper layers
693 int (*open)(struct libusb_device_handle *handle);
695 /* Close a device such that the handle cannot be used again. Your backend
696 * should destroy any resources that were allocated in the open path.
697 * This may also be a good place to call usbi_remove_pollfd() to inform
698 * libusb of any file descriptors associated with this device that should
699 * no longer be monitored.
701 * This function is called when the user closes a device handle.
703 void (*close)(struct libusb_device_handle *handle);
705 /* Retrieve the device descriptor from a device.
707 * The descriptor should be retrieved from memory, NOT via bus I/O to the
708 * device. This means that you may have to cache it in a private structure
709 * during get_device_list enumeration. Alternatively, you may be able
710 * to retrieve it from a kernel interface (some Linux setups can do this)
711 * still without generating bus I/O.
713 * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into
714 * buffer, which is guaranteed to be big enough.
716 * This function is called when sanity-checking a device before adding
717 * it to the list of discovered devices, and also when the user requests
718 * to read the device descriptor.
720 * This function is expected to return the descriptor in bus-endian format
721 * (LE). If it returns the multi-byte values in host-endian format,
722 * set the host_endian output parameter to "1".
724 * Return 0 on success or a LIBUSB_ERROR code on failure.
726 int (*get_device_descriptor)(struct libusb_device *device,
727 unsigned char *buffer, int *host_endian);
729 /* Get the ACTIVE configuration descriptor for a device.
731 * The descriptor should be retrieved from memory, NOT via bus I/O to the
732 * device. This means that you may have to cache it in a private structure
733 * during get_device_list enumeration. You may also have to keep track
734 * of which configuration is active when the user changes it.
736 * This function is expected to write len bytes of data into buffer, which
737 * is guaranteed to be big enough. If you can only do a partial write,
738 * return an error code.
740 * This function is expected to return the descriptor in bus-endian format
741 * (LE). If it returns the multi-byte values in host-endian format,
742 * set the host_endian output parameter to "1".
746 * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
747 * - another LIBUSB_ERROR code on other failure
749 int (*get_active_config_descriptor)(struct libusb_device *device,
750 unsigned char *buffer, size_t len, int *host_endian);
752 /* Get a specific configuration descriptor for a device.
754 * The descriptor should be retrieved from memory, NOT via bus I/O to the
755 * device. This means that you may have to cache it in a private structure
756 * during get_device_list enumeration.
758 * The requested descriptor is expressed as a zero-based index (i.e. 0
759 * indicates that we are requesting the first descriptor). The index does
760 * not (necessarily) equal the bConfigurationValue of the configuration
763 * This function is expected to write len bytes of data into buffer, which
764 * is guaranteed to be big enough. If you can only do a partial write,
765 * return an error code.
767 * This function is expected to return the descriptor in bus-endian format
768 * (LE). If it returns the multi-byte values in host-endian format,
769 * set the host_endian output parameter to "1".
771 * Return the length read on success or a LIBUSB_ERROR code on failure.
773 int (*get_config_descriptor)(struct libusb_device *device,
774 uint8_t config_index, unsigned char *buffer, size_t len,
777 /* Like get_config_descriptor but then by bConfigurationValue instead
780 * Optional, if not present the core will call get_config_descriptor
781 * for all configs until it finds the desired bConfigurationValue.
783 * Returns a pointer to the raw-descriptor in *buffer, this memory
784 * is valid as long as device is valid.
786 * Returns the length of the returned raw-descriptor on success,
787 * or a LIBUSB_ERROR code on failure.
789 int (*get_config_descriptor_by_value)(struct libusb_device *device,
790 uint8_t bConfigurationValue, unsigned char **buffer,
793 /* Get the bConfigurationValue for the active configuration for a device.
794 * Optional. This should only be implemented if you can retrieve it from
795 * cache (don't generate I/O).
797 * If you cannot retrieve this from cache, either do not implement this
798 * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
799 * libusb to retrieve the information through a standard control transfer.
801 * This function must be non-blocking.
804 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
806 * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
808 * - another LIBUSB_ERROR code on other failure.
810 int (*get_configuration)(struct libusb_device_handle *handle, int *config);
812 /* Set the active configuration for a device.
814 * A configuration value of -1 should put the device in unconfigured state.
816 * This function can block.
820 * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
821 * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
822 * configuration cannot be changed)
823 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
825 * - another LIBUSB_ERROR code on other failure.
827 int (*set_configuration)(struct libusb_device_handle *handle, int config);
829 /* Claim an interface. When claimed, the application can then perform
830 * I/O to an interface's endpoints.
832 * This function should not generate any bus I/O and should not block.
833 * Interface claiming is a logical operation that simply ensures that
834 * no other drivers/applications are using the interface, and after
835 * claiming, no other drivers/applications can use the interface because
840 * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
841 * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
842 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
844 * - another LIBUSB_ERROR code on other failure
846 int (*claim_interface)(struct libusb_device_handle *handle, int interface_number);
848 /* Release a previously claimed interface.
850 * This function should also generate a SET_INTERFACE control request,
851 * resetting the alternate setting of that interface to 0. It's OK for
852 * this function to block as a result.
854 * You will only ever be asked to release an interface which was
855 * successfully claimed earlier.
859 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
861 * - another LIBUSB_ERROR code on other failure
863 int (*release_interface)(struct libusb_device_handle *handle, int interface_number);
865 /* Set the alternate setting for an interface.
867 * You will only ever be asked to set the alternate setting for an
868 * interface which was successfully claimed earlier.
870 * It's OK for this function to block.
874 * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
875 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
877 * - another LIBUSB_ERROR code on other failure
879 int (*set_interface_altsetting)(struct libusb_device_handle *handle,
880 int interface_number, int altsetting);
882 /* Clear a halt/stall condition on an endpoint.
884 * It's OK for this function to block.
888 * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
889 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
891 * - another LIBUSB_ERROR code on other failure
893 int (*clear_halt)(struct libusb_device_handle *handle,
894 unsigned char endpoint);
896 /* Perform a USB port reset to reinitialize a device.
898 * If possible, the handle should still be usable after the reset
899 * completes, assuming that the device descriptors did not change during
900 * reset and all previous interface state can be restored.
902 * If something changes, or you cannot easily locate/verify the resetted
903 * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
904 * to close the old handle and re-enumerate the device.
908 * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
909 * has been disconnected since it was opened
910 * - another LIBUSB_ERROR code on other failure
912 int (*reset_device)(struct libusb_device_handle *handle);
914 /* Alloc num_streams usb3 bulk streams on the passed in endpoints */
915 int (*alloc_streams)(struct libusb_device_handle *handle,
916 uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
918 /* Free usb3 bulk streams allocated with alloc_streams */
919 int (*free_streams)(struct libusb_device_handle *handle,
920 unsigned char *endpoints, int num_endpoints);
922 /* Determine if a kernel driver is active on an interface. Optional.
924 * The presence of a kernel driver on an interface indicates that any
925 * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
928 * - 0 if no driver is active
929 * - 1 if a driver is active
930 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
932 * - another LIBUSB_ERROR code on other failure
934 int (*kernel_driver_active)(struct libusb_device_handle *handle,
935 int interface_number);
937 /* Detach a kernel driver from an interface. Optional.
939 * After detaching a kernel driver, the interface should be available
944 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
945 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
946 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
948 * - another LIBUSB_ERROR code on other failure
950 int (*detach_kernel_driver)(struct libusb_device_handle *handle,
951 int interface_number);
953 /* Attach a kernel driver to an interface. Optional.
955 * Reattach a kernel driver to the device.
959 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
960 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
961 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
963 * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
964 * preventing reattachment
965 * - another LIBUSB_ERROR code on other failure
967 int (*attach_kernel_driver)(struct libusb_device_handle *handle,
968 int interface_number);
970 /* Destroy a device. Optional.
972 * This function is called when the last reference to a device is
973 * destroyed. It should free any resources allocated in the get_device_list
976 void (*destroy_device)(struct libusb_device *dev);
978 /* Submit a transfer. Your implementation should take the transfer,
979 * morph it into whatever form your platform requires, and submit it
982 * This function must not block.
984 * This function gets called with the flying_transfers_lock locked!
988 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
989 * - another LIBUSB_ERROR code on other failure
991 int (*submit_transfer)(struct usbi_transfer *itransfer);
993 /* Cancel a previously submitted transfer.
995 * This function must not block. The transfer cancellation must complete
996 * later, resulting in a call to usbi_handle_transfer_cancellation()
997 * from the context of handle_events.
999 int (*cancel_transfer)(struct usbi_transfer *itransfer);
1001 /* Clear a transfer as if it has completed or cancelled, but do not
1002 * report any completion/cancellation to the library. You should free
1003 * all private data from the transfer as if you were just about to report
1004 * completion or cancellation.
1006 * This function might seem a bit out of place. It is used when libusb
1007 * detects a disconnected device - it calls this function for all pending
1008 * transfers before reporting completion (with the disconnect code) to
1009 * the user. Maybe we can improve upon this internal interface in future.
1011 void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
1013 /* Handle any pending events on file descriptors. Optional.
1015 * Provide this function when file descriptors directly indicate device
1016 * or transfer activity. If your backend does not have such file descriptors,
1017 * implement the handle_transfer_completion function below.
1019 * This involves monitoring any active transfers and processing their
1020 * completion or cancellation.
1022 * The function is passed an array of pollfd structures (size nfds)
1023 * as a result of the poll() system call. The num_ready parameter
1024 * indicates the number of file descriptors that have reported events
1025 * (i.e. the poll() return value). This should be enough information
1026 * for you to determine which actions need to be taken on the currently
1029 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1030 * For completed transfers, call usbi_handle_transfer_completion().
1031 * For control/bulk/interrupt transfers, populate the "transferred"
1032 * element of the appropriate usbi_transfer structure before calling the
1033 * above functions. For isochronous transfers, populate the status and
1034 * transferred fields of the iso packet descriptors of the transfer.
1036 * This function should also be able to detect disconnection of the
1037 * device, reporting that situation with usbi_handle_disconnect().
1039 * When processing an event related to a transfer, you probably want to
1040 * take usbi_transfer.lock to prevent races. See the documentation for
1041 * the usbi_transfer structure.
1043 * Return 0 on success, or a LIBUSB_ERROR code on failure.
1045 int (*handle_events)(struct libusb_context *ctx,
1046 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready);
1048 /* Handle transfer completion. Optional.
1050 * Provide this function when there are no file descriptors available
1051 * that directly indicate device or transfer activity. If your backend does
1052 * have such file descriptors, implement the handle_events function above.
1054 * Your backend must tell the library when a transfer has completed by
1055 * calling usbi_signal_transfer_completion(). You should store any private
1056 * information about the transfer and its completion status in the transfer's
1057 * private backend data.
1059 * During event handling, this function will be called on each transfer for
1060 * which usbi_signal_transfer_completion() was called.
1062 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1063 * For completed transfers, call usbi_handle_transfer_completion().
1064 * For control/bulk/interrupt transfers, populate the "transferred"
1065 * element of the appropriate usbi_transfer structure before calling the
1066 * above functions. For isochronous transfers, populate the status and
1067 * transferred fields of the iso packet descriptors of the transfer.
1069 * Return 0 on success, or a LIBUSB_ERROR code on failure.
1071 int (*handle_transfer_completion)(struct usbi_transfer *itransfer);
1073 /* Get time from specified clock. At least two clocks must be implemented
1074 by the backend: USBI_CLOCK_REALTIME, and USBI_CLOCK_MONOTONIC.
1076 Description of clocks:
1077 USBI_CLOCK_REALTIME : clock returns time since system epoch.
1078 USBI_CLOCK_MONOTONIC: clock returns time since unspecified start
1079 time (usually boot).
1081 int (*clock_gettime)(int clkid, struct timespec *tp);
1083 #ifdef USBI_TIMERFD_AVAILABLE
1084 /* clock ID of the clock that should be used for timerfd */
1085 clockid_t (*get_timerfd_clockid)(void);
1088 /* Number of bytes to reserve for per-device private backend data.
1089 * This private data area is accessible through the "os_priv" field of
1090 * struct libusb_device. */
1091 size_t device_priv_size;
1093 /* Number of bytes to reserve for per-handle private backend data.
1094 * This private data area is accessible through the "os_priv" field of
1095 * struct libusb_device. */
1096 size_t device_handle_priv_size;
1098 /* Number of bytes to reserve for per-transfer private backend data.
1099 * This private data area is accessible by calling
1100 * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance.
1102 size_t transfer_priv_size;
1105 extern const struct usbi_os_backend * const usbi_backend;
1107 extern const struct usbi_os_backend linux_usbfs_backend;
1108 extern const struct usbi_os_backend darwin_backend;
1109 extern const struct usbi_os_backend openbsd_backend;
1110 extern const struct usbi_os_backend netbsd_backend;
1111 extern const struct usbi_os_backend windows_backend;
1112 extern const struct usbi_os_backend wince_backend;
1113 extern const struct usbi_os_backend haiku_usb_raw_backend;
1115 extern struct list_head active_contexts_list;
1116 extern usbi_mutex_static_t active_contexts_lock;