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