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
64 #define USBI_CAP_HAS_POLLABLE_DEVICE_FD 0x00040000
66 /* Maximum number of bytes in a log line */
67 #define USBI_MAX_LOG_LEN 1024
68 /* Terminator for log lines */
69 #define USBI_LOG_LINE_END "\n"
71 /* The following is used to silence warnings for unused variables */
72 #define UNUSED(var) do { (void)(var); } while(0)
74 #if !defined(ARRAYSIZE)
75 #define ARRAYSIZE(array) (sizeof(array)/sizeof(array[0]))
79 struct list_head *prev, *next;
82 /* Get an entry from the list
83 * ptr - the address of this list_head element in "type"
84 * type - the data type that contains "member"
85 * member - the list_head element in "type"
87 #define list_entry(ptr, type, member) \
88 ((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
90 /* Get each entry from a list
91 * pos - A structure pointer has a "member" element
93 * member - the list_head element in "pos"
94 * type - the type of the first parameter
96 #define list_for_each_entry(pos, head, member, type) \
97 for (pos = list_entry((head)->next, type, member); \
98 &pos->member != (head); \
99 pos = list_entry(pos->member.next, type, member))
101 #define list_for_each_entry_safe(pos, n, head, member, type) \
102 for (pos = list_entry((head)->next, type, member), \
103 n = list_entry(pos->member.next, type, member); \
104 &pos->member != (head); \
105 pos = n, n = list_entry(n->member.next, type, member))
107 #define list_empty(entry) ((entry)->next == (entry))
109 static inline void list_init(struct list_head *entry)
111 entry->prev = entry->next = entry;
114 static inline void list_add(struct list_head *entry, struct list_head *head)
116 entry->next = head->next;
119 head->next->prev = entry;
123 static inline void list_add_tail(struct list_head *entry,
124 struct list_head *head)
127 entry->prev = head->prev;
129 head->prev->next = entry;
133 static inline void list_del(struct list_head *entry)
135 entry->next->prev = entry->prev;
136 entry->prev->next = entry->next;
137 entry->next = entry->prev = NULL;
140 static inline void *usbi_reallocf(void *ptr, size_t size)
142 void *ret = realloc(ptr, size);
148 #define container_of(ptr, type, member) ({ \
149 const typeof( ((type *)0)->member ) *mptr = (ptr); \
150 (type *)( (char *)mptr - offsetof(type,member) );})
153 #define MIN(a, b) ((a) < (b) ? (a) : (b))
156 #define MAX(a, b) ((a) > (b) ? (a) : (b))
159 #define TIMESPEC_IS_SET(ts) ((ts)->tv_sec != 0 || (ts)->tv_nsec != 0)
161 /* Some platforms don't have this define */
162 #ifndef TIMESPEC_TO_TIMEVAL
163 #define TIMESPEC_TO_TIMEVAL(tv, ts) \
165 (tv)->tv_sec = (ts)->tv_sec; \
166 (tv)->tv_usec = (ts)->tv_nsec / 1000; \
170 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
171 const char *function, const char *format, ...);
173 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
174 const char *function, const char *format, va_list args);
176 #if !defined(_MSC_VER) || _MSC_VER >= 1400
178 #ifdef ENABLE_LOGGING
179 #define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __FUNCTION__, __VA_ARGS__)
180 #define usbi_dbg(...) _usbi_log(NULL, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
182 #define _usbi_log(ctx, level, ...) do { (void)(ctx); } while(0)
183 #define usbi_dbg(...) do {} while(0)
186 #define usbi_info(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
187 #define usbi_warn(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
188 #define usbi_err(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
190 #else /* !defined(_MSC_VER) || _MSC_VER >= 1400 */
192 #ifdef ENABLE_LOGGING
193 #define LOG_BODY(ctxt, level) \
196 va_start (args, format); \
197 usbi_log_v(ctxt, level, "", format, args); \
201 #define LOG_BODY(ctxt, level) do { (void)(ctxt); } while(0)
204 static inline void usbi_info(struct libusb_context *ctx, const char *format,
206 LOG_BODY(ctx,LIBUSB_LOG_LEVEL_INFO)
207 static inline void usbi_warn(struct libusb_context *ctx, const char *format,
209 LOG_BODY(ctx,LIBUSB_LOG_LEVEL_WARNING)
210 static inline void usbi_err( struct libusb_context *ctx, const char *format,
212 LOG_BODY(ctx,LIBUSB_LOG_LEVEL_ERROR)
214 static inline void usbi_dbg(const char *format, ...)
215 LOG_BODY(NULL,LIBUSB_LOG_LEVEL_DEBUG)
217 #endif /* !defined(_MSC_VER) || _MSC_VER >= 1400 */
219 #define USBI_GET_CONTEXT(ctx) if (!(ctx)) (ctx) = usbi_default_context
220 #define DEVICE_CTX(dev) ((dev)->ctx)
221 #define HANDLE_CTX(handle) (DEVICE_CTX((handle)->dev))
222 #define TRANSFER_CTX(transfer) (HANDLE_CTX((transfer)->dev_handle))
223 #define ITRANSFER_CTX(transfer) \
224 (TRANSFER_CTX(USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)))
226 #define IS_EPIN(ep) (0 != ((ep) & LIBUSB_ENDPOINT_IN))
227 #define IS_EPOUT(ep) (!IS_EPIN(ep))
228 #define IS_XFERIN(xfer) (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
229 #define IS_XFEROUT(xfer) (!IS_XFERIN(xfer))
231 /* Internal abstraction for thread synchronization */
232 #if defined(THREADS_POSIX)
233 #include "os/threads_posix.h"
234 #elif defined(OS_WINDOWS) || defined(OS_WINCE)
235 #include <os/threads_windows.h>
238 extern struct libusb_context *usbi_default_context;
240 /* Forward declaration for use in context (fully defined inside poll abstraction) */
243 struct libusb_context {
247 /* internal event pipe, used for signalling occurrence of an internal event. */
250 struct list_head usb_devs;
251 usbi_mutex_t usb_devs_lock;
253 /* A list of open handles. Backends are free to traverse this if required.
255 struct list_head open_devs;
256 usbi_mutex_t open_devs_lock;
258 /* A list of registered hotplug callbacks */
259 struct list_head hotplug_cbs;
260 usbi_mutex_t hotplug_cbs_lock;
263 /* this is a list of in-flight transfer handles, sorted by timeout
264 * expiration. URBs to timeout the soonest are placed at the beginning of
265 * the list, URBs that will time out later are placed after, and urbs with
266 * infinite timeout are always placed at the very end. */
267 struct list_head flying_transfers;
268 usbi_mutex_t flying_transfers_lock;
270 /* list and count of poll fds and an array of poll fd structures that is
271 * (re)allocated as necessary prior to polling, and a flag to indicate
272 * when the list of poll fds has changed since the last poll. */
273 struct list_head ipollfds;
274 struct pollfd *pollfds;
275 POLL_NFDS_TYPE pollfds_cnt;
276 unsigned int pollfds_modified;
277 usbi_mutex_t pollfds_lock;
279 /* user callbacks for pollfd changes */
280 libusb_pollfd_added_cb fd_added_cb;
281 libusb_pollfd_removed_cb fd_removed_cb;
282 void *fd_cb_user_data;
284 /* ensures that only one thread is handling events at any one time */
285 usbi_mutex_t events_lock;
287 /* used to see if there is an active thread doing event handling */
288 int event_handler_active;
290 /* A lock to protect internal context event data. */
291 usbi_mutex_t event_data_lock;
293 /* A counter that is set when we want to interrupt and prevent event handling,
294 * in order to safely close a device. Protected by event_data_lock. */
295 unsigned int device_close;
297 /* used to wait for event completion in threads other than the one that is
299 usbi_mutex_t event_waiters_lock;
300 usbi_cond_t event_waiters_cond;
302 #ifdef USBI_TIMERFD_AVAILABLE
303 /* used for timeout handling, if supported by OS.
304 * this timerfd is maintained to trigger on the next pending timeout */
308 struct list_head list;
311 #ifdef USBI_TIMERFD_AVAILABLE
312 #define usbi_using_timerfd(ctx) ((ctx)->timerfd >= 0)
314 #define usbi_using_timerfd(ctx) (0)
317 struct libusb_device {
318 /* lock protects refcnt, everything else is finalized at initialization
323 struct libusb_context *ctx;
327 struct libusb_device* parent_dev;
328 uint8_t device_address;
329 uint8_t num_configurations;
330 enum libusb_speed speed;
332 struct list_head list;
333 unsigned long session_data;
335 struct libusb_device_descriptor device_descriptor;
338 unsigned char os_priv
339 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
340 [] /* valid C99 code */
342 [0] /* non-standard, but usually working code */
347 struct libusb_device_handle {
348 /* lock protects claimed_interfaces */
350 unsigned long claimed_interfaces;
352 struct list_head list;
353 struct libusb_device *dev;
354 int auto_detach_kernel_driver;
355 unsigned char os_priv
356 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
357 [] /* valid C99 code */
359 [0] /* non-standard, but usually working code */
365 USBI_CLOCK_MONOTONIC,
369 /* in-memory transfer layout:
371 * 1. struct usbi_transfer
372 * 2. struct libusb_transfer (which includes iso packets) [variable size]
373 * 3. os private data [variable size]
375 * from a libusb_transfer, you can get the usbi_transfer by rewinding the
376 * appropriate number of bytes.
377 * the usbi_transfer includes the number of allocated packets, so you can
378 * determine the size of the transfer and hence the start and length of the
382 struct usbi_transfer {
384 struct list_head list;
385 struct timeval timeout;
390 /* this lock is held during libusb_submit_transfer() and
391 * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
392 * cancellation, submission-during-cancellation, etc). the OS backend
393 * should also take this lock in the handle_events path, to prevent the user
394 * cancelling the transfer from another thread while you are processing
395 * its completion (presumably there would be races within your OS backend
396 * if this were possible). */
400 enum usbi_transfer_flags {
401 /* The transfer has timed out */
402 USBI_TRANSFER_TIMED_OUT = 1 << 0,
404 /* Set by backend submit_transfer() if the OS handles timeout */
405 USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1 << 1,
407 /* Cancellation was requested via libusb_cancel_transfer() */
408 USBI_TRANSFER_CANCELLING = 1 << 2,
410 /* Operation on the transfer failed because the device disappeared */
411 USBI_TRANSFER_DEVICE_DISAPPEARED = 1 << 3,
413 /* Set by backend submit_transfer() if the fds in use have been updated */
414 USBI_TRANSFER_UPDATED_FDS = 1 << 4,
417 #define USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer) \
418 ((struct libusb_transfer *)(((unsigned char *)(transfer)) \
419 + sizeof(struct usbi_transfer)))
420 #define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \
421 ((struct usbi_transfer *)(((unsigned char *)(transfer)) \
422 - sizeof(struct usbi_transfer)))
424 static inline void *usbi_transfer_get_os_priv(struct usbi_transfer *transfer)
426 return ((unsigned char *)transfer) + sizeof(struct usbi_transfer)
427 + sizeof(struct libusb_transfer)
428 + (transfer->num_iso_packets
429 * sizeof(struct libusb_iso_packet_descriptor));
434 /* All standard descriptors have these 2 fields in common */
435 struct usb_descriptor_header {
437 uint8_t bDescriptorType;
440 /* shared data and functions */
442 int usbi_io_init(struct libusb_context *ctx);
443 void usbi_io_exit(struct libusb_context *ctx);
445 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
446 unsigned long session_id);
447 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
448 unsigned long session_id);
449 int usbi_sanitize_device(struct libusb_device *dev);
450 void usbi_handle_disconnect(struct libusb_device_handle *handle);
452 int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
453 enum libusb_transfer_status status);
454 int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer);
456 int usbi_parse_descriptor(const unsigned char *source, const char *descriptor,
457 void *dest, int host_endian);
458 int usbi_device_cache_descriptor(libusb_device *dev);
459 int usbi_get_config_index_by_value(struct libusb_device *dev,
460 uint8_t bConfigurationValue, int *idx);
462 void usbi_connect_device (struct libusb_device *dev);
463 void usbi_disconnect_device (struct libusb_device *dev);
465 int usbi_signal_event(struct libusb_context *ctx);
466 int usbi_clear_event(struct libusb_context *ctx);
468 /* Internal abstraction for poll (needs struct usbi_transfer on Windows) */
469 #if defined(OS_LINUX) || defined(OS_DARWIN) || defined(OS_OPENBSD) || defined(OS_NETBSD) || defined(OS_HAIKU)
471 #include "os/poll_posix.h"
472 #elif defined(OS_WINDOWS) || defined(OS_WINCE)
473 #include "os/poll_windows.h"
476 #if (defined(OS_WINDOWS) || defined(OS_WINCE)) && !defined(__GNUC__)
477 #define snprintf _snprintf
478 #define vsnprintf _vsnprintf
479 int usbi_gettimeofday(struct timeval *tp, void *tzp);
480 #define LIBUSB_GETTIMEOFDAY_WIN32
481 #define HAVE_USBI_GETTIMEOFDAY
483 #ifdef HAVE_GETTIMEOFDAY
484 #define usbi_gettimeofday(tv, tz) gettimeofday((tv), (tz))
485 #define HAVE_USBI_GETTIMEOFDAY
490 /* must come first */
491 struct libusb_pollfd pollfd;
493 struct list_head list;
496 int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events);
497 void usbi_remove_pollfd(struct libusb_context *ctx, int fd);
498 void usbi_fd_notification(struct libusb_context *ctx);
500 /* device discovery */
502 /* we traverse usbfs without knowing how many devices we are going to find.
503 * so we create this discovered_devs model which is similar to a linked-list
504 * which grows when required. it can be freed once discovery has completed,
505 * eliminating the need for a list node in the libusb_device structure
507 struct discovered_devs {
510 struct libusb_device *devices
511 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
512 [] /* valid C99 code */
514 [0] /* non-standard, but usually working code */
519 struct discovered_devs *discovered_devs_append(
520 struct discovered_devs *discdevs, struct libusb_device *dev);
524 /* This is the interface that OS backends need to implement.
525 * All fields are mandatory, except ones explicitly noted as optional. */
526 struct usbi_os_backend {
527 /* A human-readable name for your backend, e.g. "Linux usbfs" */
530 /* Binary mask for backend specific capabilities */
533 /* Perform initialization of your backend. You might use this function
534 * to determine specific capabilities of the system, allocate required
535 * data structures for later, etc.
537 * This function is called when a libusb user initializes the library
540 * Return 0 on success, or a LIBUSB_ERROR code on failure.
542 int (*init)(struct libusb_context *ctx);
544 /* Deinitialization. Optional. This function should destroy anything
545 * that was set up by init.
547 * This function is called when the user deinitializes the library.
551 /* Enumerate all the USB devices on the system, returning them in a list
552 * of discovered devices.
554 * Your implementation should enumerate all devices on the system,
555 * regardless of whether they have been seen before or not.
557 * When you have found a device, compute a session ID for it. The session
558 * ID should uniquely represent that particular device for that particular
559 * connection session since boot (i.e. if you disconnect and reconnect a
560 * device immediately after, it should be assigned a different session ID).
561 * If your OS cannot provide a unique session ID as described above,
562 * presenting a session ID of (bus_number << 8 | device_address) should
563 * be sufficient. Bus numbers and device addresses wrap and get reused,
564 * but that is an unlikely case.
566 * After computing a session ID for a device, call
567 * usbi_get_device_by_session_id(). This function checks if libusb already
568 * knows about the device, and if so, it provides you with a reference
569 * to a libusb_device structure for it.
571 * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
572 * a new device structure for the device. Call usbi_alloc_device() to
573 * obtain a new libusb_device structure with reference count 1. Populate
574 * the bus_number and device_address attributes of the new device, and
575 * perform any other internal backend initialization you need to do. At
576 * this point, you should be ready to provide device descriptors and so
577 * on through the get_*_descriptor functions. Finally, call
578 * usbi_sanitize_device() to perform some final sanity checks on the
579 * device. Assuming all of the above succeeded, we can now continue.
580 * If any of the above failed, remember to unreference the device that
581 * was returned by usbi_alloc_device().
583 * At this stage we have a populated libusb_device structure (either one
584 * that was found earlier, or one that we have just allocated and
585 * populated). This can now be added to the discovered devices list
586 * using discovered_devs_append(). Note that discovered_devs_append()
587 * may reallocate the list, returning a new location for it, and also
588 * note that reallocation can fail. Your backend should handle these
589 * error conditions appropriately.
591 * This function should not generate any bus I/O and should not block.
592 * If I/O is required (e.g. reading the active configuration value), it is
593 * OK to ignore these suggestions :)
595 * This function is executed when the user wishes to retrieve a list
596 * of USB devices connected to the system.
598 * If the backend has hotplug support, this function is not used!
600 * Return 0 on success, or a LIBUSB_ERROR code on failure.
602 int (*get_device_list)(struct libusb_context *ctx,
603 struct discovered_devs **discdevs);
605 /* Apps which were written before hotplug support, may listen for
606 * hotplug events on their own and call libusb_get_device_list on
607 * device addition. In this case libusb_get_device_list will likely
608 * return a list without the new device in there, as the hotplug
609 * event thread will still be busy enumerating the device, which may
610 * take a while, or may not even have seen the event yet.
612 * To avoid this libusb_get_device_list will call this optional
613 * function for backends with hotplug support before copying
614 * ctx->usb_devs to the user. In this function the backend should
615 * ensure any pending hotplug events are fully processed before
618 * Optional, should be implemented by backends with hotplug support.
620 void (*hotplug_poll)(void);
622 /* Open a device for I/O and other USB operations. The device handle
623 * is preallocated for you, you can retrieve the device in question
624 * through handle->dev.
626 * Your backend should allocate any internal resources required for I/O
627 * and other operations so that those operations can happen (hopefully)
628 * without hiccup. This is also a good place to inform libusb that it
629 * should monitor certain file descriptors related to this device -
630 * see the usbi_add_pollfd() function.
632 * This function should not generate any bus I/O and should not block.
634 * This function is called when the user attempts to obtain a device
635 * handle for a device.
639 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
640 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
642 * - another LIBUSB_ERROR code on other failure
644 * Do not worry about freeing the handle on failed open, the upper layers
647 int (*open)(struct libusb_device_handle *handle);
649 /* Close a device such that the handle cannot be used again. Your backend
650 * should destroy any resources that were allocated in the open path.
651 * This may also be a good place to call usbi_remove_pollfd() to inform
652 * libusb of any file descriptors associated with this device that should
653 * no longer be monitored.
655 * This function is called when the user closes a device handle.
657 void (*close)(struct libusb_device_handle *handle);
659 /* Retrieve the device descriptor from a device.
661 * The descriptor should be retrieved from memory, NOT via bus I/O to the
662 * device. This means that you may have to cache it in a private structure
663 * during get_device_list enumeration. Alternatively, you may be able
664 * to retrieve it from a kernel interface (some Linux setups can do this)
665 * still without generating bus I/O.
667 * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into
668 * buffer, which is guaranteed to be big enough.
670 * This function is called when sanity-checking a device before adding
671 * it to the list of discovered devices, and also when the user requests
672 * to read the device descriptor.
674 * This function is expected to return the descriptor in bus-endian format
675 * (LE). If it returns the multi-byte values in host-endian format,
676 * set the host_endian output parameter to "1".
678 * Return 0 on success or a LIBUSB_ERROR code on failure.
680 int (*get_device_descriptor)(struct libusb_device *device,
681 unsigned char *buffer, int *host_endian);
683 /* Get the ACTIVE configuration descriptor for a device.
685 * The descriptor should be retrieved from memory, NOT via bus I/O to the
686 * device. This means that you may have to cache it in a private structure
687 * during get_device_list enumeration. You may also have to keep track
688 * of which configuration is active when the user changes it.
690 * This function is expected to write len bytes of data into buffer, which
691 * is guaranteed to be big enough. If you can only do a partial write,
692 * return an error code.
694 * This function is expected to return the descriptor in bus-endian format
695 * (LE). If it returns the multi-byte values in host-endian format,
696 * set the host_endian output parameter to "1".
700 * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
701 * - another LIBUSB_ERROR code on other failure
703 int (*get_active_config_descriptor)(struct libusb_device *device,
704 unsigned char *buffer, size_t len, int *host_endian);
706 /* Get a specific configuration descriptor for a device.
708 * The descriptor should be retrieved from memory, NOT via bus I/O to the
709 * device. This means that you may have to cache it in a private structure
710 * during get_device_list enumeration.
712 * The requested descriptor is expressed as a zero-based index (i.e. 0
713 * indicates that we are requesting the first descriptor). The index does
714 * not (necessarily) equal the bConfigurationValue of the configuration
717 * This function is expected to write len bytes of data into buffer, which
718 * is guaranteed to be big enough. If you can only do a partial write,
719 * return an error code.
721 * This function is expected to return the descriptor in bus-endian format
722 * (LE). If it returns the multi-byte values in host-endian format,
723 * set the host_endian output parameter to "1".
725 * Return the length read on success or a LIBUSB_ERROR code on failure.
727 int (*get_config_descriptor)(struct libusb_device *device,
728 uint8_t config_index, unsigned char *buffer, size_t len,
731 /* Like get_config_descriptor but then by bConfigurationValue instead
734 * Optional, if not present the core will call get_config_descriptor
735 * for all configs until it finds the desired bConfigurationValue.
737 * Returns a pointer to the raw-descriptor in *buffer, this memory
738 * is valid as long as device is valid.
740 * Returns the length of the returned raw-descriptor on success,
741 * or a LIBUSB_ERROR code on failure.
743 int (*get_config_descriptor_by_value)(struct libusb_device *device,
744 uint8_t bConfigurationValue, unsigned char **buffer,
747 /* Get the bConfigurationValue for the active configuration for a device.
748 * Optional. This should only be implemented if you can retrieve it from
749 * cache (don't generate I/O).
751 * If you cannot retrieve this from cache, either do not implement this
752 * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
753 * libusb to retrieve the information through a standard control transfer.
755 * This function must be non-blocking.
758 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
760 * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
762 * - another LIBUSB_ERROR code on other failure.
764 int (*get_configuration)(struct libusb_device_handle *handle, int *config);
766 /* Set the active configuration for a device.
768 * A configuration value of -1 should put the device in unconfigured state.
770 * This function can block.
774 * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
775 * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
776 * configuration cannot be changed)
777 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
779 * - another LIBUSB_ERROR code on other failure.
781 int (*set_configuration)(struct libusb_device_handle *handle, int config);
783 /* Claim an interface. When claimed, the application can then perform
784 * I/O to an interface's endpoints.
786 * This function should not generate any bus I/O and should not block.
787 * Interface claiming is a logical operation that simply ensures that
788 * no other drivers/applications are using the interface, and after
789 * claiming, no other drivers/applicatiosn can use the interface because
794 * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
795 * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
796 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
798 * - another LIBUSB_ERROR code on other failure
800 int (*claim_interface)(struct libusb_device_handle *handle, int interface_number);
802 /* Release a previously claimed interface.
804 * This function should also generate a SET_INTERFACE control request,
805 * resetting the alternate setting of that interface to 0. It's OK for
806 * this function to block as a result.
808 * You will only ever be asked to release an interface which was
809 * successfully claimed earlier.
813 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
815 * - another LIBUSB_ERROR code on other failure
817 int (*release_interface)(struct libusb_device_handle *handle, int interface_number);
819 /* Set the alternate setting for an interface.
821 * You will only ever be asked to set the alternate setting for an
822 * interface which was successfully claimed earlier.
824 * It's OK for this function to block.
828 * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
829 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
831 * - another LIBUSB_ERROR code on other failure
833 int (*set_interface_altsetting)(struct libusb_device_handle *handle,
834 int interface_number, int altsetting);
836 /* Clear a halt/stall condition on an endpoint.
838 * It's OK for this function to block.
842 * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
843 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
845 * - another LIBUSB_ERROR code on other failure
847 int (*clear_halt)(struct libusb_device_handle *handle,
848 unsigned char endpoint);
850 /* Perform a USB port reset to reinitialize a device.
852 * If possible, the handle should still be usable after the reset
853 * completes, assuming that the device descriptors did not change during
854 * reset and all previous interface state can be restored.
856 * If something changes, or you cannot easily locate/verify the resetted
857 * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
858 * to close the old handle and re-enumerate the device.
862 * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
863 * has been disconnected since it was opened
864 * - another LIBUSB_ERROR code on other failure
866 int (*reset_device)(struct libusb_device_handle *handle);
868 /* Alloc num_streams usb3 bulk streams on the passed in endpoints */
869 int (*alloc_streams)(struct libusb_device_handle *handle,
870 uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
872 /* Free usb3 bulk streams allocated with alloc_streams */
873 int (*free_streams)(struct libusb_device_handle *handle,
874 unsigned char *endpoints, int num_endpoints);
876 /* Determine if a kernel driver is active on an interface. Optional.
878 * The presence of a kernel driver on an interface indicates that any
879 * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
882 * - 0 if no driver is active
883 * - 1 if a driver is active
884 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
886 * - another LIBUSB_ERROR code on other failure
888 int (*kernel_driver_active)(struct libusb_device_handle *handle,
889 int interface_number);
891 /* Detach a kernel driver from an interface. Optional.
893 * After detaching a kernel driver, the interface should be available
898 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
899 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
900 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
902 * - another LIBUSB_ERROR code on other failure
904 int (*detach_kernel_driver)(struct libusb_device_handle *handle,
905 int interface_number);
907 /* Attach a kernel driver to an interface. Optional.
909 * Reattach a kernel driver to the device.
913 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
914 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
915 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
917 * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
918 * preventing reattachment
919 * - another LIBUSB_ERROR code on other failure
921 int (*attach_kernel_driver)(struct libusb_device_handle *handle,
922 int interface_number);
924 /* Destroy a device. Optional.
926 * This function is called when the last reference to a device is
927 * destroyed. It should free any resources allocated in the get_device_list
930 void (*destroy_device)(struct libusb_device *dev);
932 /* Submit a transfer. Your implementation should take the transfer,
933 * morph it into whatever form your platform requires, and submit it
936 * This function must not block.
938 * This function gets called with the flying_transfers_lock locked!
942 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
943 * - another LIBUSB_ERROR code on other failure
945 int (*submit_transfer)(struct usbi_transfer *itransfer);
947 /* Cancel a previously submitted transfer.
949 * This function must not block. The transfer cancellation must complete
950 * later, resulting in a call to usbi_handle_transfer_cancellation()
951 * from the context of handle_events.
953 int (*cancel_transfer)(struct usbi_transfer *itransfer);
955 /* Clear a transfer as if it has completed or cancelled, but do not
956 * report any completion/cancellation to the library. You should free
957 * all private data from the transfer as if you were just about to report
958 * completion or cancellation.
960 * This function might seem a bit out of place. It is used when libusb
961 * detects a disconnected device - it calls this function for all pending
962 * transfers before reporting completion (with the disconnect code) to
963 * the user. Maybe we can improve upon this internal interface in future.
965 void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
967 /* Handle any pending events. This involves monitoring any active
968 * transfers and processing their completion or cancellation.
970 * The function is passed an array of pollfd structures (size nfds)
971 * as a result of the poll() system call. The num_ready parameter
972 * indicates the number of file descriptors that have reported events
973 * (i.e. the poll() return value). This should be enough information
974 * for you to determine which actions need to be taken on the currently
977 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
978 * For completed transfers, call usbi_handle_transfer_completion().
979 * For control/bulk/interrupt transfers, populate the "transferred"
980 * element of the appropriate usbi_transfer structure before calling the
981 * above functions. For isochronous transfers, populate the status and
982 * transferred fields of the iso packet descriptors of the transfer.
984 * This function should also be able to detect disconnection of the
985 * device, reporting that situation with usbi_handle_disconnect().
987 * When processing an event related to a transfer, you probably want to
988 * take usbi_transfer.lock to prevent races. See the documentation for
989 * the usbi_transfer structure.
991 * Return 0 on success, or a LIBUSB_ERROR code on failure.
993 int (*handle_events)(struct libusb_context *ctx,
994 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready);
996 /* Get time from specified clock. At least two clocks must be implemented
997 by the backend: USBI_CLOCK_REALTIME, and USBI_CLOCK_MONOTONIC.
999 Description of clocks:
1000 USBI_CLOCK_REALTIME : clock returns time since system epoch.
1001 USBI_CLOCK_MONOTONIC: clock returns time since unspecified start
1002 time (usually boot).
1004 int (*clock_gettime)(int clkid, struct timespec *tp);
1006 #ifdef USBI_TIMERFD_AVAILABLE
1007 /* clock ID of the clock that should be used for timerfd */
1008 clockid_t (*get_timerfd_clockid)(void);
1011 /* Number of bytes to reserve for per-device private backend data.
1012 * This private data area is accessible through the "os_priv" field of
1013 * struct libusb_device. */
1014 size_t device_priv_size;
1016 /* Number of bytes to reserve for per-handle private backend data.
1017 * This private data area is accessible through the "os_priv" field of
1018 * struct libusb_device. */
1019 size_t device_handle_priv_size;
1021 /* Number of bytes to reserve for per-transfer private backend data.
1022 * This private data area is accessible by calling
1023 * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance.
1025 size_t transfer_priv_size;
1027 /* Mumber of additional bytes for os_priv for each iso packet.
1028 * Can your backend use this? */
1029 /* FIXME: linux can't use this any more. if other OS's cannot either,
1030 * then remove this */
1031 size_t add_iso_packet_size;
1034 extern const struct usbi_os_backend * const usbi_backend;
1036 extern const struct usbi_os_backend linux_usbfs_backend;
1037 extern const struct usbi_os_backend darwin_backend;
1038 extern const struct usbi_os_backend openbsd_backend;
1039 extern const struct usbi_os_backend netbsd_backend;
1040 extern const struct usbi_os_backend windows_backend;
1041 extern const struct usbi_os_backend wince_backend;
1042 extern const struct usbi_os_backend haiku_usb_raw_backend;
1044 extern struct list_head active_contexts_list;
1045 extern usbi_mutex_static_t active_contexts_lock;