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