core: Suppress hotplug events during initial enumeration
[platform/upstream/libusb.git] / 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  * Copyright © 2019 Nathan Hjelm <hjelmn@cs.umm.edu>
6  * Copyright © 2019-2020 Google LLC. All rights reserved.
7  * Copyright © 2020 Chris Dickens <christopher.a.dickens@gmail.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #ifndef LIBUSBI_H
25 #define LIBUSBI_H
26
27 #include <config.h>
28
29 #include <assert.h>
30 #include <inttypes.h>
31 #include <stdarg.h>
32 #include <stddef.h>
33 #include <stdlib.h>
34 #ifdef HAVE_SYS_TIME_H
35 #include <sys/time.h>
36 #endif
37
38 #include "libusb.h"
39
40 /* Not all C standard library headers define static_assert in assert.h
41  * Additionally, Visual Studio treats static_assert as a keyword.
42  */
43 #if !defined(__cplusplus) && !defined(static_assert) && !defined(_MSC_VER)
44 #define static_assert(cond, msg) _Static_assert(cond, msg)
45 #endif
46
47 #ifdef NDEBUG
48 #define ASSERT_EQ(expression, value)    (void)expression
49 #define ASSERT_NE(expression, value)    (void)expression
50 #else
51 #define ASSERT_EQ(expression, value)    assert(expression == value)
52 #define ASSERT_NE(expression, value)    assert(expression != value)
53 #endif
54
55 #define container_of(ptr, type, member) \
56         ((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
57
58 #ifndef ARRAYSIZE
59 #define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))
60 #endif
61
62 #ifndef CLAMP
63 #define CLAMP(val, min, max) \
64         ((val) < (min) ? (min) : ((val) > (max) ? (max) : (val)))
65 #endif
66
67 #ifndef MIN
68 #define MIN(a, b)       ((a) < (b) ? (a) : (b))
69 #endif
70
71 #ifndef MAX
72 #define MAX(a, b)       ((a) > (b) ? (a) : (b))
73 #endif
74
75 /* The following is used to silence warnings for unused variables */
76 #if defined(UNREFERENCED_PARAMETER)
77 #define UNUSED(var)     UNREFERENCED_PARAMETER(var)
78 #else
79 #define UNUSED(var)     do { (void)(var); } while(0)
80 #endif
81
82 /* Macro to align a value up to the next multiple of the size of a pointer */
83 #define PTR_ALIGN(v) \
84         (((v) + (sizeof(void *) - 1)) & ~(sizeof(void *) - 1))
85
86 /* Atomic operations
87  *
88  * Useful for reference counting or when accessing a value without a lock
89  *
90  * The following atomic operations are defined:
91  *   usbi_atomic_load() - Atomically read a variable's value
92  *   usbi_atomic_store() - Atomically write a new value value to a variable
93  *   usbi_atomic_inc() - Atomically increment a variable's value and return the new value
94  *   usbi_atomic_dec() - Atomically decrement a variable's value and return the new value
95  *
96  * All of these operations are ordered with each other, thus the effects of
97  * any one operation is guaranteed to be seen by any other operation.
98  */
99 #ifdef _MSC_VER
100 typedef volatile LONG usbi_atomic_t;
101 #define usbi_atomic_load(a)     (*(a))
102 #define usbi_atomic_store(a, v) (*(a)) = (v)
103 #define usbi_atomic_inc(a)      InterlockedIncrement((a))
104 #define usbi_atomic_dec(a)      InterlockedDecrement((a))
105 #else
106 #include <stdatomic.h>
107 typedef atomic_long usbi_atomic_t;
108 #define usbi_atomic_load(a)     atomic_load((a))
109 #define usbi_atomic_store(a, v) atomic_store((a), (v))
110 #define usbi_atomic_inc(a)      (atomic_fetch_add((a), 1) + 1)
111 #define usbi_atomic_dec(a)      (atomic_fetch_add((a), -1) - 1)
112 #endif
113
114 /* Internal abstractions for event handling and thread synchronization */
115 #if defined(PLATFORM_POSIX)
116 #include "os/events_posix.h"
117 #include "os/threads_posix.h"
118 #elif defined(PLATFORM_WINDOWS)
119 #include "os/events_windows.h"
120 #include "os/threads_windows.h"
121 #endif
122
123 /* Inside the libusb code, mark all public functions as follows:
124  *   return_type API_EXPORTED function_name(params) { ... }
125  * But if the function returns a pointer, mark it as follows:
126  *   DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
127  * In the libusb public header, mark all declarations as:
128  *   return_type LIBUSB_CALL function_name(params);
129  */
130 #define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
131
132 #ifdef __cplusplus
133 extern "C" {
134 #endif
135
136 #define USB_MAXENDPOINTS        32
137 #define USB_MAXINTERFACES       32
138 #define USB_MAXCONFIG           8
139
140 /* Backend specific capabilities */
141 #define USBI_CAP_HAS_HID_ACCESS                 0x00010000
142 #define USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER  0x00020000
143
144 /* Maximum number of bytes in a log line */
145 #define USBI_MAX_LOG_LEN        1024
146 /* Terminator for log lines */
147 #define USBI_LOG_LINE_END       "\n"
148
149 struct list_head {
150         struct list_head *prev, *next;
151 };
152
153 /* Get an entry from the list
154  *  ptr - the address of this list_head element in "type"
155  *  type - the data type that contains "member"
156  *  member - the list_head element in "type"
157  */
158 #define list_entry(ptr, type, member) \
159         container_of(ptr, type, member)
160
161 #define list_first_entry(ptr, type, member) \
162         list_entry((ptr)->next, type, member)
163
164 #define list_next_entry(ptr, type, member) \
165         list_entry((ptr)->member.next, type, member)
166
167 /* Get each entry from a list
168  *  pos - A structure pointer has a "member" element
169  *  head - list head
170  *  member - the list_head element in "pos"
171  *  type - the type of the first parameter
172  */
173 #define list_for_each_entry(pos, head, member, type)                    \
174         for (pos = list_first_entry(head, type, member);                \
175                  &pos->member != (head);                                \
176                  pos = list_next_entry(pos, type, member))
177
178 #define list_for_each_entry_safe(pos, n, head, member, type)            \
179         for (pos = list_first_entry(head, type, member),                \
180                  n = list_next_entry(pos, type, member);                \
181                  &pos->member != (head);                                \
182                  pos = n, n = list_next_entry(n, type, member))
183
184 /* Helper macros to iterate over a list. The structure pointed
185  * to by "pos" must have a list_head member named "list".
186  */
187 #define for_each_helper(pos, head, type) \
188         list_for_each_entry(pos, head, list, type)
189
190 #define for_each_safe_helper(pos, n, head, type) \
191         list_for_each_entry_safe(pos, n, head, list, type)
192
193 #define list_empty(entry) ((entry)->next == (entry))
194
195 static inline void list_init(struct list_head *entry)
196 {
197         entry->prev = entry->next = entry;
198 }
199
200 static inline void list_add(struct list_head *entry, struct list_head *head)
201 {
202         entry->next = head->next;
203         entry->prev = head;
204
205         head->next->prev = entry;
206         head->next = entry;
207 }
208
209 static inline void list_add_tail(struct list_head *entry,
210         struct list_head *head)
211 {
212         entry->next = head;
213         entry->prev = head->prev;
214
215         head->prev->next = entry;
216         head->prev = entry;
217 }
218
219 static inline void list_del(struct list_head *entry)
220 {
221         entry->next->prev = entry->prev;
222         entry->prev->next = entry->next;
223         entry->next = entry->prev = NULL;
224 }
225
226 static inline void list_cut(struct list_head *list, struct list_head *head)
227 {
228         if (list_empty(head)) {
229                 list_init(list);
230                 return;
231         }
232
233         list->next = head->next;
234         list->next->prev = list;
235         list->prev = head->prev;
236         list->prev->next = list;
237
238         list_init(head);
239 }
240
241 static inline void list_splice_front(struct list_head *list, struct list_head *head)
242 {
243         list->next->prev = head;
244         list->prev->next = head->next;
245         head->next->prev = list->prev;
246         head->next = list->next;
247 }
248
249 static inline void *usbi_reallocf(void *ptr, size_t size)
250 {
251         void *ret = realloc(ptr, size);
252
253         if (!ret)
254                 free(ptr);
255         return ret;
256 }
257
258 #if !defined(USEC_PER_SEC)
259 #define USEC_PER_SEC    1000000L
260 #endif
261
262 #if !defined(NSEC_PER_SEC)
263 #define NSEC_PER_SEC    1000000000L
264 #endif
265
266 #define TIMEVAL_IS_VALID(tv)                                            \
267         ((tv)->tv_sec >= 0 &&                                           \
268          (tv)->tv_usec >= 0 && (tv)->tv_usec < USEC_PER_SEC)
269
270 #define TIMESPEC_IS_SET(ts)     ((ts)->tv_sec || (ts)->tv_nsec)
271 #define TIMESPEC_CLEAR(ts)      (ts)->tv_sec = (ts)->tv_nsec = 0
272 #define TIMESPEC_CMP(a, b, CMP)                                         \
273         (((a)->tv_sec == (b)->tv_sec)                                   \
274          ? ((a)->tv_nsec CMP (b)->tv_nsec)                              \
275          : ((a)->tv_sec CMP (b)->tv_sec))
276 #define TIMESPEC_SUB(a, b, result)                                      \
277         do {                                                            \
278                 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec;           \
279                 (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec;        \
280                 if ((result)->tv_nsec < 0L) {                           \
281                         --(result)->tv_sec;                             \
282                         (result)->tv_nsec += NSEC_PER_SEC;              \
283                 }                                                       \
284         } while (0)
285
286 #if defined(PLATFORM_WINDOWS)
287 #define TIMEVAL_TV_SEC_TYPE     long
288 #else
289 #define TIMEVAL_TV_SEC_TYPE     time_t
290 #endif
291
292 /* Some platforms don't have this define */
293 #ifndef TIMESPEC_TO_TIMEVAL
294 #define TIMESPEC_TO_TIMEVAL(tv, ts)                                     \
295         do {                                                            \
296                 (tv)->tv_sec = (TIMEVAL_TV_SEC_TYPE) (ts)->tv_sec;      \
297                 (tv)->tv_usec = (ts)->tv_nsec / 1000L;                  \
298         } while (0)
299 #endif
300
301 #ifdef ENABLE_LOGGING
302
303 #if defined(_MSC_VER) && (_MSC_VER < 1900)
304 #include <stdio.h>
305 #define snprintf usbi_snprintf
306 #define vsnprintf usbi_vsnprintf
307 int usbi_snprintf(char *dst, size_t size, const char *format, ...);
308 int usbi_vsnprintf(char *dst, size_t size, const char *format, va_list args);
309 #define LIBUSB_PRINTF_WIN32
310 #endif /* defined(_MSC_VER) && (_MSC_VER < 1900) */
311
312 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
313         const char *function, const char *format, ...) PRINTF_FORMAT(4, 5);
314
315 #define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __func__, __VA_ARGS__)
316
317 #define usbi_err(ctx, ...)      _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
318 #define usbi_warn(ctx, ...)     _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
319 #define usbi_info(ctx, ...)     _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
320 #define usbi_dbg(ctx ,...)              _usbi_log(ctx, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
321
322 #else /* ENABLE_LOGGING */
323
324 #define usbi_err(ctx, ...)      UNUSED(ctx)
325 #define usbi_warn(ctx, ...)     UNUSED(ctx)
326 #define usbi_info(ctx, ...)     UNUSED(ctx)
327 #define usbi_dbg(ctx, ...)      do {} while (0)
328
329 #endif /* ENABLE_LOGGING */
330
331 #define DEVICE_CTX(dev)         ((dev)->ctx)
332 #define HANDLE_CTX(handle)      ((handle) ? DEVICE_CTX((handle)->dev) : NULL)
333 #define ITRANSFER_CTX(itransfer) \
334         ((itransfer)->dev ? DEVICE_CTX((itransfer)->dev) : NULL)
335 #define TRANSFER_CTX(transfer) \
336         (ITRANSFER_CTX(LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)))
337
338 #define IS_EPIN(ep)             (0 != ((ep) & LIBUSB_ENDPOINT_IN))
339 #define IS_EPOUT(ep)            (!IS_EPIN(ep))
340 #define IS_XFERIN(xfer)         (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
341 #define IS_XFEROUT(xfer)        (!IS_XFERIN(xfer))
342
343 struct libusb_context {
344 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
345         enum libusb_log_level debug;
346         int debug_fixed;
347         libusb_log_cb log_handler;
348 #endif
349
350         /* used for signalling occurrence of an internal event. */
351         usbi_event_t event;
352
353 #ifdef HAVE_OS_TIMER
354         /* used for timeout handling, if supported by OS.
355          * this timer is maintained to trigger on the next pending timeout */
356         usbi_timer_t timer;
357 #endif
358
359         struct list_head usb_devs;
360         usbi_mutex_t usb_devs_lock;
361
362         /* A list of open handles. Backends are free to traverse this if required.
363          */
364         struct list_head open_devs;
365         usbi_mutex_t open_devs_lock;
366
367         /* A list of registered hotplug callbacks */
368         struct list_head hotplug_cbs;
369         libusb_hotplug_callback_handle next_hotplug_cb_handle;
370         usbi_mutex_t hotplug_cbs_lock;
371
372         /* A flag to indicate that the context is ready for hotplug notifications */
373         usbi_atomic_t hotplug_ready;
374
375         /* this is a list of in-flight transfer handles, sorted by timeout
376          * expiration. URBs to timeout the soonest are placed at the beginning of
377          * the list, URBs that will time out later are placed after, and urbs with
378          * infinite timeout are always placed at the very end. */
379         struct list_head flying_transfers;
380         /* Note paths taking both this and usbi_transfer->lock must always
381          * take this lock first */
382         usbi_mutex_t flying_transfers_lock;
383
384 #if !defined(PLATFORM_WINDOWS)
385         /* user callbacks for pollfd changes */
386         libusb_pollfd_added_cb fd_added_cb;
387         libusb_pollfd_removed_cb fd_removed_cb;
388         void *fd_cb_user_data;
389 #endif
390
391         /* ensures that only one thread is handling events at any one time */
392         usbi_mutex_t events_lock;
393
394         /* used to see if there is an active thread doing event handling */
395         int event_handler_active;
396
397         /* A thread-local storage key to track which thread is performing event
398          * handling */
399         usbi_tls_key_t event_handling_key;
400
401         /* used to wait for event completion in threads other than the one that is
402          * event handling */
403         usbi_mutex_t event_waiters_lock;
404         usbi_cond_t event_waiters_cond;
405
406         /* A lock to protect internal context event data. */
407         usbi_mutex_t event_data_lock;
408
409         /* A bitmask of flags that are set to indicate specific events that need to
410          * be handled. Protected by event_data_lock. */
411         unsigned int event_flags;
412
413         /* A counter that is set when we want to interrupt and prevent event handling,
414          * in order to safely close a device. Protected by event_data_lock. */
415         unsigned int device_close;
416
417         /* A list of currently active event sources. Protected by event_data_lock. */
418         struct list_head event_sources;
419
420         /* A list of event sources that have been removed since the last time
421          * event sources were waited on. Protected by event_data_lock. */
422         struct list_head removed_event_sources;
423
424         /* A pointer and count to platform-specific data used for monitoring event
425          * sources. Only accessed during event handling. */
426         void *event_data;
427         unsigned int event_data_cnt;
428
429         /* A list of pending hotplug messages. Protected by event_data_lock. */
430         struct list_head hotplug_msgs;
431
432         /* A list of pending completed transfers. Protected by event_data_lock. */
433         struct list_head completed_transfers;
434
435         struct list_head list;
436 };
437
438 extern struct libusb_context *usbi_default_context;
439
440 extern struct list_head active_contexts_list;
441 extern usbi_mutex_static_t active_contexts_lock;
442
443 static inline struct libusb_context *usbi_get_context(struct libusb_context *ctx)
444 {
445         return ctx ? ctx : usbi_default_context;
446 }
447
448 enum usbi_event_flags {
449         /* The list of event sources has been modified */
450         USBI_EVENT_EVENT_SOURCES_MODIFIED = 1U << 0,
451
452         /* The user has interrupted the event handler */
453         USBI_EVENT_USER_INTERRUPT = 1U << 1,
454
455         /* A hotplug callback deregistration is pending */
456         USBI_EVENT_HOTPLUG_CB_DEREGISTERED = 1U << 2,
457
458         /* One or more hotplug messages are pending */
459         USBI_EVENT_HOTPLUG_MSG_PENDING = 1U << 3,
460
461         /* One or more completed transfers are pending */
462         USBI_EVENT_TRANSFER_COMPLETED = 1U << 4,
463
464         /* A device is in the process of being closed */
465         USBI_EVENT_DEVICE_CLOSE = 1U << 5,
466 };
467
468 /* Macros for managing event handling state */
469 static inline int usbi_handling_events(struct libusb_context *ctx)
470 {
471         return usbi_tls_key_get(ctx->event_handling_key) != NULL;
472 }
473
474 static inline void usbi_start_event_handling(struct libusb_context *ctx)
475 {
476         usbi_tls_key_set(ctx->event_handling_key, ctx);
477 }
478
479 static inline void usbi_end_event_handling(struct libusb_context *ctx)
480 {
481         usbi_tls_key_set(ctx->event_handling_key, NULL);
482 }
483
484 struct libusb_device {
485         usbi_atomic_t refcnt;
486
487         struct libusb_context *ctx;
488         struct libusb_device *parent_dev;
489
490         uint8_t bus_number;
491         uint8_t port_number;
492         uint8_t device_address;
493         enum libusb_speed speed;
494
495         struct list_head list;
496         unsigned long session_data;
497
498         struct libusb_device_descriptor device_descriptor;
499         usbi_atomic_t attached;
500 };
501
502 struct libusb_device_handle {
503         /* lock protects claimed_interfaces */
504         usbi_mutex_t lock;
505         unsigned long claimed_interfaces;
506
507         struct list_head list;
508         struct libusb_device *dev;
509         int auto_detach_kernel_driver;
510 };
511
512 /* Function called by backend during device initialization to convert
513  * multi-byte fields in the device descriptor to host-endian format.
514  */
515 static inline void usbi_localize_device_descriptor(struct libusb_device_descriptor *desc)
516 {
517         desc->bcdUSB = libusb_le16_to_cpu(desc->bcdUSB);
518         desc->idVendor = libusb_le16_to_cpu(desc->idVendor);
519         desc->idProduct = libusb_le16_to_cpu(desc->idProduct);
520         desc->bcdDevice = libusb_le16_to_cpu(desc->bcdDevice);
521 }
522
523 #ifdef HAVE_CLOCK_GETTIME
524 static inline void usbi_get_monotonic_time(struct timespec *tp)
525 {
526         ASSERT_EQ(clock_gettime(CLOCK_MONOTONIC, tp), 0);
527 }
528 static inline void usbi_get_real_time(struct timespec *tp)
529 {
530         ASSERT_EQ(clock_gettime(CLOCK_REALTIME, tp), 0);
531 }
532 #else
533 /* If the platform doesn't provide the clock_gettime() function, the backend
534  * must provide its own clock implementations.  Two clock functions are
535  * required:
536  *
537  *   usbi_get_monotonic_time(): returns the time since an unspecified starting
538  *                              point (usually boot) that is monotonically
539  *                              increasing.
540  *   usbi_get_real_time(): returns the time since system epoch.
541  */
542 void usbi_get_monotonic_time(struct timespec *tp);
543 void usbi_get_real_time(struct timespec *tp);
544 #endif
545
546 /* in-memory transfer layout:
547  *
548  * 1. os private data
549  * 2. struct usbi_transfer
550  * 3. struct libusb_transfer (which includes iso packets) [variable size]
551  *
552  * from a libusb_transfer, you can get the usbi_transfer by rewinding the
553  * appropriate number of bytes.
554  */
555
556 struct usbi_transfer {
557         int num_iso_packets;
558         struct list_head list;
559         struct list_head completed_list;
560         struct timespec timeout;
561         int transferred;
562         uint32_t stream_id;
563         uint32_t state_flags;   /* Protected by usbi_transfer->lock */
564         uint32_t timeout_flags; /* Protected by the flying_stransfers_lock */
565
566         /* The device reference is held until destruction for logging
567          * even after dev_handle is set to NULL.  */
568         struct libusb_device *dev;
569
570         /* this lock is held during libusb_submit_transfer() and
571          * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
572          * cancellation, submission-during-cancellation, etc). the OS backend
573          * should also take this lock in the handle_events path, to prevent the user
574          * cancelling the transfer from another thread while you are processing
575          * its completion (presumably there would be races within your OS backend
576          * if this were possible).
577          * Note paths taking both this and the flying_transfers_lock must
578          * always take the flying_transfers_lock first */
579         usbi_mutex_t lock;
580
581         void *priv;
582 };
583
584 enum usbi_transfer_state_flags {
585         /* Transfer successfully submitted by backend */
586         USBI_TRANSFER_IN_FLIGHT = 1U << 0,
587
588         /* Cancellation was requested via libusb_cancel_transfer() */
589         USBI_TRANSFER_CANCELLING = 1U << 1,
590
591         /* Operation on the transfer failed because the device disappeared */
592         USBI_TRANSFER_DEVICE_DISAPPEARED = 1U << 2,
593 };
594
595 enum usbi_transfer_timeout_flags {
596         /* Set by backend submit_transfer() if the OS handles timeout */
597         USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1U << 0,
598
599         /* The transfer timeout has been handled */
600         USBI_TRANSFER_TIMEOUT_HANDLED = 1U << 1,
601
602         /* The transfer timeout was successfully processed */
603         USBI_TRANSFER_TIMED_OUT = 1U << 2,
604 };
605
606 #define USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)     \
607         ((struct libusb_transfer *)                     \
608          ((unsigned char *)(itransfer)                  \
609           + PTR_ALIGN(sizeof(struct usbi_transfer))))
610 #define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)      \
611         ((struct usbi_transfer *)                       \
612          ((unsigned char *)(transfer)                   \
613           - PTR_ALIGN(sizeof(struct usbi_transfer))))
614
615 #ifdef _MSC_VER
616 #pragma pack(push, 1)
617 #endif
618
619 /* All standard descriptors have these 2 fields in common */
620 struct usbi_descriptor_header {
621         uint8_t  bLength;
622         uint8_t  bDescriptorType;
623 } LIBUSB_PACKED;
624
625 struct usbi_device_descriptor {
626         uint8_t  bLength;
627         uint8_t  bDescriptorType;
628         uint16_t bcdUSB;
629         uint8_t  bDeviceClass;
630         uint8_t  bDeviceSubClass;
631         uint8_t  bDeviceProtocol;
632         uint8_t  bMaxPacketSize0;
633         uint16_t idVendor;
634         uint16_t idProduct;
635         uint16_t bcdDevice;
636         uint8_t  iManufacturer;
637         uint8_t  iProduct;
638         uint8_t  iSerialNumber;
639         uint8_t  bNumConfigurations;
640 } LIBUSB_PACKED;
641
642 struct usbi_configuration_descriptor {
643         uint8_t  bLength;
644         uint8_t  bDescriptorType;
645         uint16_t wTotalLength;
646         uint8_t  bNumInterfaces;
647         uint8_t  bConfigurationValue;
648         uint8_t  iConfiguration;
649         uint8_t  bmAttributes;
650         uint8_t  bMaxPower;
651 } LIBUSB_PACKED;
652
653 struct usbi_interface_descriptor {
654         uint8_t  bLength;
655         uint8_t  bDescriptorType;
656         uint8_t  bInterfaceNumber;
657         uint8_t  bAlternateSetting;
658         uint8_t  bNumEndpoints;
659         uint8_t  bInterfaceClass;
660         uint8_t  bInterfaceSubClass;
661         uint8_t  bInterfaceProtocol;
662         uint8_t  iInterface;
663 } LIBUSB_PACKED;
664
665 struct usbi_string_descriptor {
666         uint8_t  bLength;
667         uint8_t  bDescriptorType;
668         uint16_t wData[ZERO_SIZED_ARRAY];
669 } LIBUSB_PACKED;
670
671 struct usbi_bos_descriptor {
672         uint8_t  bLength;
673         uint8_t  bDescriptorType;
674         uint16_t wTotalLength;
675         uint8_t  bNumDeviceCaps;
676 } LIBUSB_PACKED;
677
678 #ifdef _MSC_VER
679 #pragma pack(pop)
680 #endif
681
682 union usbi_config_desc_buf {
683         struct usbi_configuration_descriptor desc;
684         uint8_t buf[LIBUSB_DT_CONFIG_SIZE];
685         uint16_t align;         /* Force 2-byte alignment */
686 };
687
688 union usbi_string_desc_buf {
689         struct usbi_string_descriptor desc;
690         uint8_t buf[255];       /* Some devices choke on size > 255 */
691         uint16_t align;         /* Force 2-byte alignment */
692 };
693
694 union usbi_bos_desc_buf {
695         struct usbi_bos_descriptor desc;
696         uint8_t buf[LIBUSB_DT_BOS_SIZE];
697         uint16_t align;         /* Force 2-byte alignment */
698 };
699
700 enum usbi_hotplug_flags {
701         /* This callback is interested in device arrivals */
702         USBI_HOTPLUG_DEVICE_ARRIVED = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
703
704         /* This callback is interested in device removals */
705         USBI_HOTPLUG_DEVICE_LEFT = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT,
706
707         /* IMPORTANT: The values for the below entries must start *after*
708          * the highest value of the above entries!!!
709          */
710
711         /* The vendor_id field is valid for matching */
712         USBI_HOTPLUG_VENDOR_ID_VALID = (1U << 3),
713
714         /* The product_id field is valid for matching */
715         USBI_HOTPLUG_PRODUCT_ID_VALID = (1U << 4),
716
717         /* The dev_class field is valid for matching */
718         USBI_HOTPLUG_DEV_CLASS_VALID = (1U << 5),
719
720         /* This callback has been unregistered and needs to be freed */
721         USBI_HOTPLUG_NEEDS_FREE = (1U << 6),
722 };
723
724 struct usbi_hotplug_callback {
725         /* Flags that control how this callback behaves */
726         uint8_t flags;
727
728         /* Vendor ID to match (if flags says this is valid) */
729         uint16_t vendor_id;
730
731         /* Product ID to match (if flags says this is valid) */
732         uint16_t product_id;
733
734         /* Device class to match (if flags says this is valid) */
735         uint8_t dev_class;
736
737         /* Callback function to invoke for matching event/device */
738         libusb_hotplug_callback_fn cb;
739
740         /* Handle for this callback (used to match on deregister) */
741         libusb_hotplug_callback_handle handle;
742
743         /* User data that will be passed to the callback function */
744         void *user_data;
745
746         /* List this callback is registered in (ctx->hotplug_cbs) */
747         struct list_head list;
748 };
749
750 struct usbi_hotplug_message {
751         /* The hotplug event that occurred */
752         libusb_hotplug_event event;
753
754         /* The device for which this hotplug event occurred */
755         struct libusb_device *device;
756
757         /* List this message is contained in (ctx->hotplug_msgs) */
758         struct list_head list;
759 };
760
761 /* shared data and functions */
762
763 void usbi_hotplug_init(struct libusb_context *ctx);
764 void usbi_hotplug_exit(struct libusb_context *ctx);
765 void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
766         libusb_hotplug_event event);
767 void usbi_hotplug_process(struct libusb_context *ctx, struct list_head *hotplug_msgs);
768
769 int usbi_io_init(struct libusb_context *ctx);
770 void usbi_io_exit(struct libusb_context *ctx);
771
772 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
773         unsigned long session_id);
774 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
775         unsigned long session_id);
776 int usbi_sanitize_device(struct libusb_device *dev);
777 void usbi_handle_disconnect(struct libusb_device_handle *dev_handle);
778
779 int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
780         enum libusb_transfer_status status);
781 int usbi_handle_transfer_cancellation(struct usbi_transfer *itransfer);
782 void usbi_signal_transfer_completion(struct usbi_transfer *itransfer);
783
784 void usbi_connect_device(struct libusb_device *dev);
785 void usbi_disconnect_device(struct libusb_device *dev);
786
787 struct usbi_event_source {
788         struct usbi_event_source_data {
789                 usbi_os_handle_t os_handle;
790                 short poll_events;
791         } data;
792         struct list_head list;
793 };
794
795 int usbi_add_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle,
796         short poll_events);
797 void usbi_remove_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle);
798
799 struct usbi_option {
800   int is_set;
801   union {
802     int ival;
803   } arg;
804 };
805
806 /* OS event abstraction */
807
808 int usbi_create_event(usbi_event_t *event);
809 void usbi_destroy_event(usbi_event_t *event);
810 void usbi_signal_event(usbi_event_t *event);
811 void usbi_clear_event(usbi_event_t *event);
812
813 #ifdef HAVE_OS_TIMER
814 int usbi_create_timer(usbi_timer_t *timer);
815 void usbi_destroy_timer(usbi_timer_t *timer);
816 int usbi_arm_timer(usbi_timer_t *timer, const struct timespec *timeout);
817 int usbi_disarm_timer(usbi_timer_t *timer);
818 #endif
819
820 static inline int usbi_using_timer(struct libusb_context *ctx)
821 {
822 #ifdef HAVE_OS_TIMER
823         return usbi_timer_valid(&ctx->timer);
824 #else
825         UNUSED(ctx);
826         return 0;
827 #endif
828 }
829
830 struct usbi_reported_events {
831         union {
832                 struct {
833                         unsigned int event_triggered:1;
834 #ifdef HAVE_OS_TIMER
835                         unsigned int timer_triggered:1;
836 #endif
837                 };
838                 unsigned int event_bits;
839         };
840         void *event_data;
841         unsigned int event_data_count;
842         unsigned int num_ready;
843 };
844
845 int usbi_alloc_event_data(struct libusb_context *ctx);
846 int usbi_wait_for_events(struct libusb_context *ctx,
847         struct usbi_reported_events *reported_events, int timeout_ms);
848
849 /* accessor functions for structure private data */
850
851 static inline void *usbi_get_context_priv(struct libusb_context *ctx)
852 {
853         return (unsigned char *)ctx + PTR_ALIGN(sizeof(*ctx));
854 }
855
856 static inline void *usbi_get_device_priv(struct libusb_device *dev)
857 {
858         return (unsigned char *)dev + PTR_ALIGN(sizeof(*dev));
859 }
860
861 static inline void *usbi_get_device_handle_priv(struct libusb_device_handle *dev_handle)
862 {
863         return (unsigned char *)dev_handle + PTR_ALIGN(sizeof(*dev_handle));
864 }
865
866 static inline void *usbi_get_transfer_priv(struct usbi_transfer *itransfer)
867 {
868         return itransfer->priv;
869 }
870
871 /* device discovery */
872
873 /* we traverse usbfs without knowing how many devices we are going to find.
874  * so we create this discovered_devs model which is similar to a linked-list
875  * which grows when required. it can be freed once discovery has completed,
876  * eliminating the need for a list node in the libusb_device structure
877  * itself. */
878 struct discovered_devs {
879         size_t len;
880         size_t capacity;
881         struct libusb_device *devices[ZERO_SIZED_ARRAY];
882 };
883
884 struct discovered_devs *discovered_devs_append(
885         struct discovered_devs *discdevs, struct libusb_device *dev);
886
887 /* OS abstraction */
888
889 /* This is the interface that OS backends need to implement.
890  * All fields are mandatory, except ones explicitly noted as optional. */
891 struct usbi_os_backend {
892         /* A human-readable name for your backend, e.g. "Linux usbfs" */
893         const char *name;
894
895         /* Binary mask for backend specific capabilities */
896         uint32_t caps;
897
898         /* Perform initialization of your backend. You might use this function
899          * to determine specific capabilities of the system, allocate required
900          * data structures for later, etc.
901          *
902          * This function is called when a libusb user initializes the library
903          * prior to use. Mutual exclusion with other init and exit calls is
904          * guaranteed when this function is called.
905          *
906          * Return 0 on success, or a LIBUSB_ERROR code on failure.
907          */
908         int (*init)(struct libusb_context *ctx);
909
910         /* Deinitialization. Optional. This function should destroy anything
911          * that was set up by init.
912          *
913          * This function is called when the user deinitializes the library.
914          * Mutual exclusion with other init and exit calls is guaranteed when
915          * this function is called.
916          */
917         void (*exit)(struct libusb_context *ctx);
918
919         /* Set a backend-specific option. Optional.
920          *
921          * This function is called when the user calls libusb_set_option() and
922          * the option is not handled by the core library.
923          *
924          * Return 0 on success, or a LIBUSB_ERROR code on failure.
925          */
926         int (*set_option)(struct libusb_context *ctx, enum libusb_option option,
927                 va_list args);
928
929         /* Enumerate all the USB devices on the system, returning them in a list
930          * of discovered devices.
931          *
932          * Your implementation should enumerate all devices on the system,
933          * regardless of whether they have been seen before or not.
934          *
935          * When you have found a device, compute a session ID for it. The session
936          * ID should uniquely represent that particular device for that particular
937          * connection session since boot (i.e. if you disconnect and reconnect a
938          * device immediately after, it should be assigned a different session ID).
939          * If your OS cannot provide a unique session ID as described above,
940          * presenting a session ID of (bus_number << 8 | device_address) should
941          * be sufficient. Bus numbers and device addresses wrap and get reused,
942          * but that is an unlikely case.
943          *
944          * After computing a session ID for a device, call
945          * usbi_get_device_by_session_id(). This function checks if libusb already
946          * knows about the device, and if so, it provides you with a reference
947          * to a libusb_device structure for it.
948          *
949          * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
950          * a new device structure for the device. Call usbi_alloc_device() to
951          * obtain a new libusb_device structure with reference count 1. Populate
952          * the bus_number and device_address attributes of the new device, and
953          * perform any other internal backend initialization you need to do. At
954          * this point, you should be ready to provide device descriptors and so
955          * on through the get_*_descriptor functions. Finally, call
956          * usbi_sanitize_device() to perform some final sanity checks on the
957          * device. Assuming all of the above succeeded, we can now continue.
958          * If any of the above failed, remember to unreference the device that
959          * was returned by usbi_alloc_device().
960          *
961          * At this stage we have a populated libusb_device structure (either one
962          * that was found earlier, or one that we have just allocated and
963          * populated). This can now be added to the discovered devices list
964          * using discovered_devs_append(). Note that discovered_devs_append()
965          * may reallocate the list, returning a new location for it, and also
966          * note that reallocation can fail. Your backend should handle these
967          * error conditions appropriately.
968          *
969          * This function should not generate any bus I/O and should not block.
970          * If I/O is required (e.g. reading the active configuration value), it is
971          * OK to ignore these suggestions :)
972          *
973          * This function is executed when the user wishes to retrieve a list
974          * of USB devices connected to the system.
975          *
976          * If the backend has hotplug support, this function is not used!
977          *
978          * Return 0 on success, or a LIBUSB_ERROR code on failure.
979          */
980         int (*get_device_list)(struct libusb_context *ctx,
981                 struct discovered_devs **discdevs);
982
983         /* Apps which were written before hotplug support, may listen for
984          * hotplug events on their own and call libusb_get_device_list on
985          * device addition. In this case libusb_get_device_list will likely
986          * return a list without the new device in there, as the hotplug
987          * event thread will still be busy enumerating the device, which may
988          * take a while, or may not even have seen the event yet.
989          *
990          * To avoid this libusb_get_device_list will call this optional
991          * function for backends with hotplug support before copying
992          * ctx->usb_devs to the user. In this function the backend should
993          * ensure any pending hotplug events are fully processed before
994          * returning.
995          *
996          * Optional, should be implemented by backends with hotplug support.
997          */
998         void (*hotplug_poll)(void);
999
1000         /* Wrap a platform-specific device handle for I/O and other USB
1001          * operations. The device handle is preallocated for you.
1002          *
1003          * Your backend should allocate any internal resources required for I/O
1004          * and other operations so that those operations can happen (hopefully)
1005          * without hiccup. This is also a good place to inform libusb that it
1006          * should monitor certain file descriptors related to this device -
1007          * see the usbi_add_event_source() function.
1008          *
1009          * Your backend should also initialize the device structure
1010          * (dev_handle->dev), which is NULL at the beginning of the call.
1011          *
1012          * This function should not generate any bus I/O and should not block.
1013          *
1014          * This function is called when the user attempts to wrap an existing
1015          * platform-specific device handle for a device.
1016          *
1017          * Return:
1018          * - 0 on success
1019          * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1020          * - another LIBUSB_ERROR code on other failure
1021          *
1022          * Do not worry about freeing the handle on failed open, the upper layers
1023          * do this for you.
1024          */
1025         int (*wrap_sys_device)(struct libusb_context *ctx,
1026                 struct libusb_device_handle *dev_handle, intptr_t sys_dev);
1027
1028         /* Open a device for I/O and other USB operations. The device handle
1029          * is preallocated for you, you can retrieve the device in question
1030          * through handle->dev.
1031          *
1032          * Your backend should allocate any internal resources required for I/O
1033          * and other operations so that those operations can happen (hopefully)
1034          * without hiccup. This is also a good place to inform libusb that it
1035          * should monitor certain file descriptors related to this device -
1036          * see the usbi_add_event_source() function.
1037          *
1038          * This function should not generate any bus I/O and should not block.
1039          *
1040          * This function is called when the user attempts to obtain a device
1041          * handle for a device.
1042          *
1043          * Return:
1044          * - 0 on success
1045          * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1046          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
1047          *   discovery
1048          * - another LIBUSB_ERROR code on other failure
1049          *
1050          * Do not worry about freeing the handle on failed open, the upper layers
1051          * do this for you.
1052          */
1053         int (*open)(struct libusb_device_handle *dev_handle);
1054
1055         /* Close a device such that the handle cannot be used again. Your backend
1056          * should destroy any resources that were allocated in the open path.
1057          * This may also be a good place to call usbi_remove_event_source() to
1058          * inform libusb of any event sources associated with this device that
1059          * should no longer be monitored.
1060          *
1061          * This function is called when the user closes a device handle.
1062          */
1063         void (*close)(struct libusb_device_handle *dev_handle);
1064
1065         /* Get the ACTIVE configuration descriptor for a device.
1066          *
1067          * The descriptor should be retrieved from memory, NOT via bus I/O to the
1068          * device. This means that you may have to cache it in a private structure
1069          * during get_device_list enumeration. You may also have to keep track
1070          * of which configuration is active when the user changes it.
1071          *
1072          * This function is expected to write len bytes of data into buffer, which
1073          * is guaranteed to be big enough. If you can only do a partial write,
1074          * return an error code.
1075          *
1076          * This function is expected to return the descriptor in bus-endian format
1077          * (LE).
1078          *
1079          * Return:
1080          * - 0 on success
1081          * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
1082          * - another LIBUSB_ERROR code on other failure
1083          */
1084         int (*get_active_config_descriptor)(struct libusb_device *device,
1085                 void *buffer, size_t len);
1086
1087         /* Get a specific configuration descriptor for a device.
1088          *
1089          * The descriptor should be retrieved from memory, NOT via bus I/O to the
1090          * device. This means that you may have to cache it in a private structure
1091          * during get_device_list enumeration.
1092          *
1093          * The requested descriptor is expressed as a zero-based index (i.e. 0
1094          * indicates that we are requesting the first descriptor). The index does
1095          * not (necessarily) equal the bConfigurationValue of the configuration
1096          * being requested.
1097          *
1098          * This function is expected to write len bytes of data into buffer, which
1099          * is guaranteed to be big enough. If you can only do a partial write,
1100          * return an error code.
1101          *
1102          * This function is expected to return the descriptor in bus-endian format
1103          * (LE).
1104          *
1105          * Return the length read on success or a LIBUSB_ERROR code on failure.
1106          */
1107         int (*get_config_descriptor)(struct libusb_device *device,
1108                 uint8_t config_index, void *buffer, size_t len);
1109
1110         /* Like get_config_descriptor but then by bConfigurationValue instead
1111          * of by index.
1112          *
1113          * Optional, if not present the core will call get_config_descriptor
1114          * for all configs until it finds the desired bConfigurationValue.
1115          *
1116          * Returns a pointer to the raw-descriptor in *buffer, this memory
1117          * is valid as long as device is valid.
1118          *
1119          * Returns the length of the returned raw-descriptor on success,
1120          * or a LIBUSB_ERROR code on failure.
1121          */
1122         int (*get_config_descriptor_by_value)(struct libusb_device *device,
1123                 uint8_t bConfigurationValue, void **buffer);
1124
1125         /* Get the bConfigurationValue for the active configuration for a device.
1126          * Optional. This should only be implemented if you can retrieve it from
1127          * cache (don't generate I/O).
1128          *
1129          * If you cannot retrieve this from cache, either do not implement this
1130          * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
1131          * libusb to retrieve the information through a standard control transfer.
1132          *
1133          * This function must be non-blocking.
1134          * Return:
1135          * - 0 on success
1136          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1137          *   was opened
1138          * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
1139          *   blocking
1140          * - another LIBUSB_ERROR code on other failure.
1141          */
1142         int (*get_configuration)(struct libusb_device_handle *dev_handle, uint8_t *config);
1143
1144         /* Set the active configuration for a device.
1145          *
1146          * A configuration value of -1 should put the device in unconfigured state.
1147          *
1148          * This function can block.
1149          *
1150          * Return:
1151          * - 0 on success
1152          * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
1153          * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
1154          *   configuration cannot be changed)
1155          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1156          *   was opened
1157          * - another LIBUSB_ERROR code on other failure.
1158          */
1159         int (*set_configuration)(struct libusb_device_handle *dev_handle, int config);
1160
1161         /* Claim an interface. When claimed, the application can then perform
1162          * I/O to an interface's endpoints.
1163          *
1164          * This function should not generate any bus I/O and should not block.
1165          * Interface claiming is a logical operation that simply ensures that
1166          * no other drivers/applications are using the interface, and after
1167          * claiming, no other drivers/applications can use the interface because
1168          * we now "own" it.
1169          *
1170          * Return:
1171          * - 0 on success
1172          * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
1173          * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
1174          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1175          *   was opened
1176          * - another LIBUSB_ERROR code on other failure
1177          */
1178         int (*claim_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
1179
1180         /* Release a previously claimed interface.
1181          *
1182          * This function should also generate a SET_INTERFACE control request,
1183          * resetting the alternate setting of that interface to 0. It's OK for
1184          * this function to block as a result.
1185          *
1186          * You will only ever be asked to release an interface which was
1187          * successfully claimed earlier.
1188          *
1189          * Return:
1190          * - 0 on success
1191          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1192          *   was opened
1193          * - another LIBUSB_ERROR code on other failure
1194          */
1195         int (*release_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
1196
1197         /* Set the alternate setting for an interface.
1198          *
1199          * You will only ever be asked to set the alternate setting for an
1200          * interface which was successfully claimed earlier.
1201          *
1202          * It's OK for this function to block.
1203          *
1204          * Return:
1205          * - 0 on success
1206          * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
1207          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1208          *   was opened
1209          * - another LIBUSB_ERROR code on other failure
1210          */
1211         int (*set_interface_altsetting)(struct libusb_device_handle *dev_handle,
1212                 uint8_t interface_number, uint8_t altsetting);
1213
1214         /* Clear a halt/stall condition on an endpoint.
1215          *
1216          * It's OK for this function to block.
1217          *
1218          * Return:
1219          * - 0 on success
1220          * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1221          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1222          *   was opened
1223          * - another LIBUSB_ERROR code on other failure
1224          */
1225         int (*clear_halt)(struct libusb_device_handle *dev_handle,
1226                 unsigned char endpoint);
1227
1228         /* Perform a USB port reset to reinitialize a device. Optional.
1229          *
1230          * If possible, the device handle should still be usable after the reset
1231          * completes, assuming that the device descriptors did not change during
1232          * reset and all previous interface state can be restored.
1233          *
1234          * If something changes, or you cannot easily locate/verify the reset
1235          * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
1236          * to close the old handle and re-enumerate the device.
1237          *
1238          * Return:
1239          * - 0 on success
1240          * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
1241          *   has been disconnected since it was opened
1242          * - another LIBUSB_ERROR code on other failure
1243          */
1244         int (*reset_device)(struct libusb_device_handle *dev_handle);
1245
1246         /* Alloc num_streams usb3 bulk streams on the passed in endpoints */
1247         int (*alloc_streams)(struct libusb_device_handle *dev_handle,
1248                 uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
1249
1250         /* Free usb3 bulk streams allocated with alloc_streams */
1251         int (*free_streams)(struct libusb_device_handle *dev_handle,
1252                 unsigned char *endpoints, int num_endpoints);
1253
1254         /* Allocate persistent DMA memory for the given device, suitable for
1255          * zerocopy. May return NULL on failure. Optional to implement.
1256          */
1257         void *(*dev_mem_alloc)(struct libusb_device_handle *handle, size_t len);
1258
1259         /* Free memory allocated by dev_mem_alloc. */
1260         int (*dev_mem_free)(struct libusb_device_handle *handle, void *buffer,
1261                 size_t len);
1262
1263         /* Determine if a kernel driver is active on an interface. Optional.
1264          *
1265          * The presence of a kernel driver on an interface indicates that any
1266          * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
1267          *
1268          * Return:
1269          * - 0 if no driver is active
1270          * - 1 if a driver is active
1271          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1272          *   was opened
1273          * - another LIBUSB_ERROR code on other failure
1274          */
1275         int (*kernel_driver_active)(struct libusb_device_handle *dev_handle,
1276                 uint8_t interface_number);
1277
1278         /* Detach a kernel driver from an interface. Optional.
1279          *
1280          * After detaching a kernel driver, the interface should be available
1281          * for claim.
1282          *
1283          * Return:
1284          * - 0 on success
1285          * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1286          * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1287          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1288          *   was opened
1289          * - another LIBUSB_ERROR code on other failure
1290          */
1291         int (*detach_kernel_driver)(struct libusb_device_handle *dev_handle,
1292                 uint8_t interface_number);
1293
1294         /* Attach a kernel driver to an interface. Optional.
1295          *
1296          * Reattach a kernel driver to the device.
1297          *
1298          * Return:
1299          * - 0 on success
1300          * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1301          * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1302          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1303          *   was opened
1304          * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
1305          *   preventing reattachment
1306          * - another LIBUSB_ERROR code on other failure
1307          */
1308         int (*attach_kernel_driver)(struct libusb_device_handle *dev_handle,
1309                 uint8_t interface_number);
1310
1311         /* Destroy a device. Optional.
1312          *
1313          * This function is called when the last reference to a device is
1314          * destroyed. It should free any resources allocated in the get_device_list
1315          * path.
1316          */
1317         void (*destroy_device)(struct libusb_device *dev);
1318
1319         /* Submit a transfer. Your implementation should take the transfer,
1320          * morph it into whatever form your platform requires, and submit it
1321          * asynchronously.
1322          *
1323          * This function must not block.
1324          *
1325          * This function gets called with the flying_transfers_lock locked!
1326          *
1327          * Return:
1328          * - 0 on success
1329          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1330          * - another LIBUSB_ERROR code on other failure
1331          */
1332         int (*submit_transfer)(struct usbi_transfer *itransfer);
1333
1334         /* Cancel a previously submitted transfer.
1335          *
1336          * This function must not block. The transfer cancellation must complete
1337          * later, resulting in a call to usbi_handle_transfer_cancellation()
1338          * from the context of handle_events.
1339          */
1340         int (*cancel_transfer)(struct usbi_transfer *itransfer);
1341
1342         /* Clear a transfer as if it has completed or cancelled, but do not
1343          * report any completion/cancellation to the library. You should free
1344          * all private data from the transfer as if you were just about to report
1345          * completion or cancellation.
1346          *
1347          * This function might seem a bit out of place. It is used when libusb
1348          * detects a disconnected device - it calls this function for all pending
1349          * transfers before reporting completion (with the disconnect code) to
1350          * the user. Maybe we can improve upon this internal interface in future.
1351          */
1352         void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
1353
1354         /* Handle any pending events on event sources. Optional.
1355          *
1356          * Provide this function when event sources directly indicate device
1357          * or transfer activity. If your backend does not have such event sources,
1358          * implement the handle_transfer_completion function below.
1359          *
1360          * This involves monitoring any active transfers and processing their
1361          * completion or cancellation.
1362          *
1363          * The function is passed a pointer that represents platform-specific
1364          * data for monitoring event sources (size count). This data is to be
1365          * (re)allocated as necessary when event sources are modified.
1366          * The num_ready parameter indicates the number of event sources that
1367          * have reported events. This should be enough information for you to
1368          * determine which actions need to be taken on the currently active
1369          * transfers.
1370          *
1371          * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1372          * For completed transfers, call usbi_handle_transfer_completion().
1373          * For control/bulk/interrupt transfers, populate the "transferred"
1374          * element of the appropriate usbi_transfer structure before calling the
1375          * above functions. For isochronous transfers, populate the status and
1376          * transferred fields of the iso packet descriptors of the transfer.
1377          *
1378          * This function should also be able to detect disconnection of the
1379          * device, reporting that situation with usbi_handle_disconnect().
1380          *
1381          * When processing an event related to a transfer, you probably want to
1382          * take usbi_transfer.lock to prevent races. See the documentation for
1383          * the usbi_transfer structure.
1384          *
1385          * Return 0 on success, or a LIBUSB_ERROR code on failure.
1386          */
1387         int (*handle_events)(struct libusb_context *ctx,
1388                 void *event_data, unsigned int count, unsigned int num_ready);
1389
1390         /* Handle transfer completion. Optional.
1391          *
1392          * Provide this function when there are no event sources available that
1393          * directly indicate device or transfer activity. If your backend does
1394          * have such event sources, implement the handle_events function above.
1395          *
1396          * Your backend must tell the library when a transfer has completed by
1397          * calling usbi_signal_transfer_completion(). You should store any private
1398          * information about the transfer and its completion status in the transfer's
1399          * private backend data.
1400          *
1401          * During event handling, this function will be called on each transfer for
1402          * which usbi_signal_transfer_completion() was called.
1403          *
1404          * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1405          * For completed transfers, call usbi_handle_transfer_completion().
1406          * For control/bulk/interrupt transfers, populate the "transferred"
1407          * element of the appropriate usbi_transfer structure before calling the
1408          * above functions. For isochronous transfers, populate the status and
1409          * transferred fields of the iso packet descriptors of the transfer.
1410          *
1411          * Return 0 on success, or a LIBUSB_ERROR code on failure.
1412          */
1413         int (*handle_transfer_completion)(struct usbi_transfer *itransfer);
1414
1415         /* Number of bytes to reserve for per-context private backend data.
1416          * This private data area is accessible by calling
1417          * usbi_get_context_priv() on the libusb_context instance.
1418          */
1419         size_t context_priv_size;
1420
1421         /* Number of bytes to reserve for per-device private backend data.
1422          * This private data area is accessible by calling
1423          * usbi_get_device_priv() on the libusb_device instance.
1424          */
1425         size_t device_priv_size;
1426
1427         /* Number of bytes to reserve for per-handle private backend data.
1428          * This private data area is accessible by calling
1429          * usbi_get_device_handle_priv() on the libusb_device_handle instance.
1430          */
1431         size_t device_handle_priv_size;
1432
1433         /* Number of bytes to reserve for per-transfer private backend data.
1434          * This private data area is accessible by calling
1435          * usbi_get_transfer_priv() on the usbi_transfer instance.
1436          */
1437         size_t transfer_priv_size;
1438 };
1439
1440 extern const struct usbi_os_backend usbi_backend;
1441
1442 #define for_each_context(c) \
1443         for_each_helper(c, &active_contexts_list, struct libusb_context)
1444
1445 #define for_each_device(ctx, d) \
1446         for_each_helper(d, &(ctx)->usb_devs, struct libusb_device)
1447
1448 #define for_each_device_safe(ctx, d, n) \
1449         for_each_safe_helper(d, n, &(ctx)->usb_devs, struct libusb_device)
1450
1451 #define for_each_open_device(ctx, h) \
1452         for_each_helper(h, &(ctx)->open_devs, struct libusb_device_handle)
1453
1454 #define __for_each_transfer(list, t) \
1455         for_each_helper(t, (list), struct usbi_transfer)
1456
1457 #define for_each_transfer(ctx, t) \
1458         __for_each_transfer(&(ctx)->flying_transfers, t)
1459
1460 #define __for_each_transfer_safe(list, t, n) \
1461         for_each_safe_helper(t, n, (list), struct usbi_transfer)
1462
1463 #define for_each_transfer_safe(ctx, t, n) \
1464         __for_each_transfer_safe(&(ctx)->flying_transfers, t, n)
1465
1466 #define __for_each_completed_transfer_safe(list, t, n) \
1467         list_for_each_entry_safe(t, n, (list), completed_list, struct usbi_transfer)
1468
1469 #define for_each_event_source(ctx, e) \
1470         for_each_helper(e, &(ctx)->event_sources, struct usbi_event_source)
1471
1472 #define for_each_removed_event_source(ctx, e) \
1473         for_each_helper(e, &(ctx)->removed_event_sources, struct usbi_event_source)
1474
1475 #define for_each_removed_event_source_safe(ctx, e, n) \
1476         for_each_safe_helper(e, n, &(ctx)->removed_event_sources, struct usbi_event_source)
1477
1478 #define for_each_hotplug_cb(ctx, c) \
1479         for_each_helper(c, &(ctx)->hotplug_cbs, struct usbi_hotplug_callback)
1480
1481 #define for_each_hotplug_cb_safe(ctx, c, n) \
1482         for_each_safe_helper(c, n, &(ctx)->hotplug_cbs, struct usbi_hotplug_callback)
1483
1484 #ifdef __cplusplus
1485 }
1486 #endif
1487
1488 #endif