libusbi.h 50 KB

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