libusbi.h 35 KB

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