Add libusb and libuvc
[rtmpclient.git] / app / src / main / jni / libusb-1.0.22 / libusb / libusbi.h
1 /*
2  * Internal header for libusb
3  * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
4  * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #ifndef LIBUSBI_H
22 #define LIBUSBI_H
23
24 #include <config.h>
25
26 #include <stdlib.h>
27
28 #include <stddef.h>
29 #include <stdint.h>
30 #include <time.h>
31 #include <stdarg.h>
32 #ifdef HAVE_POLL_H
33 #include <poll.h>
34 #endif
35 #ifdef HAVE_MISSING_H
36 #include <missing.h>
37 #endif
38
39 #include "libusb.h"
40 #include "version.h"
41
42 /* Attribute to ensure that a structure member is aligned to a natural
43  * pointer alignment. Used for os_priv member. */
44 #if defined(_MSC_VER)
45 #if defined(_WIN64)
46 #define PTR_ALIGNED __declspec(align(8))
47 #else
48 #define PTR_ALIGNED __declspec(align(4))
49 #endif
50 #elif defined(__GNUC__)
51 #define PTR_ALIGNED __attribute__((aligned(sizeof(void *))))
52 #else
53 #define PTR_ALIGNED
54 #endif
55
56 /* Inside the libusb code, mark all public functions as follows:
57  *   return_type API_EXPORTED function_name(params) { ... }
58  * But if the function returns a pointer, mark it as follows:
59  *   DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
60  * In the libusb public header, mark all declarations as:
61  *   return_type LIBUSB_CALL function_name(params);
62  */
63 #define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
64
65 #ifdef __cplusplus
66 extern "C" {
67 #endif
68
69 #define DEVICE_DESC_LENGTH      18
70
71 #define USB_MAXENDPOINTS        32
72 #define USB_MAXINTERFACES       32
73 #define USB_MAXCONFIG           8
74
75 /* Backend specific capabilities */
76 #define USBI_CAP_HAS_HID_ACCESS                 0x00010000
77 #define USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER  0x00020000
78
79 /* Maximum number of bytes in a log line */
80 #define USBI_MAX_LOG_LEN        1024
81 /* Terminator for log lines */
82 #define USBI_LOG_LINE_END       "\n"
83
84 /* The following is used to silence warnings for unused variables */
85 #define UNUSED(var)             do { (void)(var); } while(0)
86
87 #if !defined(ARRAYSIZE)
88 #define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))
89 #endif
90
91 struct list_head {
92         struct list_head *prev, *next;
93 };
94
95 /* Get an entry from the list
96  *  ptr - the address of this list_head element in "type"
97  *  type - the data type that contains "member"
98  *  member - the list_head element in "type"
99  */
100 #define list_entry(ptr, type, member) \
101         ((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
102
103 #define list_first_entry(ptr, type, member) \
104         list_entry((ptr)->next, type, member)
105
106 /* Get each entry from a list
107  *  pos - A structure pointer has a "member" element
108  *  head - list head
109  *  member - the list_head element in "pos"
110  *  type - the type of the first parameter
111  */
112 #define list_for_each_entry(pos, head, member, type)                    \
113         for (pos = list_entry((head)->next, type, member);              \
114                  &pos->member != (head);                                \
115                  pos = list_entry(pos->member.next, type, member))
116
117 #define list_for_each_entry_safe(pos, n, head, member, type)            \
118         for (pos = list_entry((head)->next, type, member),              \
119                  n = list_entry(pos->member.next, type, member);        \
120                  &pos->member != (head);                                \
121                  pos = n, n = list_entry(n->member.next, type, member))
122
123 #define list_empty(entry) ((entry)->next == (entry))
124
125 static inline void list_init(struct list_head *entry)
126 {
127         entry->prev = entry->next = entry;
128 }
129
130 static inline void list_add(struct list_head *entry, struct list_head *head)
131 {
132         entry->next = head->next;
133         entry->prev = head;
134
135         head->next->prev = entry;
136         head->next = entry;
137 }
138
139 static inline void list_add_tail(struct list_head *entry,
140         struct list_head *head)
141 {
142         entry->next = head;
143         entry->prev = head->prev;
144
145         head->prev->next = entry;
146         head->prev = entry;
147 }
148
149 static inline void list_del(struct list_head *entry)
150 {
151         entry->next->prev = entry->prev;
152         entry->prev->next = entry->next;
153         entry->next = entry->prev = NULL;
154 }
155
156 static inline void list_cut(struct list_head *list, struct list_head *head)
157 {
158         if (list_empty(head))
159                 return;
160
161         list->next = head->next;
162         list->next->prev = list;
163         list->prev = head->prev;
164         list->prev->next = list;
165
166         list_init(head);
167 }
168
169 static inline void *usbi_reallocf(void *ptr, size_t size)
170 {
171         void *ret = realloc(ptr, size);
172         if (!ret)
173                 free(ptr);
174         return ret;
175 }
176
177 #define container_of(ptr, type, member) ({                      \
178         const typeof( ((type *)0)->member ) *mptr = (ptr);      \
179         (type *)( (char *)mptr - offsetof(type,member) );})
180
181 #ifndef CLAMP
182 #define CLAMP(val, min, max) ((val) < (min) ? (min) : ((val) > (max) ? (max) : (val)))
183 #endif
184 #ifndef MIN
185 #define MIN(a, b)       ((a) < (b) ? (a) : (b))
186 #endif
187 #ifndef MAX
188 #define MAX(a, b)       ((a) > (b) ? (a) : (b))
189 #endif
190
191 #define TIMESPEC_IS_SET(ts) ((ts)->tv_sec != 0 || (ts)->tv_nsec != 0)
192
193 #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
194 #define TIMEVAL_TV_SEC_TYPE     long
195 #else
196 #define TIMEVAL_TV_SEC_TYPE     time_t
197 #endif
198
199 /* Some platforms don't have this define */
200 #ifndef TIMESPEC_TO_TIMEVAL
201 #define TIMESPEC_TO_TIMEVAL(tv, ts)                                     \
202         do {                                                            \
203                 (tv)->tv_sec = (TIMEVAL_TV_SEC_TYPE) (ts)->tv_sec;      \
204                 (tv)->tv_usec = (ts)->tv_nsec / 1000;                   \
205         } while (0)
206 #endif
207
208 #ifdef ENABLE_LOGGING
209
210 #if defined(_MSC_VER) && (_MSC_VER < 1900)
211 #define snprintf usbi_snprintf
212 #define vsnprintf usbi_vsnprintf
213 int usbi_snprintf(char *dst, size_t size, const char *format, ...);
214 int usbi_vsnprintf(char *dst, size_t size, const char *format, va_list ap);
215 #define LIBUSB_PRINTF_WIN32
216 #endif /* defined(_MSC_VER) && (_MSC_VER < 1900) */
217
218 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
219         const char *function, const char *format, ...);
220
221 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
222         const char *function, const char *format, va_list args);
223
224 #if !defined(_MSC_VER) || (_MSC_VER >= 1400)
225
226 #define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __FUNCTION__, __VA_ARGS__)
227
228 #define usbi_err(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
229 #define usbi_warn(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
230 #define usbi_info(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
231 #define usbi_dbg(...) _usbi_log(NULL, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
232
233 #else /* !defined(_MSC_VER) || (_MSC_VER >= 1400) */
234
235 #define LOG_BODY(ctxt, level)                           \
236 {                                                       \
237         va_list args;                                   \
238         va_start(args, format);                         \
239         usbi_log_v(ctxt, level, "", format, args);      \
240         va_end(args);                                   \
241 }
242
243 static inline void usbi_err(struct libusb_context *ctx, const char *format, ...)
244         LOG_BODY(ctx, LIBUSB_LOG_LEVEL_ERROR)
245 static inline void usbi_warn(struct libusb_context *ctx, const char *format, ...)
246         LOG_BODY(ctx, LIBUSB_LOG_LEVEL_WARNING)
247 static inline void usbi_info(struct libusb_context *ctx, const char *format, ...)
248         LOG_BODY(ctx, LIBUSB_LOG_LEVEL_INFO)
249 static inline void usbi_dbg(const char *format, ...)
250         LOG_BODY(NULL, LIBUSB_LOG_LEVEL_DEBUG)
251
252 #endif /* !defined(_MSC_VER) || (_MSC_VER >= 1400) */
253
254 #else /* ENABLE_LOGGING */
255
256 #define usbi_err(ctx, ...) do { (void)ctx; } while (0)
257 #define usbi_warn(ctx, ...) do { (void)ctx; } while (0)
258 #define usbi_info(ctx, ...) do { (void)ctx; } while (0)
259 #define usbi_dbg(...) do {} while (0)
260
261 #endif /* ENABLE_LOGGING */
262
263 #define USBI_GET_CONTEXT(ctx)                           \
264         do {                                            \
265                 if (!(ctx))                             \
266                         (ctx) = usbi_default_context;   \
267         } while(0)
268
269 #define DEVICE_CTX(dev)         ((dev)->ctx)
270 #define HANDLE_CTX(handle)      (DEVICE_CTX((handle)->dev))
271 #define TRANSFER_CTX(transfer)  (HANDLE_CTX((transfer)->dev_handle))
272 #define ITRANSFER_CTX(transfer) \
273         (TRANSFER_CTX(USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)))
274
275 #define IS_EPIN(ep)             (0 != ((ep) & LIBUSB_ENDPOINT_IN))
276 #define IS_EPOUT(ep)            (!IS_EPIN(ep))
277 #define IS_XFERIN(xfer)         (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
278 #define IS_XFEROUT(xfer)        (!IS_XFERIN(xfer))
279
280 /* Internal abstraction for thread synchronization */
281 #if defined(THREADS_POSIX)
282 #include "os/threads_posix.h"
283 #elif defined(OS_WINDOWS) || defined(OS_WINCE)
284 #include "os/threads_windows.h"
285 #endif
286
287 extern struct libusb_context *usbi_default_context;
288
289 /* Forward declaration for use in context (fully defined inside poll abstraction) */
290 struct pollfd;
291
292 struct libusb_context {
293 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
294         enum libusb_log_level debug;
295         int debug_fixed;
296 #endif
297
298         /* internal event pipe, used for signalling occurrence of an internal event. */
299         int event_pipe[2];
300
301         struct list_head usb_devs;
302         usbi_mutex_t usb_devs_lock;
303
304         /* A list of open handles. Backends are free to traverse this if required.
305          */
306         struct list_head open_devs;
307         usbi_mutex_t open_devs_lock;
308
309         /* A list of registered hotplug callbacks */
310         struct list_head hotplug_cbs;
311         libusb_hotplug_callback_handle next_hotplug_cb_handle;
312         usbi_mutex_t hotplug_cbs_lock;
313
314         /* this is a list of in-flight transfer handles, sorted by timeout
315          * expiration. URBs to timeout the soonest are placed at the beginning of
316          * the list, URBs that will time out later are placed after, and urbs with
317          * infinite timeout are always placed at the very end. */
318         struct list_head flying_transfers;
319         /* Note paths taking both this and usbi_transfer->lock must always
320          * take this lock first */
321         usbi_mutex_t flying_transfers_lock;
322
323         /* user callbacks for pollfd changes */
324         libusb_pollfd_added_cb fd_added_cb;
325         libusb_pollfd_removed_cb fd_removed_cb;
326         void *fd_cb_user_data;
327
328         /* ensures that only one thread is handling events at any one time */
329         usbi_mutex_t events_lock;
330
331         /* used to see if there is an active thread doing event handling */
332         int event_handler_active;
333
334         /* A thread-local storage key to track which thread is performing event
335          * handling */
336         usbi_tls_key_t event_handling_key;
337
338         /* used to wait for event completion in threads other than the one that is
339          * event handling */
340         usbi_mutex_t event_waiters_lock;
341         usbi_cond_t event_waiters_cond;
342
343         /* A lock to protect internal context event data. */
344         usbi_mutex_t event_data_lock;
345
346         /* A bitmask of flags that are set to indicate specific events that need to
347          * be handled. Protected by event_data_lock. */
348         unsigned int event_flags;
349
350         /* A counter that is set when we want to interrupt and prevent event handling,
351          * in order to safely close a device. Protected by event_data_lock. */
352         unsigned int device_close;
353
354         /* list and count of poll fds and an array of poll fd structures that is
355          * (re)allocated as necessary prior to polling. Protected by event_data_lock. */
356         struct list_head ipollfds;
357         struct pollfd *pollfds;
358         POLL_NFDS_TYPE pollfds_cnt;
359
360         /* A list of pending hotplug messages. Protected by event_data_lock. */
361         struct list_head hotplug_msgs;
362
363         /* A list of pending completed transfers. Protected by event_data_lock. */
364         struct list_head completed_transfers;
365
366 #ifdef USBI_TIMERFD_AVAILABLE
367         /* used for timeout handling, if supported by OS.
368          * this timerfd is maintained to trigger on the next pending timeout */
369         int timerfd;
370 #endif
371
372         struct list_head list;
373
374         PTR_ALIGNED unsigned char os_priv[ZERO_SIZED_ARRAY];
375 };
376
377 enum usbi_event_flags {
378         /* The list of pollfds has been modified */
379         USBI_EVENT_POLLFDS_MODIFIED = 1 << 0,
380
381         /* The user has interrupted the event handler */
382         USBI_EVENT_USER_INTERRUPT = 1 << 1,
383
384         /* A hotplug callback deregistration is pending */
385         USBI_EVENT_HOTPLUG_CB_DEREGISTERED = 1 << 2,
386 };
387
388 /* Macros for managing event handling state */
389 #define usbi_handling_events(ctx) \
390         (usbi_tls_key_get((ctx)->event_handling_key) != NULL)
391
392 #define usbi_start_event_handling(ctx) \
393         usbi_tls_key_set((ctx)->event_handling_key, ctx)
394
395 #define usbi_end_event_handling(ctx) \
396         usbi_tls_key_set((ctx)->event_handling_key, NULL)
397
398 /* Update the following macro if new event sources are added */
399 #define usbi_pending_events(ctx) \
400         ((ctx)->event_flags || (ctx)->device_close \
401          || !list_empty(&(ctx)->hotplug_msgs) || !list_empty(&(ctx)->completed_transfers))
402
403 #ifdef USBI_TIMERFD_AVAILABLE
404 #define usbi_using_timerfd(ctx) ((ctx)->timerfd >= 0)
405 #else
406 #define usbi_using_timerfd(ctx) (0)
407 #endif
408
409 struct libusb_device {
410         /* lock protects refcnt, everything else is finalized at initialization
411          * time */
412         usbi_mutex_t lock;
413         int refcnt;
414
415         struct libusb_context *ctx;
416
417         uint8_t bus_number;
418         uint8_t port_number;
419         struct libusb_device* parent_dev;
420         uint8_t device_address;
421         uint8_t num_configurations;
422         enum libusb_speed speed;
423
424         struct list_head list;
425         unsigned long session_data;
426
427         struct libusb_device_descriptor device_descriptor;
428         int attached;
429
430         PTR_ALIGNED unsigned char os_priv[ZERO_SIZED_ARRAY];
431 };
432
433 struct libusb_device_handle {
434         /* lock protects claimed_interfaces */
435         usbi_mutex_t lock;
436         unsigned long claimed_interfaces;
437
438         struct list_head list;
439         struct libusb_device *dev;
440         int auto_detach_kernel_driver;
441
442         PTR_ALIGNED unsigned char os_priv[ZERO_SIZED_ARRAY];
443 };
444
445 enum {
446         USBI_CLOCK_MONOTONIC,
447         USBI_CLOCK_REALTIME
448 };
449
450 /* in-memory transfer layout:
451  *
452  * 1. struct usbi_transfer
453  * 2. struct libusb_transfer (which includes iso packets) [variable size]
454  * 3. os private data [variable size]
455  *
456  * from a libusb_transfer, you can get the usbi_transfer by rewinding the
457  * appropriate number of bytes.
458  * the usbi_transfer includes the number of allocated packets, so you can
459  * determine the size of the transfer and hence the start and length of the
460  * OS-private data.
461  */
462
463 struct usbi_transfer {
464         int num_iso_packets;
465         struct list_head list;
466         struct list_head completed_list;
467         struct timeval timeout;
468         int transferred;
469         uint32_t stream_id;
470         uint8_t state_flags;   /* Protected by usbi_transfer->lock */
471         uint8_t timeout_flags; /* Protected by the flying_stransfers_lock */
472
473         /* this lock is held during libusb_submit_transfer() and
474          * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
475          * cancellation, submission-during-cancellation, etc). the OS backend
476          * should also take this lock in the handle_events path, to prevent the user
477          * cancelling the transfer from another thread while you are processing
478          * its completion (presumably there would be races within your OS backend
479          * if this were possible).
480          * Note paths taking both this and the flying_transfers_lock must
481          * always take the flying_transfers_lock first */
482         usbi_mutex_t lock;
483 };
484
485 enum usbi_transfer_state_flags {
486         /* Transfer successfully submitted by backend */
487         USBI_TRANSFER_IN_FLIGHT = 1 << 0,
488
489         /* Cancellation was requested via libusb_cancel_transfer() */
490         USBI_TRANSFER_CANCELLING = 1 << 1,
491
492         /* Operation on the transfer failed because the device disappeared */
493         USBI_TRANSFER_DEVICE_DISAPPEARED = 1 << 2,
494 };
495
496 enum usbi_transfer_timeout_flags {
497         /* Set by backend submit_transfer() if the OS handles timeout */
498         USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1 << 0,
499
500         /* The transfer timeout has been handled */
501         USBI_TRANSFER_TIMEOUT_HANDLED = 1 << 1,
502
503         /* The transfer timeout was successfully processed */
504         USBI_TRANSFER_TIMED_OUT = 1 << 2,
505 };
506
507 #define USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)                      \
508         ((struct libusb_transfer *)(((unsigned char *)(transfer))       \
509                 + sizeof(struct usbi_transfer)))
510 #define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)                      \
511         ((struct usbi_transfer *)(((unsigned char *)(transfer))         \
512                 - sizeof(struct usbi_transfer)))
513
514 static inline void *usbi_transfer_get_os_priv(struct usbi_transfer *transfer)
515 {
516         return ((unsigned char *)transfer) + sizeof(struct usbi_transfer)
517                 + sizeof(struct libusb_transfer)
518                 + (transfer->num_iso_packets
519                         * sizeof(struct libusb_iso_packet_descriptor));
520 }
521
522 /* bus structures */
523
524 /* All standard descriptors have these 2 fields in common */
525 struct usb_descriptor_header {
526         uint8_t bLength;
527         uint8_t bDescriptorType;
528 };
529
530 /* shared data and functions */
531
532 int usbi_io_init(struct libusb_context *ctx);
533 void usbi_io_exit(struct libusb_context *ctx);
534
535 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
536         unsigned long session_id);
537 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
538         unsigned long session_id);
539 int usbi_sanitize_device(struct libusb_device *dev);
540 void usbi_handle_disconnect(struct libusb_device_handle *dev_handle);
541
542 int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
543         enum libusb_transfer_status status);
544 int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer);
545 void usbi_signal_transfer_completion(struct usbi_transfer *transfer);
546
547 int usbi_parse_descriptor(const unsigned char *source, const char *descriptor,
548         void *dest, int host_endian);
549 int usbi_device_cache_descriptor(libusb_device *dev);
550 int usbi_get_config_index_by_value(struct libusb_device *dev,
551         uint8_t bConfigurationValue, int *idx);
552
553 void usbi_connect_device (struct libusb_device *dev);
554 void usbi_disconnect_device (struct libusb_device *dev);
555
556 int usbi_signal_event(struct libusb_context *ctx);
557 int usbi_clear_event(struct libusb_context *ctx);
558
559 /* Internal abstraction for poll (needs struct usbi_transfer on Windows) */
560 #if defined(OS_LINUX) || defined(OS_DARWIN) || defined(OS_OPENBSD) || defined(OS_NETBSD) ||\
561         defined(OS_HAIKU) || defined(OS_SUNOS)
562 #include <unistd.h>
563 #include "os/poll_posix.h"
564 #elif defined(OS_WINDOWS) || defined(OS_WINCE)
565 #include "os/poll_windows.h"
566 #endif
567
568 struct usbi_pollfd {
569         /* must come first */
570         struct libusb_pollfd pollfd;
571
572         struct list_head list;
573 };
574
575 int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events);
576 void usbi_remove_pollfd(struct libusb_context *ctx, int fd);
577
578 /* device discovery */
579
580 /* we traverse usbfs without knowing how many devices we are going to find.
581  * so we create this discovered_devs model which is similar to a linked-list
582  * which grows when required. it can be freed once discovery has completed,
583  * eliminating the need for a list node in the libusb_device structure
584  * itself. */
585 struct discovered_devs {
586         size_t len;
587         size_t capacity;
588         struct libusb_device *devices[ZERO_SIZED_ARRAY];
589 };
590
591 struct discovered_devs *discovered_devs_append(
592         struct discovered_devs *discdevs, struct libusb_device *dev);
593
594 /* OS abstraction */
595
596 /* This is the interface that OS backends need to implement.
597  * All fields are mandatory, except ones explicitly noted as optional. */
598 struct usbi_os_backend {
599         /* A human-readable name for your backend, e.g. "Linux usbfs" */
600         const char *name;
601
602         /* Binary mask for backend specific capabilities */
603         uint32_t caps;
604
605         /* Perform initialization of your backend. You might use this function
606          * to determine specific capabilities of the system, allocate required
607          * data structures for later, etc.
608          *
609          * This function is called when a libusb user initializes the library
610          * prior to use.
611          *
612          * Return 0 on success, or a LIBUSB_ERROR code on failure.
613          */
614         int (*init)(struct libusb_context *ctx);
615
616         /* Deinitialization. Optional. This function should destroy anything
617          * that was set up by init.
618          *
619          * This function is called when the user deinitializes the library.
620          */
621         void (*exit)(struct libusb_context *ctx);
622
623         /* Set a backend-specific option. Optional.
624          *
625          * This function is called when the user calls libusb_set_option() and
626          * the option is not handled by the core library.
627          *
628          * Return 0 on success, or a LIBUSB_ERROR code on failure.
629          */
630         int (*set_option)(struct libusb_context *ctx, enum libusb_option option,
631                 va_list args);
632
633         /* Enumerate all the USB devices on the system, returning them in a list
634          * of discovered devices.
635          *
636          * Your implementation should enumerate all devices on the system,
637          * regardless of whether they have been seen before or not.
638          *
639          * When you have found a device, compute a session ID for it. The session
640          * ID should uniquely represent that particular device for that particular
641          * connection session since boot (i.e. if you disconnect and reconnect a
642          * device immediately after, it should be assigned a different session ID).
643          * If your OS cannot provide a unique session ID as described above,
644          * presenting a session ID of (bus_number << 8 | device_address) should
645          * be sufficient. Bus numbers and device addresses wrap and get reused,
646          * but that is an unlikely case.
647          *
648          * After computing a session ID for a device, call
649          * usbi_get_device_by_session_id(). This function checks if libusb already
650          * knows about the device, and if so, it provides you with a reference
651          * to a libusb_device structure for it.
652          *
653          * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
654          * a new device structure for the device. Call usbi_alloc_device() to
655          * obtain a new libusb_device structure with reference count 1. Populate
656          * the bus_number and device_address attributes of the new device, and
657          * perform any other internal backend initialization you need to do. At
658          * this point, you should be ready to provide device descriptors and so
659          * on through the get_*_descriptor functions. Finally, call
660          * usbi_sanitize_device() to perform some final sanity checks on the
661          * device. Assuming all of the above succeeded, we can now continue.
662          * If any of the above failed, remember to unreference the device that
663          * was returned by usbi_alloc_device().
664          *
665          * At this stage we have a populated libusb_device structure (either one
666          * that was found earlier, or one that we have just allocated and
667          * populated). This can now be added to the discovered devices list
668          * using discovered_devs_append(). Note that discovered_devs_append()
669          * may reallocate the list, returning a new location for it, and also
670          * note that reallocation can fail. Your backend should handle these
671          * error conditions appropriately.
672          *
673          * This function should not generate any bus I/O and should not block.
674          * If I/O is required (e.g. reading the active configuration value), it is
675          * OK to ignore these suggestions :)
676          *
677          * This function is executed when the user wishes to retrieve a list
678          * of USB devices connected to the system.
679          *
680          * If the backend has hotplug support, this function is not used!
681          *
682          * Return 0 on success, or a LIBUSB_ERROR code on failure.
683          */
684         int (*get_device_list)(struct libusb_context *ctx,
685                 struct discovered_devs **discdevs);
686
687         /* Apps which were written before hotplug support, may listen for
688          * hotplug events on their own and call libusb_get_device_list on
689          * device addition. In this case libusb_get_device_list will likely
690          * return a list without the new device in there, as the hotplug
691          * event thread will still be busy enumerating the device, which may
692          * take a while, or may not even have seen the event yet.
693          *
694          * To avoid this libusb_get_device_list will call this optional
695          * function for backends with hotplug support before copying
696          * ctx->usb_devs to the user. In this function the backend should
697          * ensure any pending hotplug events are fully processed before
698          * returning.
699          *
700          * Optional, should be implemented by backends with hotplug support.
701          */
702         void (*hotplug_poll)(void);
703
704         /* Open a device for I/O and other USB operations. The device handle
705          * is preallocated for you, you can retrieve the device in question
706          * through handle->dev.
707          *
708          * Your backend should allocate any internal resources required for I/O
709          * and other operations so that those operations can happen (hopefully)
710          * without hiccup. This is also a good place to inform libusb that it
711          * should monitor certain file descriptors related to this device -
712          * see the usbi_add_pollfd() function.
713          *
714          * This function should not generate any bus I/O and should not block.
715          *
716          * This function is called when the user attempts to obtain a device
717          * handle for a device.
718          *
719          * Return:
720          * - 0 on success
721          * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
722          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
723          *   discovery
724          * - another LIBUSB_ERROR code on other failure
725          *
726          * Do not worry about freeing the handle on failed open, the upper layers
727          * do this for you.
728          */
729         int (*open)(struct libusb_device_handle *dev_handle);
730
731         /* Close a device such that the handle cannot be used again. Your backend
732          * should destroy any resources that were allocated in the open path.
733          * This may also be a good place to call usbi_remove_pollfd() to inform
734          * libusb of any file descriptors associated with this device that should
735          * no longer be monitored.
736          *
737          * This function is called when the user closes a device handle.
738          */
739         void (*close)(struct libusb_device_handle *dev_handle);
740
741         /* Retrieve the device descriptor from a device.
742          *
743          * The descriptor should be retrieved from memory, NOT via bus I/O to the
744          * device. This means that you may have to cache it in a private structure
745          * during get_device_list enumeration. Alternatively, you may be able
746          * to retrieve it from a kernel interface (some Linux setups can do this)
747          * still without generating bus I/O.
748          *
749          * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into
750          * buffer, which is guaranteed to be big enough.
751          *
752          * This function is called when sanity-checking a device before adding
753          * it to the list of discovered devices, and also when the user requests
754          * to read the device descriptor.
755          *
756          * This function is expected to return the descriptor in bus-endian format
757          * (LE). If it returns the multi-byte values in host-endian format,
758          * set the host_endian output parameter to "1".
759          *
760          * Return 0 on success or a LIBUSB_ERROR code on failure.
761          */
762         int (*get_device_descriptor)(struct libusb_device *device,
763                 unsigned char *buffer, int *host_endian);
764
765         /* Get the ACTIVE configuration descriptor for a device.
766          *
767          * The descriptor should be retrieved from memory, NOT via bus I/O to the
768          * device. This means that you may have to cache it in a private structure
769          * during get_device_list enumeration. You may also have to keep track
770          * of which configuration is active when the user changes it.
771          *
772          * This function is expected to write len bytes of data into buffer, which
773          * is guaranteed to be big enough. If you can only do a partial write,
774          * return an error code.
775          *
776          * This function is expected to return the descriptor in bus-endian format
777          * (LE). If it returns the multi-byte values in host-endian format,
778          * set the host_endian output parameter to "1".
779          *
780          * Return:
781          * - 0 on success
782          * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
783          * - another LIBUSB_ERROR code on other failure
784          */
785         int (*get_active_config_descriptor)(struct libusb_device *device,
786                 unsigned char *buffer, size_t len, int *host_endian);
787
788         /* Get a specific configuration descriptor for a device.
789          *
790          * The descriptor should be retrieved from memory, NOT via bus I/O to the
791          * device. This means that you may have to cache it in a private structure
792          * during get_device_list enumeration.
793          *
794          * The requested descriptor is expressed as a zero-based index (i.e. 0
795          * indicates that we are requesting the first descriptor). The index does
796          * not (necessarily) equal the bConfigurationValue of the configuration
797          * being requested.
798          *
799          * This function is expected to write len bytes of data into buffer, which
800          * is guaranteed to be big enough. If you can only do a partial write,
801          * return an error code.
802          *
803          * This function is expected to return the descriptor in bus-endian format
804          * (LE). If it returns the multi-byte values in host-endian format,
805          * set the host_endian output parameter to "1".
806          *
807          * Return the length read on success or a LIBUSB_ERROR code on failure.
808          */
809         int (*get_config_descriptor)(struct libusb_device *device,
810                 uint8_t config_index, unsigned char *buffer, size_t len,
811                 int *host_endian);
812
813         /* Like get_config_descriptor but then by bConfigurationValue instead
814          * of by index.
815          *
816          * Optional, if not present the core will call get_config_descriptor
817          * for all configs until it finds the desired bConfigurationValue.
818          *
819          * Returns a pointer to the raw-descriptor in *buffer, this memory
820          * is valid as long as device is valid.
821          *
822          * Returns the length of the returned raw-descriptor on success,
823          * or a LIBUSB_ERROR code on failure.
824          */
825         int (*get_config_descriptor_by_value)(struct libusb_device *device,
826                 uint8_t bConfigurationValue, unsigned char **buffer,
827                 int *host_endian);
828
829         /* Get the bConfigurationValue for the active configuration for a device.
830          * Optional. This should only be implemented if you can retrieve it from
831          * cache (don't generate I/O).
832          *
833          * If you cannot retrieve this from cache, either do not implement this
834          * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
835          * libusb to retrieve the information through a standard control transfer.
836          *
837          * This function must be non-blocking.
838          * Return:
839          * - 0 on success
840          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
841          *   was opened
842          * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
843          *   blocking
844          * - another LIBUSB_ERROR code on other failure.
845          */
846         int (*get_configuration)(struct libusb_device_handle *dev_handle, int *config);
847
848         /* Set the active configuration for a device.
849          *
850          * A configuration value of -1 should put the device in unconfigured state.
851          *
852          * This function can block.
853          *
854          * Return:
855          * - 0 on success
856          * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
857          * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
858          *   configuration cannot be changed)
859          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
860          *   was opened
861          * - another LIBUSB_ERROR code on other failure.
862          */
863         int (*set_configuration)(struct libusb_device_handle *dev_handle, int config);
864
865         /* Claim an interface. When claimed, the application can then perform
866          * I/O to an interface's endpoints.
867          *
868          * This function should not generate any bus I/O and should not block.
869          * Interface claiming is a logical operation that simply ensures that
870          * no other drivers/applications are using the interface, and after
871          * claiming, no other drivers/applications can use the interface because
872          * we now "own" it.
873          *
874          * Return:
875          * - 0 on success
876          * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
877          * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
878          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
879          *   was opened
880          * - another LIBUSB_ERROR code on other failure
881          */
882         int (*claim_interface)(struct libusb_device_handle *dev_handle, int interface_number);
883
884         /* Release a previously claimed interface.
885          *
886          * This function should also generate a SET_INTERFACE control request,
887          * resetting the alternate setting of that interface to 0. It's OK for
888          * this function to block as a result.
889          *
890          * You will only ever be asked to release an interface which was
891          * successfully claimed earlier.
892          *
893          * Return:
894          * - 0 on success
895          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
896          *   was opened
897          * - another LIBUSB_ERROR code on other failure
898          */
899         int (*release_interface)(struct libusb_device_handle *dev_handle, int interface_number);
900
901         /* Set the alternate setting for an interface.
902          *
903          * You will only ever be asked to set the alternate setting for an
904          * interface which was successfully claimed earlier.
905          *
906          * It's OK for this function to block.
907          *
908          * Return:
909          * - 0 on success
910          * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
911          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
912          *   was opened
913          * - another LIBUSB_ERROR code on other failure
914          */
915         int (*set_interface_altsetting)(struct libusb_device_handle *dev_handle,
916                 int interface_number, int altsetting);
917
918         /* Clear a halt/stall condition on an endpoint.
919          *
920          * It's OK for this function to block.
921          *
922          * Return:
923          * - 0 on success
924          * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
925          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
926          *   was opened
927          * - another LIBUSB_ERROR code on other failure
928          */
929         int (*clear_halt)(struct libusb_device_handle *dev_handle,
930                 unsigned char endpoint);
931
932         /* Perform a USB port reset to reinitialize a device.
933          *
934          * If possible, the device handle should still be usable after the reset
935          * completes, assuming that the device descriptors did not change during
936          * reset and all previous interface state can be restored.
937          *
938          * If something changes, or you cannot easily locate/verify the resetted
939          * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
940          * to close the old handle and re-enumerate the device.
941          *
942          * Return:
943          * - 0 on success
944          * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
945          *   has been disconnected since it was opened
946          * - another LIBUSB_ERROR code on other failure
947          */
948         int (*reset_device)(struct libusb_device_handle *dev_handle);
949
950         /* Alloc num_streams usb3 bulk streams on the passed in endpoints */
951         int (*alloc_streams)(struct libusb_device_handle *dev_handle,
952                 uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
953
954         /* Free usb3 bulk streams allocated with alloc_streams */
955         int (*free_streams)(struct libusb_device_handle *dev_handle,
956                 unsigned char *endpoints, int num_endpoints);
957
958         /* Allocate persistent DMA memory for the given device, suitable for
959          * zerocopy. May return NULL on failure. Optional to implement.
960          */
961         unsigned char *(*dev_mem_alloc)(struct libusb_device_handle *handle,
962                 size_t len);
963
964         /* Free memory allocated by dev_mem_alloc. */
965         int (*dev_mem_free)(struct libusb_device_handle *handle,
966                 unsigned char *buffer, size_t len);
967
968         /* Determine if a kernel driver is active on an interface. Optional.
969          *
970          * The presence of a kernel driver on an interface indicates that any
971          * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
972          *
973          * Return:
974          * - 0 if no driver is active
975          * - 1 if a driver is active
976          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
977          *   was opened
978          * - another LIBUSB_ERROR code on other failure
979          */
980         int (*kernel_driver_active)(struct libusb_device_handle *dev_handle,
981                 int interface_number);
982
983         /* Detach a kernel driver from an interface. Optional.
984          *
985          * After detaching a kernel driver, the interface should be available
986          * for claim.
987          *
988          * Return:
989          * - 0 on success
990          * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
991          * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
992          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
993          *   was opened
994          * - another LIBUSB_ERROR code on other failure
995          */
996         int (*detach_kernel_driver)(struct libusb_device_handle *dev_handle,
997                 int interface_number);
998
999         /* Attach a kernel driver to an interface. Optional.
1000          *
1001          * Reattach a kernel driver to the device.
1002          *
1003          * Return:
1004          * - 0 on success
1005          * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1006          * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1007          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1008          *   was opened
1009          * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
1010          *   preventing reattachment
1011          * - another LIBUSB_ERROR code on other failure
1012          */
1013         int (*attach_kernel_driver)(struct libusb_device_handle *dev_handle,
1014                 int interface_number);
1015
1016         /* Destroy a device. Optional.
1017          *
1018          * This function is called when the last reference to a device is
1019          * destroyed. It should free any resources allocated in the get_device_list
1020          * path.
1021          */
1022         void (*destroy_device)(struct libusb_device *dev);
1023
1024         /* Submit a transfer. Your implementation should take the transfer,
1025          * morph it into whatever form your platform requires, and submit it
1026          * asynchronously.
1027          *
1028          * This function must not block.
1029          *
1030          * This function gets called with the flying_transfers_lock locked!
1031          *
1032          * Return:
1033          * - 0 on success
1034          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1035          * - another LIBUSB_ERROR code on other failure
1036          */
1037         int (*submit_transfer)(struct usbi_transfer *itransfer);
1038
1039         /* Cancel a previously submitted transfer.
1040          *
1041          * This function must not block. The transfer cancellation must complete
1042          * later, resulting in a call to usbi_handle_transfer_cancellation()
1043          * from the context of handle_events.
1044          */
1045         int (*cancel_transfer)(struct usbi_transfer *itransfer);
1046
1047         /* Clear a transfer as if it has completed or cancelled, but do not
1048          * report any completion/cancellation to the library. You should free
1049          * all private data from the transfer as if you were just about to report
1050          * completion or cancellation.
1051          *
1052          * This function might seem a bit out of place. It is used when libusb
1053          * detects a disconnected device - it calls this function for all pending
1054          * transfers before reporting completion (with the disconnect code) to
1055          * the user. Maybe we can improve upon this internal interface in future.
1056          */
1057         void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
1058
1059         /* Handle any pending events on file descriptors. Optional.
1060          *
1061          * Provide this function when file descriptors directly indicate device
1062          * or transfer activity. If your backend does not have such file descriptors,
1063          * implement the handle_transfer_completion function below.
1064          *
1065          * This involves monitoring any active transfers and processing their
1066          * completion or cancellation.
1067          *
1068          * The function is passed an array of pollfd structures (size nfds)
1069          * as a result of the poll() system call. The num_ready parameter
1070          * indicates the number of file descriptors that have reported events
1071          * (i.e. the poll() return value). This should be enough information
1072          * for you to determine which actions need to be taken on the currently
1073          * active transfers.
1074          *
1075          * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1076          * For completed transfers, call usbi_handle_transfer_completion().
1077          * For control/bulk/interrupt transfers, populate the "transferred"
1078          * element of the appropriate usbi_transfer structure before calling the
1079          * above functions. For isochronous transfers, populate the status and
1080          * transferred fields of the iso packet descriptors of the transfer.
1081          *
1082          * This function should also be able to detect disconnection of the
1083          * device, reporting that situation with usbi_handle_disconnect().
1084          *
1085          * When processing an event related to a transfer, you probably want to
1086          * take usbi_transfer.lock to prevent races. See the documentation for
1087          * the usbi_transfer structure.
1088          *
1089          * Return 0 on success, or a LIBUSB_ERROR code on failure.
1090          */
1091         int (*handle_events)(struct libusb_context *ctx,
1092                 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready);
1093
1094         /* Handle transfer completion. Optional.
1095          *
1096          * Provide this function when there are no file descriptors available
1097          * that directly indicate device or transfer activity. If your backend does
1098          * have such file descriptors, implement the handle_events function above.
1099          *
1100          * Your backend must tell the library when a transfer has completed by
1101          * calling usbi_signal_transfer_completion(). You should store any private
1102          * information about the transfer and its completion status in the transfer's
1103          * private backend data.
1104          *
1105          * During event handling, this function will be called on each transfer for
1106          * which usbi_signal_transfer_completion() was called.
1107          *
1108          * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1109          * For completed transfers, call usbi_handle_transfer_completion().
1110          * For control/bulk/interrupt transfers, populate the "transferred"
1111          * element of the appropriate usbi_transfer structure before calling the
1112          * above functions. For isochronous transfers, populate the status and
1113          * transferred fields of the iso packet descriptors of the transfer.
1114          *
1115          * Return 0 on success, or a LIBUSB_ERROR code on failure.
1116          */
1117         int (*handle_transfer_completion)(struct usbi_transfer *itransfer);
1118
1119         /* Get time from specified clock. At least two clocks must be implemented
1120            by the backend: USBI_CLOCK_REALTIME, and USBI_CLOCK_MONOTONIC.
1121
1122            Description of clocks:
1123              USBI_CLOCK_REALTIME : clock returns time since system epoch.
1124              USBI_CLOCK_MONOTONIC: clock returns time since unspecified start
1125                                      time (usually boot).
1126          */
1127         int (*clock_gettime)(int clkid, struct timespec *tp);
1128
1129 #ifdef USBI_TIMERFD_AVAILABLE
1130         /* clock ID of the clock that should be used for timerfd */
1131         clockid_t (*get_timerfd_clockid)(void);
1132 #endif
1133
1134         /* Number of bytes to reserve for per-context private backend data.
1135          * This private data area is accessible through the "os_priv" field of
1136          * struct libusb_context. */
1137         size_t context_priv_size;
1138
1139         /* Number of bytes to reserve for per-device private backend data.
1140          * This private data area is accessible through the "os_priv" field of
1141          * struct libusb_device. */
1142         size_t device_priv_size;
1143
1144         /* Number of bytes to reserve for per-handle private backend data.
1145          * This private data area is accessible through the "os_priv" field of
1146          * struct libusb_device. */
1147         size_t device_handle_priv_size;
1148
1149         /* Number of bytes to reserve for per-transfer private backend data.
1150          * This private data area is accessible by calling
1151          * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance.
1152          */
1153         size_t transfer_priv_size;
1154 };
1155
1156 extern const struct usbi_os_backend usbi_backend;
1157
1158 extern struct list_head active_contexts_list;
1159 extern usbi_mutex_static_t active_contexts_lock;
1160
1161 #ifdef __cplusplus
1162 }
1163 #endif
1164
1165 #endif