2 * Internal header for libusb
3 * Copyright (C) 2007-2008 Daniel Drake <dsd@gentoo.org>
4 * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
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.
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.
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
33 #define DEVICE_DESC_LENGTH 18
35 #define USB_MAXENDPOINTS 32
36 #define USB_MAXINTERFACES 32
37 #define USB_MAXCONFIG 8
40 struct list_head *prev, *next;
43 /* Get an entry from the list
44 * ptr - the address of this list_head element in "type"
45 * type - the data type that contains "member"
46 * member - the list_head element in "type"
48 #define list_entry(ptr, type, member) \
49 ((type *)((char *)(ptr) - (unsigned long)(&((type *)0L)->member)))
51 /* Get each entry from a list
52 * pos - A structure pointer has a "member" element
54 * member - the list_head element in "pos"
56 #define list_for_each_entry(pos, head, member) \
57 for (pos = list_entry((head)->next, typeof(*pos), member); \
58 &pos->member != (head); \
59 pos = list_entry(pos->member.next, typeof(*pos), member))
61 #define list_for_each_entry_safe(pos, n, head, member) \
62 for (pos = list_entry((head)->next, typeof(*pos), member), \
63 n = list_entry(pos->member.next, typeof(*pos), member); \
64 &pos->member != (head); \
65 pos = n, n = list_entry(n->member.next, typeof(*n), member))
67 #define list_empty(entry) ((entry)->next == (entry))
69 static inline void list_init(struct list_head *entry)
71 entry->prev = entry->next = entry;
74 static inline void list_add(struct list_head *entry, struct list_head *head)
76 entry->next = head->next;
79 head->next->prev = entry;
83 static inline void list_add_tail(struct list_head *entry,
84 struct list_head *head)
87 entry->prev = head->prev;
89 head->prev->next = entry;
93 static inline void list_del(struct list_head *entry)
95 entry->next->prev = entry->prev;
96 entry->prev->next = entry->next;
99 #define container_of(ptr, type, member) ({ \
100 const typeof( ((type *)0)->member ) *__mptr = (ptr); \
101 (type *)( (char *)__mptr - offsetof(type,member) );})
103 #define MIN(a, b) ((a) < (b) ? (a) : (b))
104 #define MAX(a, b) ((a) > (b) ? (a) : (b))
106 #define TIMESPEC_IS_SET(ts) ((ts)->tv_sec != 0 || (ts)->tv_nsec != 0)
108 enum usbi_log_level {
115 void usbi_log(struct libusb_context *ctx, enum usbi_log_level,
116 const char *function, const char *format, ...);
118 #ifdef ENABLE_LOGGING
119 #define _usbi_log(ctx, level, fmt...) usbi_log(ctx, level, __FUNCTION__, fmt)
121 #define _usbi_log(ctx, level, fmt...)
124 #ifdef ENABLE_DEBUG_LOGGING
125 #define usbi_dbg(fmt...) _usbi_log(NULL, LOG_LEVEL_DEBUG, fmt)
127 #define usbi_dbg(fmt...)
130 #define usbi_info(ctx, fmt...) _usbi_log(ctx, LOG_LEVEL_INFO, fmt)
131 #define usbi_warn(ctx, fmt...) _usbi_log(ctx, LOG_LEVEL_WARNING, fmt)
132 #define usbi_err(ctx, fmt...) _usbi_log(ctx, LOG_LEVEL_ERROR, fmt)
134 #define USBI_GET_CONTEXT(ctx) if (!(ctx)) (ctx) = usbi_default_context
135 #define DEVICE_CTX(dev) ((dev)->ctx)
136 #define HANDLE_CTX(handle) (DEVICE_CTX((handle)->dev))
137 #define TRANSFER_CTX(transfer) (HANDLE_CTX((transfer)->dev_handle))
138 #define ITRANSFER_CTX(transfer) \
139 (TRANSFER_CTX(__USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)))
141 extern struct libusb_context *usbi_default_context;
143 struct libusb_context {
147 struct list_head usb_devs;
148 pthread_mutex_t usb_devs_lock;
150 /* A list of open handles. Backends are free to traverse this if required.
152 struct list_head open_devs;
153 pthread_mutex_t open_devs_lock;
155 /* this is a list of in-flight transfer handles, sorted by timeout
156 * expiration. URBs to timeout the soonest are placed at the beginning of
157 * the list, URBs that will time out later are placed after, and urbs with
158 * infinite timeout are always placed at the very end. */
159 struct list_head flying_transfers;
160 pthread_mutex_t flying_transfers_lock;
162 /* list of poll fd's */
163 struct list_head pollfds;
164 pthread_mutex_t pollfds_lock;
166 /* user callbacks for pollfd changes */
167 libusb_pollfd_added_cb fd_added_cb;
168 libusb_pollfd_removed_cb fd_removed_cb;
170 /* ensures that only one thread is handling events at any one time */
171 pthread_mutex_t events_lock;
173 /* used to see if there is an active thread doing event handling */
174 int event_handler_active;
176 /* used to wait for event completion in threads other than the one that is
178 pthread_mutex_t event_waiters_lock;
179 pthread_cond_t event_waiters_cond;
182 struct libusb_device {
183 /* lock protects refcnt, everything else is finalized at initialization
185 pthread_mutex_t lock;
188 struct libusb_context *ctx;
191 uint8_t device_address;
192 uint8_t num_configurations;
194 struct list_head list;
195 unsigned long session_data;
196 unsigned char os_priv[0];
199 struct libusb_device_handle {
200 /* lock protects claimed_interfaces */
201 pthread_mutex_t lock;
202 unsigned long claimed_interfaces;
204 struct list_head list;
205 struct libusb_device *dev;
206 unsigned char os_priv[0];
209 #define USBI_TRANSFER_TIMED_OUT (1<<0)
211 /* in-memory transfer layout:
213 * 1. struct usbi_transfer
214 * 2. struct libusb_transfer (which includes iso packets) [variable size]
215 * 3. os private data [variable size]
217 * from a libusb_transfer, you can get the usbi_transfer by rewinding the
218 * appropriate number of bytes.
219 * the usbi_transfer includes the number of allocated packets, so you can
220 * determine the size of the transfer and hence the start and length of the
224 struct usbi_transfer {
226 struct list_head list;
227 struct timeval timeout;
232 #define __USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer) \
233 ((struct libusb_transfer *)(((void *)(transfer)) \
234 + sizeof(struct usbi_transfer)))
235 #define __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \
236 ((struct usbi_transfer *)(((void *)(transfer)) \
237 - sizeof(struct usbi_transfer)))
239 static inline void *usbi_transfer_get_os_priv(struct usbi_transfer *transfer)
241 return ((void *)transfer) + sizeof(struct usbi_transfer)
242 + sizeof(struct libusb_transfer)
243 + (transfer->num_iso_packets
244 * sizeof(struct libusb_iso_packet_descriptor));
249 /* All standard descriptors have these 2 fields in common */
250 struct usb_descriptor_header {
252 uint8_t bDescriptorType;
255 /* shared data and functions */
257 void usbi_io_init(struct libusb_context *ctx);
259 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
260 unsigned long session_id);
261 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
262 unsigned long session_id);
263 int usbi_sanitize_device(struct libusb_device *dev);
264 void usbi_handle_disconnect(struct libusb_device_handle *handle);
266 void usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
267 enum libusb_transfer_status status);
268 void usbi_handle_transfer_cancellation(struct usbi_transfer *transfer);
270 int usbi_parse_descriptor(unsigned char *source, char *descriptor, void *dest,
272 int usbi_get_config_index_by_value(struct libusb_device *dev,
273 uint8_t bConfigurationValue, int *idx);
278 /* must come first */
279 struct libusb_pollfd pollfd;
281 struct list_head list;
284 int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events);
285 void usbi_remove_pollfd(struct libusb_context *ctx, int fd);
287 /* device discovery */
289 /* we traverse usbfs without knowing how many devices we are going to find.
290 * so we create this discovered_devs model which is similar to a linked-list
291 * which grows when required. it can be freed once discovery has completed,
292 * eliminating the need for a list node in the libusb_device structure
294 struct discovered_devs {
297 struct libusb_device *devices[0];
300 struct discovered_devs *discovered_devs_append(
301 struct discovered_devs *discdevs, struct libusb_device *dev);
305 /* This is the interface that OS backends need to implement.
306 * All fields are mandatory, except ones explicitly noted as optional. */
307 struct usbi_os_backend {
308 /* A human-readable name for your backend, e.g. "Linux usbfs" */
311 /* Perform initialization of your backend. You might use this function
312 * to determine specific capabilities of the system, allocate required
313 * data structures for later, etc.
315 * This function is called when a libusb user initializes the library
318 * Return 0 on success, or a LIBUSB_ERROR code on failure.
320 int (*init)(struct libusb_context *ctx);
322 /* Deinitialization. Optional. This function should destroy anything
323 * that was set up by init.
325 * This function is called when the user deinitializes the library.
329 /* Enumerate all the USB devices on the system, returning them in a list
330 * of discovered devices.
332 * Your implementation should enumerate all devices on the system,
333 * regardless of whether they have been seen before or not.
335 * When you have found a device, compute a session ID for it. The session
336 * ID should uniquely represent that particular device for that particular
337 * connection session since boot (i.e. if you disconnect and reconnect a
338 * device immediately after, it should be assigned a different session ID).
339 * If your OS cannot provide a unique session ID as described above,
340 * presenting a session ID of (bus_number << 8 | device_address) should
341 * be sufficient. Bus numbers and device addresses wrap and get reused,
342 * but that is an unlikely case.
344 * After computing a session ID for a device, call
345 * usbi_get_device_by_session_id(). This function checks if libusb already
346 * knows about the device, and if so, it provides you with a libusb_device
349 * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
350 * a new device structure for the device. Call usbi_alloc_device() to
351 * obtain a new libusb_device structure with reference count 1. Populate
352 * the bus_number and device_address attributes of the new device, and
353 * perform any other internal backend initialization you need to do. At
354 * this point, you should be ready to provide device descriptors and so
355 * on through the get_*_descriptor functions. Finally, call
356 * usbi_sanitize_device() to perform some final sanity checks on the
357 * device. Assuming all of the above succeeded, we can now continue.
358 * If any of the above failed, remember to unreference the device that
359 * was returned by usbi_alloc_device().
361 * At this stage we have a populated libusb_device structure (either one
362 * that was found earlier, or one that we have just allocated and
363 * populated). This can now be added to the discovered devices list
364 * using discovered_devs_append(). Note that discovered_devs_append()
365 * may reallocate the list, returning a new location for it, and also
366 * note that reallocation can fail. Your backend should handle these
367 * error conditions appropriately.
369 * This function should not generate any bus I/O and should not block.
370 * If I/O is required (e.g. reading the active configuration value), it is
371 * OK to ignore these suggestions :)
373 * This function is executed when the user wishes to retrieve a list
374 * of USB devices connected to the system.
376 * Return 0 on success, or a LIBUSB_ERROR code on failure.
378 int (*get_device_list)(struct libusb_context *ctx,
379 struct discovered_devs **discdevs);
381 /* Open a device for I/O and other USB operations. The device handle
382 * is preallocated for you, you can retrieve the device in question
383 * through handle->dev.
385 * Your backend should allocate any internal resources required for I/O
386 * and other operations so that those operations can happen (hopefully)
387 * without hiccup. This is also a good place to inform libusb that it
388 * should monitor certain file descriptors related to this device -
389 * see the usbi_add_pollfd() function.
391 * This function should not generate any bus I/O and should not block.
393 * This function is called when the user attempts to obtain a device
394 * handle for a device.
398 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
399 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
401 * - another LIBUSB_ERROR code on other failure
403 * Do not worry about freeing the handle on failed open, the upper layers
406 int (*open)(struct libusb_device_handle *handle);
408 /* Close a device such that the handle cannot be used again. Your backend
409 * should destroy any resources that were allocated in the open path.
410 * This may also be a good place to call usbi_remove_pollfd() to inform
411 * libusb of any file descriptors associated with this device that should
412 * no longer be monitored.
414 * This function is called when the user closes a device handle.
416 void (*close)(struct libusb_device_handle *handle);
418 /* Retrieve the device descriptor from a device.
420 * The descriptor should be retrieved from memory, NOT via bus I/O to the
421 * device. This means that you may have to cache it in a private structure
422 * during get_device_list enumeration. Alternatively, you may be able
423 * to retrieve it from a kernel interface (some Linux setups can do this)
424 * still without generating bus I/O.
426 * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into
427 * buffer, which is guaranteed to be big enough.
429 * This function is called when sanity-checking a device before adding
430 * it to the list of discovered devices, and also when the user requests
431 * to read the device descriptor.
433 * This function is expected to return the descriptor in bus-endian format
434 * (LE). If it returns the multi-byte values in host-endian format,
435 * set the host_endian output parameter to "1".
437 * Return 0 on success or a LIBUSB_ERROR code on failure.
439 int (*get_device_descriptor)(struct libusb_device *device,
440 unsigned char *buffer, int *host_endian);
442 /* Get the ACTIVE configuration descriptor for a device.
444 * The descriptor should be retrieved from memory, NOT via bus I/O to the
445 * device. This means that you may have to cache it in a private structure
446 * during get_device_list enumeration. You may also have to keep track
447 * of which configuration is active when the user changes it.
449 * This function is expected to write len bytes of data into buffer, which
450 * is guaranteed to be big enough. If you can only do a partial write,
451 * return an error code.
453 * This function is expected to return the descriptor in bus-endian format
454 * (LE). If it returns the multi-byte values in host-endian format,
455 * set the host_endian output parameter to "1".
459 * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
460 * - another LIBUSB_ERROR code on other failure
462 int (*get_active_config_descriptor)(struct libusb_device *device,
463 unsigned char *buffer, size_t len, int *host_endian);
465 /* Get a specific configuration descriptor for a device.
467 * The descriptor should be retrieved from memory, NOT via bus I/O to the
468 * device. This means that you may have to cache it in a private structure
469 * during get_device_list enumeration.
471 * The requested descriptor is expressed as a zero-based index (i.e. 0
472 * indicates that we are requesting the first descriptor). The index does
473 * not (necessarily) equal the bConfigurationValue of the configuration
476 * This function is expected to write len bytes of data into buffer, which
477 * is guaranteed to be big enough. If you can only do a partial write,
478 * return an error code.
480 * This function is expected to return the descriptor in bus-endian format
481 * (LE). If it returns the multi-byte values in host-endian format,
482 * set the host_endian output parameter to "1".
484 * Return 0 on success or a LIBUSB_ERROR code on failure.
486 int (*get_config_descriptor)(struct libusb_device *device,
487 uint8_t config_index, unsigned char *buffer, size_t len,
490 /* Get the bConfigurationValue for the active configuration for a device.
491 * Optional. This should only be implemented if you can retrieve it from
492 * cache (don't generate I/O).
494 * If you cannot retrieve this from cache, either do not implement this
495 * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
496 * libusb to retrieve the information through a standard control transfer.
498 * This function must be non-blocking.
501 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
503 * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
505 * - another LIBUSB_ERROR code on other failure.
507 int (*get_configuration)(struct libusb_device_handle *handle, int *config);
509 /* Set the active configuration for a device.
511 * A configuration value of -1 should put the device in unconfigured state.
513 * This function can block.
517 * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
518 * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
519 * configuration cannot be changed)
520 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
522 * - another LIBUSB_ERROR code on other failure.
524 int (*set_configuration)(struct libusb_device_handle *handle, int config);
526 /* Claim an interface. When claimed, the application can then perform
527 * I/O to an interface's endpoints.
529 * This function should not generate any bus I/O and should not block.
530 * Interface claiming is a logical operation that simply ensures that
531 * no other drivers/applications are using the interface, and after
532 * claiming, no other drivers/applicatiosn can use the interface because
537 * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
538 * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
539 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
541 * - another LIBUSB_ERROR code on other failure
543 int (*claim_interface)(struct libusb_device_handle *handle, int iface);
545 /* Release a previously claimed interface.
547 * This function should also generate a SET_INTERFACE control request,
548 * resetting the alternate setting of that interface to 0. It's OK for
549 * this function to block as a result.
551 * You will only ever be asked to release an interface which was
552 * successfully claimed earlier.
556 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
558 * - another LIBUSB_ERROR code on other failure
560 int (*release_interface)(struct libusb_device_handle *handle, int iface);
562 /* Set the alternate setting for an interface.
564 * You will only ever be asked to set the alternate setting for an
565 * interface which was successfully claimed earlier.
567 * It's OK for this function to block.
571 * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
572 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
574 * - another LIBUSB_ERROR code on other failure
576 int (*set_interface_altsetting)(struct libusb_device_handle *handle,
577 int iface, int altsetting);
579 /* Clear a halt/stall condition on an endpoint.
581 * It's OK for this function to block.
585 * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
586 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
588 * - another LIBUSB_ERROR code on other failure
590 int (*clear_halt)(struct libusb_device_handle *handle,
591 unsigned char endpoint);
593 /* Perform a USB port reset to reinitialize a device.
595 * If possible, the handle should still be usable after the reset
596 * completes, assuming that the device descriptors did not change during
597 * reset and all previous interface state can be restored.
599 * If something changes, or you cannot easily locate/verify the resetted
600 * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
601 * to close the old handle and re-enumerate the device.
605 * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
606 * has been disconnected since it was opened
607 * - another LIBUSB_ERROR code on other failure
609 int (*reset_device)(struct libusb_device_handle *handle);
611 /* Determine if a kernel driver is active on an interface. Optional.
613 * The presence of a kernel driver on an interface indicates that any
614 * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
617 * - 0 if no driver is active
618 * - 1 if a driver is active
619 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
621 * - another LIBUSB_ERROR code on other failure
623 int (*kernel_driver_active)(struct libusb_device_handle *handle,
626 /* Detach a kernel driver from an interface. Optional.
628 * After detaching a kernel driver, the interface should be available
633 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
634 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
635 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
637 * - another LIBUSB_ERROR code on other failure
639 int (*detach_kernel_driver)(struct libusb_device_handle *handle,
642 /* Destroy a device. Optional.
644 * This function is called when the last reference to a device is
645 * destroyed. It should free any resources allocated in the get_device_list
648 void (*destroy_device)(struct libusb_device *dev);
650 /* Submit a transfer. Your implementation should take the transfer,
651 * morph it into whatever form your platform requires, and submit it
654 * This function must not block.
658 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
659 * - another LIBUSB_ERROR code on other failure
661 int (*submit_transfer)(struct usbi_transfer *itransfer);
663 /* Cancel a previously submitted transfer.
665 * This function must not block. The transfer cancellation must complete
666 * later, resulting in a call to usbi_handle_transfer_cancellation()
667 * from the context of handle_events.
669 int (*cancel_transfer)(struct usbi_transfer *itransfer);
671 /* Clear a transfer as if it has completed or cancelled, but do not
672 * report any completion/cancellation to the library. You should free
673 * all private data from the transfer as if you were just about to report
674 * completion or cancellation.
676 * This function might seem a bit out of place. It is used when libusb
677 * detects a disconnected device - it calls this function for all pending
678 * transfers before reporting completion (with the disconnect code) to
679 * the user. Maybe we can improve upon this internal interface in future.
681 void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
683 /* Handle any pending events. This involves monitoring any active
684 * transfers and processing their completion or cancellation.
686 * The function is passed an array of pollfd structures (size nfds)
687 * as a result of the poll() system call. The num_ready parameter
688 * indicates the number of file descriptors that have reported events
689 * (i.e. the poll() return value). This should be enough information
690 * for you to determine which actions need to be taken on the currently
693 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
694 * For completed transfers, call usbi_handle_transfer_completion().
695 * For control/bulk/interrupt transfers, populate the "transferred"
696 * element of the appropriate usbi_transfer structure before calling the
697 * above functions. For isochronous transfers, populate the status and
698 * transferred fields of the iso packet descriptors of the transfer.
700 * This function should also be able to detect disconnection of the
701 * device, reporting that situation with usbi_handle_disconnect().
703 * Return 0 on success, or a LIBUSB_ERROR code on failure.
705 int (*handle_events)(struct libusb_context *ctx,
706 struct pollfd *fds, nfds_t nfds, int num_ready);
708 /* Number of bytes to reserve for per-device private backend data.
709 * This private data area is accessible through the "os_priv" field of
710 * struct libusb_device. */
711 size_t device_priv_size;
713 /* Number of bytes to reserve for per-handle private backend data.
714 * This private data area is accessible through the "os_priv" field of
715 * struct libusb_device. */
716 size_t device_handle_priv_size;
718 /* Number of bytes to reserve for per-transfer private backend data.
719 * This private data area is accessible by calling
720 * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance.
722 size_t transfer_priv_size;
724 /* Mumber of additional bytes for os_priv for each iso packet.
725 * Can your backend use this? */
726 /* FIXME: linux can't use this any more. if other OS's cannot either,
727 * then remove this */
728 size_t add_iso_packet_size;
731 extern const struct usbi_os_backend * const usbi_backend;
733 extern const struct usbi_os_backend linux_usbfs_backend;