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