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