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