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