Windows: Partial fix for data race in composite_copy_transfer_data
[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)      (DEVICE_CTX((handle)->dev))
333 #define TRANSFER_CTX(transfer)  (HANDLE_CTX((transfer)->dev_handle))
334 #define ITRANSFER_CTX(itransfer) \
335         (TRANSFER_CTX(USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)))
336
337 #define IS_EPIN(ep)             (0 != ((ep) & LIBUSB_ENDPOINT_IN))
338 #define IS_EPOUT(ep)            (!IS_EPIN(ep))
339 #define IS_XFERIN(xfer)         (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
340 #define IS_XFEROUT(xfer)        (!IS_XFERIN(xfer))
341
342 struct libusb_context {
343 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
344         enum libusb_log_level debug;
345         int debug_fixed;
346         libusb_log_cb log_handler;
347 #endif
348
349         /* used for signalling occurrence of an internal event. */
350         usbi_event_t event;
351
352 #ifdef HAVE_OS_TIMER
353         /* used for timeout handling, if supported by OS.
354          * this timer is maintained to trigger on the next pending timeout */
355         usbi_timer_t timer;
356 #endif
357
358         struct list_head usb_devs;
359         usbi_mutex_t usb_devs_lock;
360
361         /* A list of open handles. Backends are free to traverse this if required.
362          */
363         struct list_head open_devs;
364         usbi_mutex_t open_devs_lock;
365
366         /* A list of registered hotplug callbacks */
367         struct list_head hotplug_cbs;
368         libusb_hotplug_callback_handle next_hotplug_cb_handle;
369         usbi_mutex_t hotplug_cbs_lock;
370
371         /* A flag to indicate that the context is ready for hotplug notifications */
372         usbi_atomic_t hotplug_ready;
373
374         /* this is a list of in-flight transfer handles, sorted by timeout
375          * expiration. URBs to timeout the soonest are placed at the beginning of
376          * the list, URBs that will time out later are placed after, and urbs with
377          * infinite timeout are always placed at the very end. */
378         struct list_head flying_transfers;
379         /* Note paths taking both this and usbi_transfer->lock must always
380          * take this lock first */
381         usbi_mutex_t flying_transfers_lock;
382
383 #if !defined(PLATFORM_WINDOWS)
384         /* user callbacks for pollfd changes */
385         libusb_pollfd_added_cb fd_added_cb;
386         libusb_pollfd_removed_cb fd_removed_cb;
387         void *fd_cb_user_data;
388 #endif
389
390         /* ensures that only one thread is handling events at any one time */
391         usbi_mutex_t events_lock;
392
393         /* used to see if there is an active thread doing event handling */
394         int event_handler_active;
395
396         /* A thread-local storage key to track which thread is performing event
397          * handling */
398         usbi_tls_key_t event_handling_key;
399
400         /* used to wait for event completion in threads other than the one that is
401          * event handling */
402         usbi_mutex_t event_waiters_lock;
403         usbi_cond_t event_waiters_cond;
404
405         /* A lock to protect internal context event data. */
406         usbi_mutex_t event_data_lock;
407
408         /* A bitmask of flags that are set to indicate specific events that need to
409          * be handled. Protected by event_data_lock. */
410         unsigned int event_flags;
411
412         /* A counter that is set when we want to interrupt and prevent event handling,
413          * in order to safely close a device. Protected by event_data_lock. */
414         unsigned int device_close;
415
416         /* A list of currently active event sources. Protected by event_data_lock. */
417         struct list_head event_sources;
418
419         /* A list of event sources that have been removed since the last time
420          * event sources were waited on. Protected by event_data_lock. */
421         struct list_head removed_event_sources;
422
423         /* A pointer and count to platform-specific data used for monitoring event
424          * sources. Only accessed during event handling. */
425         void *event_data;
426         unsigned int event_data_cnt;
427
428         /* A list of pending hotplug messages. Protected by event_data_lock. */
429         struct list_head hotplug_msgs;
430
431         /* A list of pending completed transfers. Protected by event_data_lock. */
432         struct list_head completed_transfers;
433
434         struct list_head list;
435 };
436
437 extern struct libusb_context *usbi_default_context;
438
439 extern struct list_head active_contexts_list;
440 extern usbi_mutex_static_t active_contexts_lock;
441
442 static inline struct libusb_context *usbi_get_context(struct libusb_context *ctx)
443 {
444         return ctx ? ctx : usbi_default_context;
445 }
446
447 enum usbi_event_flags {
448         /* The list of event sources has been modified */
449         USBI_EVENT_EVENT_SOURCES_MODIFIED = 1U << 0,
450
451         /* The user has interrupted the event handler */
452         USBI_EVENT_USER_INTERRUPT = 1U << 1,
453
454         /* A hotplug callback deregistration is pending */
455         USBI_EVENT_HOTPLUG_CB_DEREGISTERED = 1U << 2,
456
457         /* One or more hotplug messages are pending */
458         USBI_EVENT_HOTPLUG_MSG_PENDING = 1U << 3,
459
460         /* One or more completed transfers are pending */
461         USBI_EVENT_TRANSFER_COMPLETED = 1U << 4,
462
463         /* A device is in the process of being closed */
464         USBI_EVENT_DEVICE_CLOSE = 1U << 5,
465 };
466
467 /* Macros for managing event handling state */
468 static inline int usbi_handling_events(struct libusb_context *ctx)
469 {
470         return usbi_tls_key_get(ctx->event_handling_key) != NULL;
471 }
472
473 static inline void usbi_start_event_handling(struct libusb_context *ctx)
474 {
475         usbi_tls_key_set(ctx->event_handling_key, ctx);
476 }
477
478 static inline void usbi_end_event_handling(struct libusb_context *ctx)
479 {
480         usbi_tls_key_set(ctx->event_handling_key, NULL);
481 }
482
483 struct libusb_device {
484         usbi_atomic_t refcnt;
485
486         struct libusb_context *ctx;
487         struct libusb_device *parent_dev;
488
489         uint8_t bus_number;
490         uint8_t port_number;
491         uint8_t device_address;
492         enum libusb_speed speed;
493
494         struct list_head list;
495         unsigned long session_data;
496
497         struct libusb_device_descriptor device_descriptor;
498         usbi_atomic_t attached;
499 };
500
501 struct libusb_device_handle {
502         /* lock protects claimed_interfaces */
503         usbi_mutex_t lock;
504         unsigned long claimed_interfaces;
505
506         struct list_head list;
507         struct libusb_device *dev;
508         int auto_detach_kernel_driver;
509 };
510
511 /* Function called by backend during device initialization to convert
512  * multi-byte fields in the device descriptor to host-endian format.
513  */
514 static inline void usbi_localize_device_descriptor(struct libusb_device_descriptor *desc)
515 {
516         desc->bcdUSB = libusb_le16_to_cpu(desc->bcdUSB);
517         desc->idVendor = libusb_le16_to_cpu(desc->idVendor);
518         desc->idProduct = libusb_le16_to_cpu(desc->idProduct);
519         desc->bcdDevice = libusb_le16_to_cpu(desc->bcdDevice);
520 }
521
522 #ifdef HAVE_CLOCK_GETTIME
523 static inline void usbi_get_monotonic_time(struct timespec *tp)
524 {
525         ASSERT_EQ(clock_gettime(CLOCK_MONOTONIC, tp), 0);
526 }
527 static inline void usbi_get_real_time(struct timespec *tp)
528 {
529         ASSERT_EQ(clock_gettime(CLOCK_REALTIME, tp), 0);
530 }
531 #else
532 /* If the platform doesn't provide the clock_gettime() function, the backend
533  * must provide its own clock implementations.  Two clock functions are
534  * required:
535  *
536  *   usbi_get_monotonic_time(): returns the time since an unspecified starting
537  *                              point (usually boot) that is monotonically
538  *                              increasing.
539  *   usbi_get_real_time(): returns the time since system epoch.
540  */
541 void usbi_get_monotonic_time(struct timespec *tp);
542 void usbi_get_real_time(struct timespec *tp);
543 #endif
544
545 /* in-memory transfer layout:
546  *
547  * 1. os private data
548  * 2. struct usbi_transfer
549  * 3. struct libusb_transfer (which includes iso packets) [variable size]
550  *
551  * from a libusb_transfer, you can get the usbi_transfer by rewinding the
552  * appropriate number of bytes.
553  */
554
555 struct usbi_transfer {
556         int num_iso_packets;
557         struct list_head list;
558         struct list_head completed_list;
559         struct timespec timeout;
560         int transferred;
561         uint32_t stream_id;
562         uint32_t state_flags;   /* Protected by usbi_transfer->lock */
563         uint32_t timeout_flags; /* Protected by the flying_stransfers_lock */
564
565         /* this lock is held during libusb_submit_transfer() and
566          * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
567          * cancellation, submission-during-cancellation, etc). the OS backend
568          * should also take this lock in the handle_events path, to prevent the user
569          * cancelling the transfer from another thread while you are processing
570          * its completion (presumably there would be races within your OS backend
571          * if this were possible).
572          * Note paths taking both this and the flying_transfers_lock must
573          * always take the flying_transfers_lock first */
574         usbi_mutex_t lock;
575
576         void *priv;
577 };
578
579 enum usbi_transfer_state_flags {
580         /* Transfer successfully submitted by backend */
581         USBI_TRANSFER_IN_FLIGHT = 1U << 0,
582
583         /* Cancellation was requested via libusb_cancel_transfer() */
584         USBI_TRANSFER_CANCELLING = 1U << 1,
585
586         /* Operation on the transfer failed because the device disappeared */
587         USBI_TRANSFER_DEVICE_DISAPPEARED = 1U << 2,
588 };
589
590 enum usbi_transfer_timeout_flags {
591         /* Set by backend submit_transfer() if the OS handles timeout */
592         USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1U << 0,
593
594         /* The transfer timeout has been handled */
595         USBI_TRANSFER_TIMEOUT_HANDLED = 1U << 1,
596
597         /* The transfer timeout was successfully processed */
598         USBI_TRANSFER_TIMED_OUT = 1U << 2,
599 };
600
601 #define USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer)     \
602         ((struct libusb_transfer *)                     \
603          ((unsigned char *)(itransfer)                  \
604           + PTR_ALIGN(sizeof(struct usbi_transfer))))
605 #define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)      \
606         ((struct usbi_transfer *)                       \
607          ((unsigned char *)(transfer)                   \
608           - PTR_ALIGN(sizeof(struct usbi_transfer))))
609
610 #ifdef _MSC_VER
611 #pragma pack(push, 1)
612 #endif
613
614 /* All standard descriptors have these 2 fields in common */
615 struct usbi_descriptor_header {
616         uint8_t  bLength;
617         uint8_t  bDescriptorType;
618 } LIBUSB_PACKED;
619
620 struct usbi_device_descriptor {
621         uint8_t  bLength;
622         uint8_t  bDescriptorType;
623         uint16_t bcdUSB;
624         uint8_t  bDeviceClass;
625         uint8_t  bDeviceSubClass;
626         uint8_t  bDeviceProtocol;
627         uint8_t  bMaxPacketSize0;
628         uint16_t idVendor;
629         uint16_t idProduct;
630         uint16_t bcdDevice;
631         uint8_t  iManufacturer;
632         uint8_t  iProduct;
633         uint8_t  iSerialNumber;
634         uint8_t  bNumConfigurations;
635 } LIBUSB_PACKED;
636
637 struct usbi_configuration_descriptor {
638         uint8_t  bLength;
639         uint8_t  bDescriptorType;
640         uint16_t wTotalLength;
641         uint8_t  bNumInterfaces;
642         uint8_t  bConfigurationValue;
643         uint8_t  iConfiguration;
644         uint8_t  bmAttributes;
645         uint8_t  bMaxPower;
646 } LIBUSB_PACKED;
647
648 struct usbi_interface_descriptor {
649         uint8_t  bLength;
650         uint8_t  bDescriptorType;
651         uint8_t  bInterfaceNumber;
652         uint8_t  bAlternateSetting;
653         uint8_t  bNumEndpoints;
654         uint8_t  bInterfaceClass;
655         uint8_t  bInterfaceSubClass;
656         uint8_t  bInterfaceProtocol;
657         uint8_t  iInterface;
658 } LIBUSB_PACKED;
659
660 struct usbi_string_descriptor {
661         uint8_t  bLength;
662         uint8_t  bDescriptorType;
663         uint16_t wData[ZERO_SIZED_ARRAY];
664 } LIBUSB_PACKED;
665
666 struct usbi_bos_descriptor {
667         uint8_t  bLength;
668         uint8_t  bDescriptorType;
669         uint16_t wTotalLength;
670         uint8_t  bNumDeviceCaps;
671 } LIBUSB_PACKED;
672
673 #ifdef _MSC_VER
674 #pragma pack(pop)
675 #endif
676
677 union usbi_config_desc_buf {
678         struct usbi_configuration_descriptor desc;
679         uint8_t buf[LIBUSB_DT_CONFIG_SIZE];
680         uint16_t align;         /* Force 2-byte alignment */
681 };
682
683 union usbi_string_desc_buf {
684         struct usbi_string_descriptor desc;
685         uint8_t buf[255];       /* Some devices choke on size > 255 */
686         uint16_t align;         /* Force 2-byte alignment */
687 };
688
689 union usbi_bos_desc_buf {
690         struct usbi_bos_descriptor desc;
691         uint8_t buf[LIBUSB_DT_BOS_SIZE];
692         uint16_t align;         /* Force 2-byte alignment */
693 };
694
695 enum usbi_hotplug_flags {
696         /* This callback is interested in device arrivals */
697         USBI_HOTPLUG_DEVICE_ARRIVED = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
698
699         /* This callback is interested in device removals */
700         USBI_HOTPLUG_DEVICE_LEFT = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT,
701
702         /* IMPORTANT: The values for the below entries must start *after*
703          * the highest value of the above entries!!!
704          */
705
706         /* The vendor_id field is valid for matching */
707         USBI_HOTPLUG_VENDOR_ID_VALID = (1U << 3),
708
709         /* The product_id field is valid for matching */
710         USBI_HOTPLUG_PRODUCT_ID_VALID = (1U << 4),
711
712         /* The dev_class field is valid for matching */
713         USBI_HOTPLUG_DEV_CLASS_VALID = (1U << 5),
714
715         /* This callback has been unregistered and needs to be freed */
716         USBI_HOTPLUG_NEEDS_FREE = (1U << 6),
717 };
718
719 struct usbi_hotplug_callback {
720         /* Flags that control how this callback behaves */
721         uint8_t flags;
722
723         /* Vendor ID to match (if flags says this is valid) */
724         uint16_t vendor_id;
725
726         /* Product ID to match (if flags says this is valid) */
727         uint16_t product_id;
728
729         /* Device class to match (if flags says this is valid) */
730         uint8_t dev_class;
731
732         /* Callback function to invoke for matching event/device */
733         libusb_hotplug_callback_fn cb;
734
735         /* Handle for this callback (used to match on deregister) */
736         libusb_hotplug_callback_handle handle;
737
738         /* User data that will be passed to the callback function */
739         void *user_data;
740
741         /* List this callback is registered in (ctx->hotplug_cbs) */
742         struct list_head list;
743 };
744
745 struct usbi_hotplug_message {
746         /* The hotplug event that occurred */
747         libusb_hotplug_event event;
748
749         /* The device for which this hotplug event occurred */
750         struct libusb_device *device;
751
752         /* List this message is contained in (ctx->hotplug_msgs) */
753         struct list_head list;
754 };
755
756 /* shared data and functions */
757
758 void usbi_hotplug_init(struct libusb_context *ctx);
759 void usbi_hotplug_exit(struct libusb_context *ctx);
760 void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
761         libusb_hotplug_event event);
762 void usbi_hotplug_process(struct libusb_context *ctx, struct list_head *hotplug_msgs);
763
764 int usbi_io_init(struct libusb_context *ctx);
765 void usbi_io_exit(struct libusb_context *ctx);
766
767 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
768         unsigned long session_id);
769 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
770         unsigned long session_id);
771 int usbi_sanitize_device(struct libusb_device *dev);
772 void usbi_handle_disconnect(struct libusb_device_handle *dev_handle);
773
774 int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
775         enum libusb_transfer_status status);
776 int usbi_handle_transfer_cancellation(struct usbi_transfer *itransfer);
777 void usbi_signal_transfer_completion(struct usbi_transfer *itransfer);
778
779 void usbi_connect_device(struct libusb_device *dev);
780 void usbi_disconnect_device(struct libusb_device *dev);
781
782 struct usbi_event_source {
783         struct usbi_event_source_data {
784                 usbi_os_handle_t os_handle;
785                 short poll_events;
786         } data;
787         struct list_head list;
788 };
789
790 int usbi_add_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle,
791         short poll_events);
792 void usbi_remove_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle);
793
794 struct usbi_option {
795   int is_set;
796   union {
797     int ival;
798   } arg;
799 };
800
801 /* OS event abstraction */
802
803 int usbi_create_event(usbi_event_t *event);
804 void usbi_destroy_event(usbi_event_t *event);
805 void usbi_signal_event(usbi_event_t *event);
806 void usbi_clear_event(usbi_event_t *event);
807
808 #ifdef HAVE_OS_TIMER
809 int usbi_create_timer(usbi_timer_t *timer);
810 void usbi_destroy_timer(usbi_timer_t *timer);
811 int usbi_arm_timer(usbi_timer_t *timer, const struct timespec *timeout);
812 int usbi_disarm_timer(usbi_timer_t *timer);
813 #endif
814
815 static inline int usbi_using_timer(struct libusb_context *ctx)
816 {
817 #ifdef HAVE_OS_TIMER
818         return usbi_timer_valid(&ctx->timer);
819 #else
820         UNUSED(ctx);
821         return 0;
822 #endif
823 }
824
825 struct usbi_reported_events {
826         union {
827                 struct {
828                         unsigned int event_triggered:1;
829 #ifdef HAVE_OS_TIMER
830                         unsigned int timer_triggered:1;
831 #endif
832                 };
833                 unsigned int event_bits;
834         };
835         void *event_data;
836         unsigned int event_data_count;
837         unsigned int num_ready;
838 };
839
840 int usbi_alloc_event_data(struct libusb_context *ctx);
841 int usbi_wait_for_events(struct libusb_context *ctx,
842         struct usbi_reported_events *reported_events, int timeout_ms);
843
844 /* accessor functions for structure private data */
845
846 static inline void *usbi_get_context_priv(struct libusb_context *ctx)
847 {
848         return (unsigned char *)ctx + PTR_ALIGN(sizeof(*ctx));
849 }
850
851 static inline void *usbi_get_device_priv(struct libusb_device *dev)
852 {
853         return (unsigned char *)dev + PTR_ALIGN(sizeof(*dev));
854 }
855
856 static inline void *usbi_get_device_handle_priv(struct libusb_device_handle *dev_handle)
857 {
858         return (unsigned char *)dev_handle + PTR_ALIGN(sizeof(*dev_handle));
859 }
860
861 static inline void *usbi_get_transfer_priv(struct usbi_transfer *itransfer)
862 {
863         return itransfer->priv;
864 }
865
866 /* device discovery */
867
868 /* we traverse usbfs without knowing how many devices we are going to find.
869  * so we create this discovered_devs model which is similar to a linked-list
870  * which grows when required. it can be freed once discovery has completed,
871  * eliminating the need for a list node in the libusb_device structure
872  * itself. */
873 struct discovered_devs {
874         size_t len;
875         size_t capacity;
876         struct libusb_device *devices[ZERO_SIZED_ARRAY];
877 };
878
879 struct discovered_devs *discovered_devs_append(
880         struct discovered_devs *discdevs, struct libusb_device *dev);
881
882 /* OS abstraction */
883
884 /* This is the interface that OS backends need to implement.
885  * All fields are mandatory, except ones explicitly noted as optional. */
886 struct usbi_os_backend {
887         /* A human-readable name for your backend, e.g. "Linux usbfs" */
888         const char *name;
889
890         /* Binary mask for backend specific capabilities */
891         uint32_t caps;
892
893         /* Perform initialization of your backend. You might use this function
894          * to determine specific capabilities of the system, allocate required
895          * data structures for later, etc.
896          *
897          * This function is called when a libusb user initializes the library
898          * prior to use. Mutual exclusion with other init and exit calls is
899          * guaranteed when this function is called.
900          *
901          * Return 0 on success, or a LIBUSB_ERROR code on failure.
902          */
903         int (*init)(struct libusb_context *ctx);
904
905         /* Deinitialization. Optional. This function should destroy anything
906          * that was set up by init.
907          *
908          * This function is called when the user deinitializes the library.
909          * Mutual exclusion with other init and exit calls is guaranteed when
910          * this function is called.
911          */
912         void (*exit)(struct libusb_context *ctx);
913
914         /* Set a backend-specific option. Optional.
915          *
916          * This function is called when the user calls libusb_set_option() and
917          * the option is not handled by the core library.
918          *
919          * Return 0 on success, or a LIBUSB_ERROR code on failure.
920          */
921         int (*set_option)(struct libusb_context *ctx, enum libusb_option option,
922                 va_list args);
923
924         /* Enumerate all the USB devices on the system, returning them in a list
925          * of discovered devices.
926          *
927          * Your implementation should enumerate all devices on the system,
928          * regardless of whether they have been seen before or not.
929          *
930          * When you have found a device, compute a session ID for it. The session
931          * ID should uniquely represent that particular device for that particular
932          * connection session since boot (i.e. if you disconnect and reconnect a
933          * device immediately after, it should be assigned a different session ID).
934          * If your OS cannot provide a unique session ID as described above,
935          * presenting a session ID of (bus_number << 8 | device_address) should
936          * be sufficient. Bus numbers and device addresses wrap and get reused,
937          * but that is an unlikely case.
938          *
939          * After computing a session ID for a device, call
940          * usbi_get_device_by_session_id(). This function checks if libusb already
941          * knows about the device, and if so, it provides you with a reference
942          * to a libusb_device structure for it.
943          *
944          * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
945          * a new device structure for the device. Call usbi_alloc_device() to
946          * obtain a new libusb_device structure with reference count 1. Populate
947          * the bus_number and device_address attributes of the new device, and
948          * perform any other internal backend initialization you need to do. At
949          * this point, you should be ready to provide device descriptors and so
950          * on through the get_*_descriptor functions. Finally, call
951          * usbi_sanitize_device() to perform some final sanity checks on the
952          * device. Assuming all of the above succeeded, we can now continue.
953          * If any of the above failed, remember to unreference the device that
954          * was returned by usbi_alloc_device().
955          *
956          * At this stage we have a populated libusb_device structure (either one
957          * that was found earlier, or one that we have just allocated and
958          * populated). This can now be added to the discovered devices list
959          * using discovered_devs_append(). Note that discovered_devs_append()
960          * may reallocate the list, returning a new location for it, and also
961          * note that reallocation can fail. Your backend should handle these
962          * error conditions appropriately.
963          *
964          * This function should not generate any bus I/O and should not block.
965          * If I/O is required (e.g. reading the active configuration value), it is
966          * OK to ignore these suggestions :)
967          *
968          * This function is executed when the user wishes to retrieve a list
969          * of USB devices connected to the system.
970          *
971          * If the backend has hotplug support, this function is not used!
972          *
973          * Return 0 on success, or a LIBUSB_ERROR code on failure.
974          */
975         int (*get_device_list)(struct libusb_context *ctx,
976                 struct discovered_devs **discdevs);
977
978         /* Apps which were written before hotplug support, may listen for
979          * hotplug events on their own and call libusb_get_device_list on
980          * device addition. In this case libusb_get_device_list will likely
981          * return a list without the new device in there, as the hotplug
982          * event thread will still be busy enumerating the device, which may
983          * take a while, or may not even have seen the event yet.
984          *
985          * To avoid this libusb_get_device_list will call this optional
986          * function for backends with hotplug support before copying
987          * ctx->usb_devs to the user. In this function the backend should
988          * ensure any pending hotplug events are fully processed before
989          * returning.
990          *
991          * Optional, should be implemented by backends with hotplug support.
992          */
993         void (*hotplug_poll)(void);
994
995         /* Wrap a platform-specific device handle for I/O and other USB
996          * operations. The device handle is preallocated for you.
997          *
998          * Your backend should allocate any internal resources required for I/O
999          * and other operations so that those operations can happen (hopefully)
1000          * without hiccup. This is also a good place to inform libusb that it
1001          * should monitor certain file descriptors related to this device -
1002          * see the usbi_add_event_source() function.
1003          *
1004          * Your backend should also initialize the device structure
1005          * (dev_handle->dev), which is NULL at the beginning of the call.
1006          *
1007          * This function should not generate any bus I/O and should not block.
1008          *
1009          * This function is called when the user attempts to wrap an existing
1010          * platform-specific device handle for a device.
1011          *
1012          * Return:
1013          * - 0 on success
1014          * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1015          * - another LIBUSB_ERROR code on other failure
1016          *
1017          * Do not worry about freeing the handle on failed open, the upper layers
1018          * do this for you.
1019          */
1020         int (*wrap_sys_device)(struct libusb_context *ctx,
1021                 struct libusb_device_handle *dev_handle, intptr_t sys_dev);
1022
1023         /* Open a device for I/O and other USB operations. The device handle
1024          * is preallocated for you, you can retrieve the device in question
1025          * through handle->dev.
1026          *
1027          * Your backend should allocate any internal resources required for I/O
1028          * and other operations so that those operations can happen (hopefully)
1029          * without hiccup. This is also a good place to inform libusb that it
1030          * should monitor certain file descriptors related to this device -
1031          * see the usbi_add_event_source() function.
1032          *
1033          * This function should not generate any bus I/O and should not block.
1034          *
1035          * This function is called when the user attempts to obtain a device
1036          * handle for a device.
1037          *
1038          * Return:
1039          * - 0 on success
1040          * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1041          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
1042          *   discovery
1043          * - another LIBUSB_ERROR code on other failure
1044          *
1045          * Do not worry about freeing the handle on failed open, the upper layers
1046          * do this for you.
1047          */
1048         int (*open)(struct libusb_device_handle *dev_handle);
1049
1050         /* Close a device such that the handle cannot be used again. Your backend
1051          * should destroy any resources that were allocated in the open path.
1052          * This may also be a good place to call usbi_remove_event_source() to
1053          * inform libusb of any event sources associated with this device that
1054          * should no longer be monitored.
1055          *
1056          * This function is called when the user closes a device handle.
1057          */
1058         void (*close)(struct libusb_device_handle *dev_handle);
1059
1060         /* Get the ACTIVE configuration descriptor for a device.
1061          *
1062          * The descriptor should be retrieved from memory, NOT via bus I/O to the
1063          * device. This means that you may have to cache it in a private structure
1064          * during get_device_list enumeration. You may also have to keep track
1065          * of which configuration is active when the user changes it.
1066          *
1067          * This function is expected to write len bytes of data into buffer, which
1068          * is guaranteed to be big enough. If you can only do a partial write,
1069          * return an error code.
1070          *
1071          * This function is expected to return the descriptor in bus-endian format
1072          * (LE).
1073          *
1074          * Return:
1075          * - 0 on success
1076          * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
1077          * - another LIBUSB_ERROR code on other failure
1078          */
1079         int (*get_active_config_descriptor)(struct libusb_device *device,
1080                 void *buffer, size_t len);
1081
1082         /* Get a specific configuration descriptor for a device.
1083          *
1084          * The descriptor should be retrieved from memory, NOT via bus I/O to the
1085          * device. This means that you may have to cache it in a private structure
1086          * during get_device_list enumeration.
1087          *
1088          * The requested descriptor is expressed as a zero-based index (i.e. 0
1089          * indicates that we are requesting the first descriptor). The index does
1090          * not (necessarily) equal the bConfigurationValue of the configuration
1091          * being requested.
1092          *
1093          * This function is expected to write len bytes of data into buffer, which
1094          * is guaranteed to be big enough. If you can only do a partial write,
1095          * return an error code.
1096          *
1097          * This function is expected to return the descriptor in bus-endian format
1098          * (LE).
1099          *
1100          * Return the length read on success or a LIBUSB_ERROR code on failure.
1101          */
1102         int (*get_config_descriptor)(struct libusb_device *device,
1103                 uint8_t config_index, void *buffer, size_t len);
1104
1105         /* Like get_config_descriptor but then by bConfigurationValue instead
1106          * of by index.
1107          *
1108          * Optional, if not present the core will call get_config_descriptor
1109          * for all configs until it finds the desired bConfigurationValue.
1110          *
1111          * Returns a pointer to the raw-descriptor in *buffer, this memory
1112          * is valid as long as device is valid.
1113          *
1114          * Returns the length of the returned raw-descriptor on success,
1115          * or a LIBUSB_ERROR code on failure.
1116          */
1117         int (*get_config_descriptor_by_value)(struct libusb_device *device,
1118                 uint8_t bConfigurationValue, void **buffer);
1119
1120         /* Get the bConfigurationValue for the active configuration for a device.
1121          * Optional. This should only be implemented if you can retrieve it from
1122          * cache (don't generate I/O).
1123          *
1124          * If you cannot retrieve this from cache, either do not implement this
1125          * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
1126          * libusb to retrieve the information through a standard control transfer.
1127          *
1128          * This function must be non-blocking.
1129          * Return:
1130          * - 0 on success
1131          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1132          *   was opened
1133          * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
1134          *   blocking
1135          * - another LIBUSB_ERROR code on other failure.
1136          */
1137         int (*get_configuration)(struct libusb_device_handle *dev_handle, uint8_t *config);
1138
1139         /* Set the active configuration for a device.
1140          *
1141          * A configuration value of -1 should put the device in unconfigured state.
1142          *
1143          * This function can block.
1144          *
1145          * Return:
1146          * - 0 on success
1147          * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
1148          * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
1149          *   configuration cannot be changed)
1150          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1151          *   was opened
1152          * - another LIBUSB_ERROR code on other failure.
1153          */
1154         int (*set_configuration)(struct libusb_device_handle *dev_handle, int config);
1155
1156         /* Claim an interface. When claimed, the application can then perform
1157          * I/O to an interface's endpoints.
1158          *
1159          * This function should not generate any bus I/O and should not block.
1160          * Interface claiming is a logical operation that simply ensures that
1161          * no other drivers/applications are using the interface, and after
1162          * claiming, no other drivers/applications can use the interface because
1163          * we now "own" it.
1164          *
1165          * Return:
1166          * - 0 on success
1167          * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
1168          * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
1169          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1170          *   was opened
1171          * - another LIBUSB_ERROR code on other failure
1172          */
1173         int (*claim_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
1174
1175         /* Release a previously claimed interface.
1176          *
1177          * This function should also generate a SET_INTERFACE control request,
1178          * resetting the alternate setting of that interface to 0. It's OK for
1179          * this function to block as a result.
1180          *
1181          * You will only ever be asked to release an interface which was
1182          * successfully claimed earlier.
1183          *
1184          * Return:
1185          * - 0 on success
1186          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1187          *   was opened
1188          * - another LIBUSB_ERROR code on other failure
1189          */
1190         int (*release_interface)(struct libusb_device_handle *dev_handle, uint8_t interface_number);
1191
1192         /* Set the alternate setting for an interface.
1193          *
1194          * You will only ever be asked to set the alternate setting for an
1195          * interface which was successfully claimed earlier.
1196          *
1197          * It's OK for this function to block.
1198          *
1199          * Return:
1200          * - 0 on success
1201          * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
1202          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1203          *   was opened
1204          * - another LIBUSB_ERROR code on other failure
1205          */
1206         int (*set_interface_altsetting)(struct libusb_device_handle *dev_handle,
1207                 uint8_t interface_number, uint8_t altsetting);
1208
1209         /* Clear a halt/stall condition on an endpoint.
1210          *
1211          * It's OK for this function to block.
1212          *
1213          * Return:
1214          * - 0 on success
1215          * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1216          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1217          *   was opened
1218          * - another LIBUSB_ERROR code on other failure
1219          */
1220         int (*clear_halt)(struct libusb_device_handle *dev_handle,
1221                 unsigned char endpoint);
1222
1223         /* Perform a USB port reset to reinitialize a device. Optional.
1224          *
1225          * If possible, the device handle should still be usable after the reset
1226          * completes, assuming that the device descriptors did not change during
1227          * reset and all previous interface state can be restored.
1228          *
1229          * If something changes, or you cannot easily locate/verify the reset
1230          * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
1231          * to close the old handle and re-enumerate the device.
1232          *
1233          * Return:
1234          * - 0 on success
1235          * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
1236          *   has been disconnected since it was opened
1237          * - another LIBUSB_ERROR code on other failure
1238          */
1239         int (*reset_device)(struct libusb_device_handle *dev_handle);
1240
1241         /* Alloc num_streams usb3 bulk streams on the passed in endpoints */
1242         int (*alloc_streams)(struct libusb_device_handle *dev_handle,
1243                 uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
1244
1245         /* Free usb3 bulk streams allocated with alloc_streams */
1246         int (*free_streams)(struct libusb_device_handle *dev_handle,
1247                 unsigned char *endpoints, int num_endpoints);
1248
1249         /* Allocate persistent DMA memory for the given device, suitable for
1250          * zerocopy. May return NULL on failure. Optional to implement.
1251          */
1252         void *(*dev_mem_alloc)(struct libusb_device_handle *handle, size_t len);
1253
1254         /* Free memory allocated by dev_mem_alloc. */
1255         int (*dev_mem_free)(struct libusb_device_handle *handle, void *buffer,
1256                 size_t len);
1257
1258         /* Determine if a kernel driver is active on an interface. Optional.
1259          *
1260          * The presence of a kernel driver on an interface indicates that any
1261          * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
1262          *
1263          * Return:
1264          * - 0 if no driver is active
1265          * - 1 if a driver is active
1266          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1267          *   was opened
1268          * - another LIBUSB_ERROR code on other failure
1269          */
1270         int (*kernel_driver_active)(struct libusb_device_handle *dev_handle,
1271                 uint8_t interface_number);
1272
1273         /* Detach a kernel driver from an interface. Optional.
1274          *
1275          * After detaching a kernel driver, the interface should be available
1276          * for claim.
1277          *
1278          * Return:
1279          * - 0 on success
1280          * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1281          * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1282          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1283          *   was opened
1284          * - another LIBUSB_ERROR code on other failure
1285          */
1286         int (*detach_kernel_driver)(struct libusb_device_handle *dev_handle,
1287                 uint8_t interface_number);
1288
1289         /* Attach a kernel driver to an interface. Optional.
1290          *
1291          * Reattach a kernel driver to the device.
1292          *
1293          * Return:
1294          * - 0 on success
1295          * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1296          * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1297          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
1298          *   was opened
1299          * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
1300          *   preventing reattachment
1301          * - another LIBUSB_ERROR code on other failure
1302          */
1303         int (*attach_kernel_driver)(struct libusb_device_handle *dev_handle,
1304                 uint8_t interface_number);
1305
1306         /* Destroy a device. Optional.
1307          *
1308          * This function is called when the last reference to a device is
1309          * destroyed. It should free any resources allocated in the get_device_list
1310          * path.
1311          */
1312         void (*destroy_device)(struct libusb_device *dev);
1313
1314         /* Submit a transfer. Your implementation should take the transfer,
1315          * morph it into whatever form your platform requires, and submit it
1316          * asynchronously.
1317          *
1318          * This function must not block.
1319          *
1320          * This function gets called with the flying_transfers_lock locked!
1321          *
1322          * Return:
1323          * - 0 on success
1324          * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1325          * - another LIBUSB_ERROR code on other failure
1326          */
1327         int (*submit_transfer)(struct usbi_transfer *itransfer);
1328
1329         /* Cancel a previously submitted transfer.
1330          *
1331          * This function must not block. The transfer cancellation must complete
1332          * later, resulting in a call to usbi_handle_transfer_cancellation()
1333          * from the context of handle_events.
1334          */
1335         int (*cancel_transfer)(struct usbi_transfer *itransfer);
1336
1337         /* Clear a transfer as if it has completed or cancelled, but do not
1338          * report any completion/cancellation to the library. You should free
1339          * all private data from the transfer as if you were just about to report
1340          * completion or cancellation.
1341          *
1342          * This function might seem a bit out of place. It is used when libusb
1343          * detects a disconnected device - it calls this function for all pending
1344          * transfers before reporting completion (with the disconnect code) to
1345          * the user. Maybe we can improve upon this internal interface in future.
1346          */
1347         void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
1348
1349         /* Handle any pending events on event sources. Optional.
1350          *
1351          * Provide this function when event sources directly indicate device
1352          * or transfer activity. If your backend does not have such event sources,
1353          * implement the handle_transfer_completion function below.
1354          *
1355          * This involves monitoring any active transfers and processing their
1356          * completion or cancellation.
1357          *
1358          * The function is passed a pointer that represents platform-specific
1359          * data for monitoring event sources (size count). This data is to be
1360          * (re)allocated as necessary when event sources are modified.
1361          * The num_ready parameter indicates the number of event sources that
1362          * have reported events. This should be enough information for you to
1363          * determine which actions need to be taken on the currently active
1364          * transfers.
1365          *
1366          * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1367          * For completed transfers, call usbi_handle_transfer_completion().
1368          * For control/bulk/interrupt transfers, populate the "transferred"
1369          * element of the appropriate usbi_transfer structure before calling the
1370          * above functions. For isochronous transfers, populate the status and
1371          * transferred fields of the iso packet descriptors of the transfer.
1372          *
1373          * This function should also be able to detect disconnection of the
1374          * device, reporting that situation with usbi_handle_disconnect().
1375          *
1376          * When processing an event related to a transfer, you probably want to
1377          * take usbi_transfer.lock to prevent races. See the documentation for
1378          * the usbi_transfer structure.
1379          *
1380          * Return 0 on success, or a LIBUSB_ERROR code on failure.
1381          */
1382         int (*handle_events)(struct libusb_context *ctx,
1383                 void *event_data, unsigned int count, unsigned int num_ready);
1384
1385         /* Handle transfer completion. Optional.
1386          *
1387          * Provide this function when there are no event sources available that
1388          * directly indicate device or transfer activity. If your backend does
1389          * have such event sources, implement the handle_events function above.
1390          *
1391          * Your backend must tell the library when a transfer has completed by
1392          * calling usbi_signal_transfer_completion(). You should store any private
1393          * information about the transfer and its completion status in the transfer's
1394          * private backend data.
1395          *
1396          * During event handling, this function will be called on each transfer for
1397          * which usbi_signal_transfer_completion() was called.
1398          *
1399          * For any cancelled transfers, call usbi_handle_transfer_cancellation().
1400          * For completed transfers, call usbi_handle_transfer_completion().
1401          * For control/bulk/interrupt transfers, populate the "transferred"
1402          * element of the appropriate usbi_transfer structure before calling the
1403          * above functions. For isochronous transfers, populate the status and
1404          * transferred fields of the iso packet descriptors of the transfer.
1405          *
1406          * Return 0 on success, or a LIBUSB_ERROR code on failure.
1407          */
1408         int (*handle_transfer_completion)(struct usbi_transfer *itransfer);
1409
1410         /* Number of bytes to reserve for per-context private backend data.
1411          * This private data area is accessible by calling
1412          * usbi_get_context_priv() on the libusb_context instance.
1413          */
1414         size_t context_priv_size;
1415
1416         /* Number of bytes to reserve for per-device private backend data.
1417          * This private data area is accessible by calling
1418          * usbi_get_device_priv() on the libusb_device instance.
1419          */
1420         size_t device_priv_size;
1421
1422         /* Number of bytes to reserve for per-handle private backend data.
1423          * This private data area is accessible by calling
1424          * usbi_get_device_handle_priv() on the libusb_device_handle instance.
1425          */
1426         size_t device_handle_priv_size;
1427
1428         /* Number of bytes to reserve for per-transfer private backend data.
1429          * This private data area is accessible by calling
1430          * usbi_get_transfer_priv() on the usbi_transfer instance.
1431          */
1432         size_t transfer_priv_size;
1433 };
1434
1435 extern const struct usbi_os_backend usbi_backend;
1436
1437 #define for_each_context(c) \
1438         for_each_helper(c, &active_contexts_list, struct libusb_context)
1439
1440 #define for_each_device(ctx, d) \
1441         for_each_helper(d, &(ctx)->usb_devs, struct libusb_device)
1442
1443 #define for_each_device_safe(ctx, d, n) \
1444         for_each_safe_helper(d, n, &(ctx)->usb_devs, struct libusb_device)
1445
1446 #define for_each_open_device(ctx, h) \
1447         for_each_helper(h, &(ctx)->open_devs, struct libusb_device_handle)
1448
1449 #define __for_each_transfer(list, t) \
1450         for_each_helper(t, (list), struct usbi_transfer)
1451
1452 #define for_each_transfer(ctx, t) \
1453         __for_each_transfer(&(ctx)->flying_transfers, t)
1454
1455 #define __for_each_transfer_safe(list, t, n) \
1456         for_each_safe_helper(t, n, (list), struct usbi_transfer)
1457
1458 #define for_each_transfer_safe(ctx, t, n) \
1459         __for_each_transfer_safe(&(ctx)->flying_transfers, t, n)
1460
1461 #define __for_each_completed_transfer_safe(list, t, n) \
1462         list_for_each_entry_safe(t, n, (list), completed_list, struct usbi_transfer)
1463
1464 #define for_each_event_source(ctx, e) \
1465         for_each_helper(e, &(ctx)->event_sources, struct usbi_event_source)
1466
1467 #define for_each_removed_event_source(ctx, e) \
1468         for_each_helper(e, &(ctx)->removed_event_sources, struct usbi_event_source)
1469
1470 #define for_each_removed_event_source_safe(ctx, e, n) \
1471         for_each_safe_helper(e, n, &(ctx)->removed_event_sources, struct usbi_event_source)
1472
1473 #define for_each_hotplug_cb(ctx, c) \
1474         for_each_helper(c, &(ctx)->hotplug_cbs, struct usbi_hotplug_callback)
1475
1476 #define for_each_hotplug_cb_safe(ctx, c, n) \
1477         for_each_safe_helper(c, n, &(ctx)->hotplug_cbs, struct usbi_hotplug_callback)
1478
1479 #ifdef __cplusplus
1480 }
1481 #endif
1482
1483 #endif