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