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