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