linux_usbfs: Add support for new disconnect-and-claim ioctl
[libusbx.git] / libusb / libusbi.h
blobc9b402d8e1d300f4f2931f91cba8c0937d66aeb1
1 /*
2 * Internal header for libusbx
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
21 #ifndef LIBUSBI_H
22 #define LIBUSBI_H
24 #include "config.h"
26 #include <stddef.h>
27 #include <stdint.h>
28 #include <time.h>
29 #include <stdarg.h>
30 #ifdef HAVE_POLL_H
31 #include <poll.h>
32 #endif
34 #ifdef HAVE_MISSING_H
35 #include "missing.h"
36 #endif
37 #include "libusb.h"
38 #include "version.h"
40 /* Inside the libusbx code, mark all public functions as follows:
41 * return_type API_EXPORTED function_name(params) { ... }
42 * But if the function returns a pointer, mark it as follows:
43 * DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
44 * In the libusbx public header, mark all declarations as:
45 * return_type LIBUSB_CALL function_name(params);
47 #define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
49 #define DEVICE_DESC_LENGTH 18
51 #define USB_MAXENDPOINTS 32
52 #define USB_MAXINTERFACES 32
53 #define USB_MAXCONFIG 8
55 /* Backend specific capabilities */
56 #define USBI_CAP_HAS_HID_ACCESS 0x00010000
57 #define USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER 0x00020000
59 /* The following is used to silence warnings for unused variables */
60 #define UNUSED(var) do { (void)(var); } while(0)
62 #if !defined(ARRAYSIZE)
63 #define ARRAYSIZE(array) (sizeof(array)/sizeof(array[0]))
64 #endif
66 struct list_head {
67 struct list_head *prev, *next;
70 /* Get an entry from the list
71 * ptr - the address of this list_head element in "type"
72 * type - the data type that contains "member"
73 * member - the list_head element in "type"
75 #define list_entry(ptr, type, member) \
76 ((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
78 /* Get each entry from a list
79 * pos - A structure pointer has a "member" element
80 * head - list head
81 * member - the list_head element in "pos"
82 * type - the type of the first parameter
84 #define list_for_each_entry(pos, head, member, type) \
85 for (pos = list_entry((head)->next, type, member); \
86 &pos->member != (head); \
87 pos = list_entry(pos->member.next, type, member))
89 #define list_for_each_entry_safe(pos, n, head, member, type) \
90 for (pos = list_entry((head)->next, type, member), \
91 n = list_entry(pos->member.next, type, member); \
92 &pos->member != (head); \
93 pos = n, n = list_entry(n->member.next, type, member))
95 #define list_empty(entry) ((entry)->next == (entry))
97 static inline void list_init(struct list_head *entry)
99 entry->prev = entry->next = entry;
102 static inline void list_add(struct list_head *entry, struct list_head *head)
104 entry->next = head->next;
105 entry->prev = head;
107 head->next->prev = entry;
108 head->next = entry;
111 static inline void list_add_tail(struct list_head *entry,
112 struct list_head *head)
114 entry->next = head;
115 entry->prev = head->prev;
117 head->prev->next = entry;
118 head->prev = entry;
121 static inline void list_del(struct list_head *entry)
123 entry->next->prev = entry->prev;
124 entry->prev->next = entry->next;
125 entry->next = entry->prev = NULL;
128 static inline void *usbi_reallocf(void *ptr, size_t size)
130 void *ret = realloc(ptr, size);
131 if (!ret)
132 free(ptr);
133 return ret;
136 #define container_of(ptr, type, member) ({ \
137 const typeof( ((type *)0)->member ) *mptr = (ptr); \
138 (type *)( (char *)mptr - offsetof(type,member) );})
140 #define MIN(a, b) ((a) < (b) ? (a) : (b))
141 #define MAX(a, b) ((a) > (b) ? (a) : (b))
143 #define TIMESPEC_IS_SET(ts) ((ts)->tv_sec != 0 || (ts)->tv_nsec != 0)
145 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
146 const char *function, const char *format, ...);
148 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
149 const char *function, const char *format, va_list args);
151 #if !defined(_MSC_VER) || _MSC_VER >= 1400
153 #ifdef ENABLE_LOGGING
154 #define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __FUNCTION__, __VA_ARGS__)
155 #define usbi_dbg(...) _usbi_log(NULL, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
156 #else
157 #define _usbi_log(ctx, level, ...) do { (void)(ctx); } while(0)
158 #define usbi_dbg(...) do {} while(0)
159 #endif
161 #define usbi_info(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
162 #define usbi_warn(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
163 #define usbi_err(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
165 #else /* !defined(_MSC_VER) || _MSC_VER >= 1400 */
167 #ifdef ENABLE_LOGGING
168 #define LOG_BODY(ctxt, level) \
170 va_list args; \
171 va_start (args, format); \
172 usbi_log_v(ctxt, level, "", format, args); \
173 va_end(args); \
175 #else
176 #define LOG_BODY(ctxt, level) do { (void)(ctxt); } while(0)
177 #endif
179 static inline void usbi_info(struct libusb_context *ctx, const char *format,
180 ...)
181 LOG_BODY(ctx,LIBUSB_LOG_LEVEL_INFO)
182 static inline void usbi_warn(struct libusb_context *ctx, const char *format,
183 ...)
184 LOG_BODY(ctx,LIBUSB_LOG_LEVEL_WARNING)
185 static inline void usbi_err( struct libusb_context *ctx, const char *format,
186 ...)
187 LOG_BODY(ctx,LIBUSB_LOG_LEVEL_ERROR)
189 static inline void usbi_dbg(const char *format, ...)
190 LOG_BODY(NULL,LIBUSB_LOG_LEVEL_DEBUG)
192 #endif /* !defined(_MSC_VER) || _MSC_VER >= 1400 */
194 #define USBI_GET_CONTEXT(ctx) if (!(ctx)) (ctx) = usbi_default_context
195 #define DEVICE_CTX(dev) ((dev)->ctx)
196 #define HANDLE_CTX(handle) (DEVICE_CTX((handle)->dev))
197 #define TRANSFER_CTX(transfer) (HANDLE_CTX((transfer)->dev_handle))
198 #define ITRANSFER_CTX(transfer) \
199 (TRANSFER_CTX(USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)))
201 #define IS_EPIN(ep) (0 != ((ep) & LIBUSB_ENDPOINT_IN))
202 #define IS_EPOUT(ep) (!IS_EPIN(ep))
203 #define IS_XFERIN(xfer) (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
204 #define IS_XFEROUT(xfer) (!IS_XFERIN(xfer))
206 /* Internal abstraction for thread synchronization */
207 #if defined(THREADS_POSIX)
208 #include "os/threads_posix.h"
209 #elif defined(OS_WINDOWS) || defined(OS_WINCE)
210 #include <os/threads_windows.h>
211 #endif
213 extern struct libusb_context *usbi_default_context;
215 struct libusb_context {
216 int debug;
217 int debug_fixed;
219 /* internal control pipe, used for interrupting event handling when
220 * something needs to modify poll fds. */
221 int ctrl_pipe[2];
223 struct list_head usb_devs;
224 usbi_mutex_t usb_devs_lock;
226 /* A list of open handles. Backends are free to traverse this if required.
228 struct list_head open_devs;
229 usbi_mutex_t open_devs_lock;
231 /* A list of registered hotplug callbacks */
232 struct list_head hotplug_cbs;
233 usbi_mutex_t hotplug_cbs_lock;
234 int hotplug_pipe[2];
236 /* this is a list of in-flight transfer handles, sorted by timeout
237 * expiration. URBs to timeout the soonest are placed at the beginning of
238 * the list, URBs that will time out later are placed after, and urbs with
239 * infinite timeout are always placed at the very end. */
240 struct list_head flying_transfers;
241 usbi_mutex_t flying_transfers_lock;
243 /* list of poll fds */
244 struct list_head pollfds;
245 usbi_mutex_t pollfds_lock;
247 /* a counter that is set when we want to interrupt event handling, in order
248 * to modify the poll fd set. and a lock to protect it. */
249 unsigned int pollfd_modify;
250 usbi_mutex_t pollfd_modify_lock;
252 /* user callbacks for pollfd changes */
253 libusb_pollfd_added_cb fd_added_cb;
254 libusb_pollfd_removed_cb fd_removed_cb;
255 void *fd_cb_user_data;
257 /* ensures that only one thread is handling events at any one time */
258 usbi_mutex_t events_lock;
260 /* used to see if there is an active thread doing event handling */
261 int event_handler_active;
263 /* used to wait for event completion in threads other than the one that is
264 * event handling */
265 usbi_mutex_t event_waiters_lock;
266 usbi_cond_t event_waiters_cond;
268 #ifdef USBI_TIMERFD_AVAILABLE
269 /* used for timeout handling, if supported by OS.
270 * this timerfd is maintained to trigger on the next pending timeout */
271 int timerfd;
272 #endif
274 struct list_head list;
277 #ifdef USBI_TIMERFD_AVAILABLE
278 #define usbi_using_timerfd(ctx) ((ctx)->timerfd >= 0)
279 #else
280 #define usbi_using_timerfd(ctx) (0)
281 #endif
283 struct libusb_device {
284 /* lock protects refcnt, everything else is finalized at initialization
285 * time */
286 usbi_mutex_t lock;
287 int refcnt;
289 struct libusb_context *ctx;
291 uint8_t bus_number;
292 uint8_t port_number;
293 struct libusb_device* parent_dev;
294 uint8_t device_address;
295 uint8_t num_configurations;
296 enum libusb_speed speed;
298 struct list_head list;
299 unsigned long session_data;
301 struct libusb_device_descriptor device_descriptor;
302 int attached;
304 unsigned char os_priv
305 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
306 [] /* valid C99 code */
307 #else
308 [0] /* non-standard, but usually working code */
309 #endif
313 struct libusb_device_handle {
314 /* lock protects claimed_interfaces */
315 usbi_mutex_t lock;
316 unsigned long claimed_interfaces;
318 struct list_head list;
319 struct libusb_device *dev;
320 int auto_detach_kernel_driver;
321 unsigned char os_priv
322 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
323 [] /* valid C99 code */
324 #else
325 [0] /* non-standard, but usually working code */
326 #endif
330 enum {
331 USBI_CLOCK_MONOTONIC,
332 USBI_CLOCK_REALTIME
335 /* in-memory transfer layout:
337 * 1. struct usbi_transfer
338 * 2. struct libusb_transfer (which includes iso packets) [variable size]
339 * 3. os private data [variable size]
341 * from a libusb_transfer, you can get the usbi_transfer by rewinding the
342 * appropriate number of bytes.
343 * the usbi_transfer includes the number of allocated packets, so you can
344 * determine the size of the transfer and hence the start and length of the
345 * OS-private data.
348 struct usbi_transfer {
349 int num_iso_packets;
350 struct list_head list;
351 struct timeval timeout;
352 int transferred;
353 uint8_t flags;
355 /* this lock is held during libusb_submit_transfer() and
356 * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
357 * cancellation, submission-during-cancellation, etc). the OS backend
358 * should also take this lock in the handle_events path, to prevent the user
359 * cancelling the transfer from another thread while you are processing
360 * its completion (presumably there would be races within your OS backend
361 * if this were possible). */
362 usbi_mutex_t lock;
365 enum usbi_transfer_flags {
366 /* The transfer has timed out */
367 USBI_TRANSFER_TIMED_OUT = 1 << 0,
369 /* Set by backend submit_transfer() if the OS handles timeout */
370 USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1 << 1,
372 /* Cancellation was requested via libusb_cancel_transfer() */
373 USBI_TRANSFER_CANCELLING = 1 << 2,
375 /* Operation on the transfer failed because the device disappeared */
376 USBI_TRANSFER_DEVICE_DISAPPEARED = 1 << 3,
378 /* Set by backend submit_transfer() if the fds in use have been updated */
379 USBI_TRANSFER_UPDATED_FDS = 1 << 4,
382 #define USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer) \
383 ((struct libusb_transfer *)(((unsigned char *)(transfer)) \
384 + sizeof(struct usbi_transfer)))
385 #define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \
386 ((struct usbi_transfer *)(((unsigned char *)(transfer)) \
387 - sizeof(struct usbi_transfer)))
389 static inline void *usbi_transfer_get_os_priv(struct usbi_transfer *transfer)
391 return ((unsigned char *)transfer) + sizeof(struct usbi_transfer)
392 + sizeof(struct libusb_transfer)
393 + (transfer->num_iso_packets
394 * sizeof(struct libusb_iso_packet_descriptor));
397 /* bus structures */
399 /* All standard descriptors have these 2 fields in common */
400 struct usb_descriptor_header {
401 uint8_t bLength;
402 uint8_t bDescriptorType;
405 /* shared data and functions */
407 int usbi_io_init(struct libusb_context *ctx);
408 void usbi_io_exit(struct libusb_context *ctx);
410 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
411 unsigned long session_id);
412 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
413 unsigned long session_id);
414 int usbi_sanitize_device(struct libusb_device *dev);
415 void usbi_handle_disconnect(struct libusb_device_handle *handle);
417 int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
418 enum libusb_transfer_status status);
419 int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer);
421 int usbi_parse_descriptor(const unsigned char *source, const char *descriptor,
422 void *dest, int host_endian);
423 int usbi_device_cache_descriptor(libusb_device *dev);
424 int usbi_get_config_index_by_value(struct libusb_device *dev,
425 uint8_t bConfigurationValue, int *idx);
427 void usbi_connect_device (struct libusb_device *dev);
428 void usbi_disconnect_device (struct libusb_device *dev);
430 /* Internal abstraction for poll (needs struct usbi_transfer on Windows) */
431 #if defined(OS_LINUX) || defined(OS_DARWIN) || defined(OS_OPENBSD)
432 #include <unistd.h>
433 #include "os/poll_posix.h"
434 #elif defined(OS_WINDOWS) || defined(OS_WINCE)
435 #include <os/poll_windows.h>
436 #endif
438 #if (defined(OS_WINDOWS) || defined(OS_WINCE)) && !defined(__GCC__)
439 #undef HAVE_GETTIMEOFDAY
440 int usbi_gettimeofday(struct timeval *tp, void *tzp);
441 #define LIBUSB_GETTIMEOFDAY_WIN32
442 #define HAVE_USBI_GETTIMEOFDAY
443 #else
444 #ifdef HAVE_GETTIMEOFDAY
445 #define usbi_gettimeofday(tv, tz) gettimeofday((tv), (tz))
446 #define HAVE_USBI_GETTIMEOFDAY
447 #endif
448 #endif
450 struct usbi_pollfd {
451 /* must come first */
452 struct libusb_pollfd pollfd;
454 struct list_head list;
457 int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events);
458 void usbi_remove_pollfd(struct libusb_context *ctx, int fd);
459 void usbi_fd_notification(struct libusb_context *ctx);
461 /* device discovery */
463 /* we traverse usbfs without knowing how many devices we are going to find.
464 * so we create this discovered_devs model which is similar to a linked-list
465 * which grows when required. it can be freed once discovery has completed,
466 * eliminating the need for a list node in the libusb_device structure
467 * itself. */
468 struct discovered_devs {
469 size_t len;
470 size_t capacity;
471 struct libusb_device *devices
472 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
473 [] /* valid C99 code */
474 #else
475 [0] /* non-standard, but usually working code */
476 #endif
480 struct discovered_devs *discovered_devs_append(
481 struct discovered_devs *discdevs, struct libusb_device *dev);
483 /* OS abstraction */
485 /* This is the interface that OS backends need to implement.
486 * All fields are mandatory, except ones explicitly noted as optional. */
487 struct usbi_os_backend {
488 /* A human-readable name for your backend, e.g. "Linux usbfs" */
489 const char *name;
491 /* Binary mask for backend specific capabilities */
492 uint32_t caps;
494 /* Perform initialization of your backend. You might use this function
495 * to determine specific capabilities of the system, allocate required
496 * data structures for later, etc.
498 * This function is called when a libusbx user initializes the library
499 * prior to use.
501 * Return 0 on success, or a LIBUSB_ERROR code on failure.
503 int (*init)(struct libusb_context *ctx);
505 /* Deinitialization. Optional. This function should destroy anything
506 * that was set up by init.
508 * This function is called when the user deinitializes the library.
510 void (*exit)(void);
512 /* Enumerate all the USB devices on the system, returning them in a list
513 * of discovered devices.
515 * Your implementation should enumerate all devices on the system,
516 * regardless of whether they have been seen before or not.
518 * When you have found a device, compute a session ID for it. The session
519 * ID should uniquely represent that particular device for that particular
520 * connection session since boot (i.e. if you disconnect and reconnect a
521 * device immediately after, it should be assigned a different session ID).
522 * If your OS cannot provide a unique session ID as described above,
523 * presenting a session ID of (bus_number << 8 | device_address) should
524 * be sufficient. Bus numbers and device addresses wrap and get reused,
525 * but that is an unlikely case.
527 * After computing a session ID for a device, call
528 * usbi_get_device_by_session_id(). This function checks if libusbx already
529 * knows about the device, and if so, it provides you with a libusb_device
530 * structure for it.
532 * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
533 * a new device structure for the device. Call usbi_alloc_device() to
534 * obtain a new libusb_device structure with reference count 1. Populate
535 * the bus_number and device_address attributes of the new device, and
536 * perform any other internal backend initialization you need to do. At
537 * this point, you should be ready to provide device descriptors and so
538 * on through the get_*_descriptor functions. Finally, call
539 * usbi_sanitize_device() to perform some final sanity checks on the
540 * device. Assuming all of the above succeeded, we can now continue.
541 * If any of the above failed, remember to unreference the device that
542 * was returned by usbi_alloc_device().
544 * At this stage we have a populated libusb_device structure (either one
545 * that was found earlier, or one that we have just allocated and
546 * populated). This can now be added to the discovered devices list
547 * using discovered_devs_append(). Note that discovered_devs_append()
548 * may reallocate the list, returning a new location for it, and also
549 * note that reallocation can fail. Your backend should handle these
550 * error conditions appropriately.
552 * This function should not generate any bus I/O and should not block.
553 * If I/O is required (e.g. reading the active configuration value), it is
554 * OK to ignore these suggestions :)
556 * This function is executed when the user wishes to retrieve a list
557 * of USB devices connected to the system.
559 * If the backend has hotplug support, this function is not used!
561 * Return 0 on success, or a LIBUSB_ERROR code on failure.
563 int (*get_device_list)(struct libusb_context *ctx,
564 struct discovered_devs **discdevs);
566 /* Apps which were written before hotplug support, may listen for
567 * hotplug events on their own and call libusb_get_device_list on
568 * device addition. In this case libusb_get_device_list will likely
569 * return a list without the new device in there, as the hotplug
570 * event thread will still be busy enumerating the device, which may
571 * take a while, or may not even have seen the event yet.
573 * To avoid this libusb_get_device_list will call this optional
574 * function for backends with hotplug support before copying
575 * ctx->usb_devs to the user. In this function the backend should
576 * ensure any pending hotplug events are fully processed before
577 * returning.
579 * Optional, should be implemented by backends with hotplug support.
581 void (*hotplug_poll)(void);
583 /* Open a device for I/O and other USB operations. The device handle
584 * is preallocated for you, you can retrieve the device in question
585 * through handle->dev.
587 * Your backend should allocate any internal resources required for I/O
588 * and other operations so that those operations can happen (hopefully)
589 * without hiccup. This is also a good place to inform libusbx that it
590 * should monitor certain file descriptors related to this device -
591 * see the usbi_add_pollfd() function.
593 * This function should not generate any bus I/O and should not block.
595 * This function is called when the user attempts to obtain a device
596 * handle for a device.
598 * Return:
599 * - 0 on success
600 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
601 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
602 * discovery
603 * - another LIBUSB_ERROR code on other failure
605 * Do not worry about freeing the handle on failed open, the upper layers
606 * do this for you.
608 int (*open)(struct libusb_device_handle *handle);
610 /* Close a device such that the handle cannot be used again. Your backend
611 * should destroy any resources that were allocated in the open path.
612 * This may also be a good place to call usbi_remove_pollfd() to inform
613 * libusbx of any file descriptors associated with this device that should
614 * no longer be monitored.
616 * This function is called when the user closes a device handle.
618 void (*close)(struct libusb_device_handle *handle);
620 /* Retrieve the device descriptor from a device.
622 * The descriptor should be retrieved from memory, NOT via bus I/O to the
623 * device. This means that you may have to cache it in a private structure
624 * during get_device_list enumeration. Alternatively, you may be able
625 * to retrieve it from a kernel interface (some Linux setups can do this)
626 * still without generating bus I/O.
628 * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into
629 * buffer, which is guaranteed to be big enough.
631 * This function is called when sanity-checking a device before adding
632 * it to the list of discovered devices, and also when the user requests
633 * to read the device descriptor.
635 * This function is expected to return the descriptor in bus-endian format
636 * (LE). If it returns the multi-byte values in host-endian format,
637 * set the host_endian output parameter to "1".
639 * Return 0 on success or a LIBUSB_ERROR code on failure.
641 int (*get_device_descriptor)(struct libusb_device *device,
642 unsigned char *buffer, int *host_endian);
644 /* Get the ACTIVE configuration descriptor for a device.
646 * The descriptor should be retrieved from memory, NOT via bus I/O to the
647 * device. This means that you may have to cache it in a private structure
648 * during get_device_list enumeration. You may also have to keep track
649 * of which configuration is active when the user changes it.
651 * This function is expected to write len bytes of data into buffer, which
652 * is guaranteed to be big enough. If you can only do a partial write,
653 * return an error code.
655 * This function is expected to return the descriptor in bus-endian format
656 * (LE). If it returns the multi-byte values in host-endian format,
657 * set the host_endian output parameter to "1".
659 * Return:
660 * - 0 on success
661 * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
662 * - another LIBUSB_ERROR code on other failure
664 int (*get_active_config_descriptor)(struct libusb_device *device,
665 unsigned char *buffer, size_t len, int *host_endian);
667 /* Get a specific configuration descriptor for a device.
669 * The descriptor should be retrieved from memory, NOT via bus I/O to the
670 * device. This means that you may have to cache it in a private structure
671 * during get_device_list enumeration.
673 * The requested descriptor is expressed as a zero-based index (i.e. 0
674 * indicates that we are requesting the first descriptor). The index does
675 * not (necessarily) equal the bConfigurationValue of the configuration
676 * being requested.
678 * This function is expected to write len bytes of data into buffer, which
679 * is guaranteed to be big enough. If you can only do a partial write,
680 * return an error code.
682 * This function is expected to return the descriptor in bus-endian format
683 * (LE). If it returns the multi-byte values in host-endian format,
684 * set the host_endian output parameter to "1".
686 * Return 0 on success or a LIBUSB_ERROR code on failure.
688 int (*get_config_descriptor)(struct libusb_device *device,
689 uint8_t config_index, unsigned char *buffer, size_t len,
690 int *host_endian);
692 /* Like get_config_descriptor but then by bConfigurationValue instead
693 * of by index.
695 * Optional, if not present the core will call get_config_descriptor
696 * for all configs until it finds the desired bConfigurationValue.
698 * Returns a pointer to the raw-descriptor in *buffer, this memory
699 * is valid as long as device is valid.
701 * Returns the length of the returned raw-descriptor on success,
702 * or a LIBUSB_ERROR code on failure.
704 int (*get_config_descriptor_by_value)(struct libusb_device *device,
705 uint8_t bConfigurationValue, unsigned char **buffer,
706 int *host_endian);
708 /* Get the bConfigurationValue for the active configuration for a device.
709 * Optional. This should only be implemented if you can retrieve it from
710 * cache (don't generate I/O).
712 * If you cannot retrieve this from cache, either do not implement this
713 * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
714 * libusbx to retrieve the information through a standard control transfer.
716 * This function must be non-blocking.
717 * Return:
718 * - 0 on success
719 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
720 * was opened
721 * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
722 * blocking
723 * - another LIBUSB_ERROR code on other failure.
725 int (*get_configuration)(struct libusb_device_handle *handle, int *config);
727 /* Set the active configuration for a device.
729 * A configuration value of -1 should put the device in unconfigured state.
731 * This function can block.
733 * Return:
734 * - 0 on success
735 * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
736 * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
737 * configuration cannot be changed)
738 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
739 * was opened
740 * - another LIBUSB_ERROR code on other failure.
742 int (*set_configuration)(struct libusb_device_handle *handle, int config);
744 /* Claim an interface. When claimed, the application can then perform
745 * I/O to an interface's endpoints.
747 * This function should not generate any bus I/O and should not block.
748 * Interface claiming is a logical operation that simply ensures that
749 * no other drivers/applications are using the interface, and after
750 * claiming, no other drivers/applicatiosn can use the interface because
751 * we now "own" it.
753 * Return:
754 * - 0 on success
755 * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
756 * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
757 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
758 * was opened
759 * - another LIBUSB_ERROR code on other failure
761 int (*claim_interface)(struct libusb_device_handle *handle, int interface_number);
763 /* Release a previously claimed interface.
765 * This function should also generate a SET_INTERFACE control request,
766 * resetting the alternate setting of that interface to 0. It's OK for
767 * this function to block as a result.
769 * You will only ever be asked to release an interface which was
770 * successfully claimed earlier.
772 * Return:
773 * - 0 on success
774 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
775 * was opened
776 * - another LIBUSB_ERROR code on other failure
778 int (*release_interface)(struct libusb_device_handle *handle, int interface_number);
780 /* Set the alternate setting for an interface.
782 * You will only ever be asked to set the alternate setting for an
783 * interface which was successfully claimed earlier.
785 * It's OK for this function to block.
787 * Return:
788 * - 0 on success
789 * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
790 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
791 * was opened
792 * - another LIBUSB_ERROR code on other failure
794 int (*set_interface_altsetting)(struct libusb_device_handle *handle,
795 int interface_number, int altsetting);
797 /* Clear a halt/stall condition on an endpoint.
799 * It's OK for this function to block.
801 * Return:
802 * - 0 on success
803 * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
804 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
805 * was opened
806 * - another LIBUSB_ERROR code on other failure
808 int (*clear_halt)(struct libusb_device_handle *handle,
809 unsigned char endpoint);
811 /* Perform a USB port reset to reinitialize a device.
813 * If possible, the handle should still be usable after the reset
814 * completes, assuming that the device descriptors did not change during
815 * reset and all previous interface state can be restored.
817 * If something changes, or you cannot easily locate/verify the resetted
818 * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
819 * to close the old handle and re-enumerate the device.
821 * Return:
822 * - 0 on success
823 * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
824 * has been disconnected since it was opened
825 * - another LIBUSB_ERROR code on other failure
827 int (*reset_device)(struct libusb_device_handle *handle);
829 /* Determine if a kernel driver is active on an interface. Optional.
831 * The presence of a kernel driver on an interface indicates that any
832 * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
834 * Return:
835 * - 0 if no driver is active
836 * - 1 if a driver is active
837 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
838 * was opened
839 * - another LIBUSB_ERROR code on other failure
841 int (*kernel_driver_active)(struct libusb_device_handle *handle,
842 int interface_number);
844 /* Detach a kernel driver from an interface. Optional.
846 * After detaching a kernel driver, the interface should be available
847 * for claim.
849 * Return:
850 * - 0 on success
851 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
852 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
853 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
854 * was opened
855 * - another LIBUSB_ERROR code on other failure
857 int (*detach_kernel_driver)(struct libusb_device_handle *handle,
858 int interface_number);
860 /* Attach a kernel driver to an interface. Optional.
862 * Reattach a kernel driver to the device.
864 * Return:
865 * - 0 on success
866 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
867 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
868 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
869 * was opened
870 * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
871 * preventing reattachment
872 * - another LIBUSB_ERROR code on other failure
874 int (*attach_kernel_driver)(struct libusb_device_handle *handle,
875 int interface_number);
877 /* Destroy a device. Optional.
879 * This function is called when the last reference to a device is
880 * destroyed. It should free any resources allocated in the get_device_list
881 * path.
883 void (*destroy_device)(struct libusb_device *dev);
885 /* Submit a transfer. Your implementation should take the transfer,
886 * morph it into whatever form your platform requires, and submit it
887 * asynchronously.
889 * This function must not block.
891 * This function gets called with the flying_transfers_lock locked!
893 * Return:
894 * - 0 on success
895 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
896 * - another LIBUSB_ERROR code on other failure
898 int (*submit_transfer)(struct usbi_transfer *itransfer);
900 /* Cancel a previously submitted transfer.
902 * This function must not block. The transfer cancellation must complete
903 * later, resulting in a call to usbi_handle_transfer_cancellation()
904 * from the context of handle_events.
906 int (*cancel_transfer)(struct usbi_transfer *itransfer);
908 /* Clear a transfer as if it has completed or cancelled, but do not
909 * report any completion/cancellation to the library. You should free
910 * all private data from the transfer as if you were just about to report
911 * completion or cancellation.
913 * This function might seem a bit out of place. It is used when libusbx
914 * detects a disconnected device - it calls this function for all pending
915 * transfers before reporting completion (with the disconnect code) to
916 * the user. Maybe we can improve upon this internal interface in future.
918 void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
920 /* Handle any pending events. This involves monitoring any active
921 * transfers and processing their completion or cancellation.
923 * The function is passed an array of pollfd structures (size nfds)
924 * as a result of the poll() system call. The num_ready parameter
925 * indicates the number of file descriptors that have reported events
926 * (i.e. the poll() return value). This should be enough information
927 * for you to determine which actions need to be taken on the currently
928 * active transfers.
930 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
931 * For completed transfers, call usbi_handle_transfer_completion().
932 * For control/bulk/interrupt transfers, populate the "transferred"
933 * element of the appropriate usbi_transfer structure before calling the
934 * above functions. For isochronous transfers, populate the status and
935 * transferred fields of the iso packet descriptors of the transfer.
937 * This function should also be able to detect disconnection of the
938 * device, reporting that situation with usbi_handle_disconnect().
940 * When processing an event related to a transfer, you probably want to
941 * take usbi_transfer.lock to prevent races. See the documentation for
942 * the usbi_transfer structure.
944 * Return 0 on success, or a LIBUSB_ERROR code on failure.
946 int (*handle_events)(struct libusb_context *ctx,
947 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready);
949 /* Get time from specified clock. At least two clocks must be implemented
950 by the backend: USBI_CLOCK_REALTIME, and USBI_CLOCK_MONOTONIC.
952 Description of clocks:
953 USBI_CLOCK_REALTIME : clock returns time since system epoch.
954 USBI_CLOCK_MONOTONIC: clock returns time since unspecified start
955 time (usually boot).
957 int (*clock_gettime)(int clkid, struct timespec *tp);
959 #ifdef USBI_TIMERFD_AVAILABLE
960 /* clock ID of the clock that should be used for timerfd */
961 clockid_t (*get_timerfd_clockid)(void);
962 #endif
964 /* Number of bytes to reserve for per-device private backend data.
965 * This private data area is accessible through the "os_priv" field of
966 * struct libusb_device. */
967 size_t device_priv_size;
969 /* Number of bytes to reserve for per-handle private backend data.
970 * This private data area is accessible through the "os_priv" field of
971 * struct libusb_device. */
972 size_t device_handle_priv_size;
974 /* Number of bytes to reserve for per-transfer private backend data.
975 * This private data area is accessible by calling
976 * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance.
978 size_t transfer_priv_size;
980 /* Mumber of additional bytes for os_priv for each iso packet.
981 * Can your backend use this? */
982 /* FIXME: linux can't use this any more. if other OS's cannot either,
983 * then remove this */
984 size_t add_iso_packet_size;
987 extern const struct usbi_os_backend * const usbi_backend;
989 extern const struct usbi_os_backend linux_usbfs_backend;
990 extern const struct usbi_os_backend darwin_backend;
991 extern const struct usbi_os_backend openbsd_backend;
992 extern const struct usbi_os_backend windows_backend;
993 extern const struct usbi_os_backend wince_backend;
995 extern struct list_head active_contexts_list;
996 extern usbi_mutex_static_t active_contexts_lock;
998 #endif