summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDaniel Drake <dsd@gentoo.org>2008-05-12 18:46:37 +0100
committerDaniel Drake <dsd@gentoo.org>2008-05-13 23:47:55 +0100
commit1298c51f516a7bf04ca9add1b7db14417cdc66f3 (patch)
tree0fb1bc346bbdd5f4571d6f6128d30eace40d5700
parentade26afc42c34ceb1c45afcadd2ea5e8240eaca4 (diff)
downloadlibusb-1298c51f516a7bf04ca9add1b7db14417cdc66f3.tar.gz
Backend documentation for porting efforts
Hopefully comprehensive enough for people to get started.
-rw-r--r--PORTING95
-rw-r--r--TODO5
-rw-r--r--libusb/core.c12
-rw-r--r--libusb/io.c16
-rw-r--r--libusb/libusbi.h347
5 files changed, 461 insertions, 14 deletions
diff --git a/PORTING b/PORTING
new file mode 100644
index 0000000..7070784
--- /dev/null
+++ b/PORTING
@@ -0,0 +1,95 @@
+PORTING LIBUSB TO OTHER PLATFORMS
+
+Introduction
+============
+
+This document is aimed at developers wishing to port libusb to unsupported
+platforms. I believe the libusb API is OS-independent, so by supporting
+multiple operating systems we pave the way for cross-platform USB device
+drivers.
+
+Implementation-wise, the basic idea is that you provide an interface to
+libusb's internal "backend" API, which performs the appropriate operations on
+your target platform.
+
+In terms of USB I/O, your backend provides functionality to submit
+asynchronous transfers (synchronous transfers are implemented in the higher
+layers, based on the async interface). Your backend must also provide
+functionality to cancel those transfers.
+
+Your backend must also provide an event handling function to "reap" ongoing
+transfers and process their results.
+
+The backend must also provide standard functions for other USB operations,
+e.g. setting configuration, obtaining descriptors, etc.
+
+
+File descriptors for I/O polling
+================================
+
+For libusb to work, your event handling function obviously needs to be called
+at various points in time. Your backend must provide a set of file descriptors
+which libusb and its users can pass to poll() or select() to determine when
+it is time to call the event handling function.
+
+On Linux, this is easy: the usbfs kernel interface exposes a file descriptor
+which can be passed to poll(). If something similar is not true for your
+platform, you can emulate this using an internal library thread to reap I/O as
+necessary, and a pipe() with the main library to raise events. The file
+descriptor of the pipe can then be provided to libusb as an event source.
+
+
+Interface semantics and documentation
+=====================================
+
+Documentation of the backend interface can be found in libusbi.h inside the
+usbi_os_backend structure definition.
+
+Your implementations of these functions will need to call various internal
+libusb functions, prefixed with "usbi_". Documentation for these functions
+can be found in the .c files where they are implemented.
+
+You probably want to skim over *all* the documentation before starting your
+implementation. For example, you probably need to allocate and store private
+OS-specific data for device handles, but the documentation for the mechanism
+for doing so is probably not the first thing you will see.
+
+The Linux backend acts as a good example - view it as a reference
+implementation which you should try to match the behaviour of.
+
+
+Getting started
+===============
+
+1. Modify configure.ac to detect your platform appropriately (see the OS_LINUX
+stuff for an example).
+
+2. Implement your backend in the libusb/os/ directory, modifying
+libusb/os/Makefile.am appropriately.
+
+3. Add preprocessor logic to the top of libusb/core.c to statically assign the
+right usbi_backend for your platform.
+
+4. Produce and test your implementation.
+
+5. Send your implementation to libusb-devel mailing list.
+
+
+Implementation difficulties? Questions?
+=======================================
+
+If you encounter difficulties porting libusb to your platform, please raise
+these issues on the libusb-devel mailing list. Where possible and sensible, I
+am interested in solving problems preventing libusb from operating on other
+platforms.
+
+The libusb-devel mailing list is also a good place to ask questions and
+make suggestions about the internal API. Hopefully we can produce some
+better documentation based on your questions and other input.
+
+You are encouraged to get involved in the process; if the library needs
+some infrastructure additions/modifications to better support your platform,
+you are encouraged to make such changes (in cleanly distinct patch
+submissions). Even if you do not make such changes yourself, please do raise
+the issues on the mailing list at the very minimum.
+
diff --git a/TODO b/TODO
index ba66de7..c548443 100644
--- a/TODO
+++ b/TODO
@@ -2,11 +2,6 @@ for 1.0
=======
review functionality missing over 0.1
serialization of handle_events
-internal docs for OS porters
-
-1.0 API style/naming points to reconsider
-=========================================
-typedef _cb or _cb_fn or _cb_t?
for 1.1 or future
==================
diff --git a/libusb/core.c b/libusb/core.c
index 83f0cdb..28dafec 100644
--- a/libusb/core.c
+++ b/libusb/core.c
@@ -40,6 +40,7 @@ const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
static struct list_head usb_devs;
static pthread_mutex_t usb_devs_lock = PTHREAD_MUTEX_INITIALIZER;
+/* A list of open handles. Backends are free to traverse this if required. */
struct list_head usbi_open_devs;
pthread_mutex_t usbi_open_devs_lock = PTHREAD_MUTEX_INITIALIZER;
@@ -322,7 +323,8 @@ static void discovered_devs_free(struct discovered_devs *discdevs)
free(discdevs);
}
-/* allocate a new device with reference count 1 */
+/* Allocate a new device with a specific session ID. The returned device has
+ * a reference count of 1. */
struct libusb_device *usbi_alloc_device(unsigned long session_id)
{
size_t priv_size = usbi_backend->device_priv_size;
@@ -346,8 +348,9 @@ struct libusb_device *usbi_alloc_device(unsigned long session_id)
return dev;
}
-/* to be called by OS implementations when a new device is ready for final
- * sanitization and checking before being returned in a device list. */
+/* Perform some final sanity checks on a newly discovered device. If this
+ * function fails (negative return code), the device should not be added
+ * to the discovered device list. */
int usbi_sanitize_device(struct libusb_device *dev)
{
int r;
@@ -371,6 +374,9 @@ int usbi_sanitize_device(struct libusb_device *dev)
return 0;
}
+/* Examine libusb's internal list of known devices, looking for one with
+ * a specific session ID. Returns the matching device if it was found, and
+ * NULL otherwise. */
struct libusb_device *usbi_get_device_by_session_id(unsigned long session_id)
{
struct libusb_device *dev;
diff --git a/libusb/io.c b/libusb/io.c
index f91b14c..19b62c2 100644
--- a/libusb/io.c
+++ b/libusb/io.c
@@ -767,6 +767,11 @@ API_EXPORTED int libusb_cancel_transfer(struct libusb_transfer *transfer)
return r;
}
+/* Handle completion of a transfer (completion might be an error condition).
+ * This will invoke the user-supplied callback function, which may end up
+ * freeing the transfer. Therefore you cannot use the transfer structure
+ * after calling this function, and you should free all backend-specific
+ * data before calling it. */
void usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
enum libusb_transfer_status status)
{
@@ -800,6 +805,10 @@ void usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
libusb_free_transfer(transfer);
}
+/* Similar to usbi_handle_transfer_completion() but exclusively for transfers
+ * that were asynchronously cancelled. The same concerns w.r.t. freeing of
+ * transfers exist here.
+ */
void usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
{
/* if the URB was cancelled due to timeout, report timeout to the user */
@@ -1073,6 +1082,9 @@ API_EXPORTED void libusb_set_pollfd_notifiers(libusb_pollfd_added_cb added_cb,
fd_removed_cb = removed_cb;
}
+/* Add a file descriptor to the list of file descriptors to be monitored.
+ * events should be specified as a bitmask of events passed to poll(), e.g.
+ * POLLIN and/or POLLOUT. */
int usbi_add_pollfd(int fd, short events)
{
struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
@@ -1091,6 +1103,7 @@ int usbi_add_pollfd(int fd, short events)
return 0;
}
+/* Remove a file descriptor from the list of file descriptors to be polled. */
void usbi_remove_pollfd(int fd)
{
struct usbi_pollfd *ipollfd;
@@ -1151,6 +1164,9 @@ out:
return (const struct libusb_pollfd **) ret;
}
+/* Backends call this from handle_events to report disconnection of a device.
+ * The transfers get cancelled appropriately.
+ */
void usbi_handle_disconnect(struct libusb_device_handle *handle)
{
struct usbi_transfer *cur;
diff --git a/libusb/libusbi.h b/libusb/libusbi.h
index 87b2953..015d489 100644
--- a/libusb/libusbi.h
+++ b/libusb/libusbi.h
@@ -1,6 +1,6 @@
/*
* Internal header for libusb
- * Copyright (C) 2007 Daniel Drake <dsd@gentoo.org>
+ * Copyright (C) 2007-2008 Daniel Drake <dsd@gentoo.org>
* Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
*
* This library is free software; you can redistribute it and/or
@@ -251,58 +251,393 @@ struct discovered_devs *discovered_devs_append(
/* OS abstraction */
+/* This is the interface that OS backends need to implement.
+ * All fields are mandatory, except ones explicitly noted as optional. */
struct usbi_os_backend {
+ /* A human-readable name for your backend, e.g. "Linux usbfs" */
const char *name;
+
+ /* Perform initialization of your backend. You might use this function
+ * to determine specific capabilities of the system, allocate required
+ * data structures for later, etc.
+ *
+ * This function is called when a libusb user initializes the library
+ * prior to use.
+ *
+ * Return 0 on success, or a LIBUSB_ERROR code on failure.
+ */
int (*init)(void);
+
+ /* Deinitialization. Optional. This function should destroy anything
+ * that was set up by init.
+ *
+ * This function is called when the user deinitializes the library.
+ */
void (*exit)(void);
+ /* Enumerate all the USB devices on the system, returning them in a list
+ * of discovered devices.
+ *
+ * Your implementation should enumerate all devices on the system,
+ * regardless of whether they have been seen before or not.
+ *
+ * When you have found a device, compute a session ID for it. The session
+ * ID should uniquely represent that particular device for that particular
+ * connection session since boot (i.e. if you disconnect and reconnect a
+ * device immediately after, it should be assigned a different session ID).
+ * If your OS cannot provide a unique session ID as described above,
+ * presenting a session ID of (bus_number << 8 | device_address) should
+ * be sufficient. Bus numbers and device addresses wrap and get reused,
+ * but that is an unlikely case.
+ *
+ * After computing a session ID for a device, call
+ * usbi_get_device_by_session_id(). This function checks if libusb already
+ * knows about the device, and if so, it provides you with a libusb_device
+ * structure for it.
+ *
+ * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
+ * a new device structure for the device. Call usbi_alloc_device() to
+ * obtain a new libusb_device structure with reference count 1. Populate
+ * the bus_number and device_address attributes of the new device, and
+ * perform any other internal backend initialization you need to do. At
+ * this point, you should be ready to provide device descriptors and so
+ * on through the get_*_descriptor functions. Finally, call
+ * usbi_sanitize_device() to perform some final sanity checks on the
+ * device. Assuming all of the above succeeded, we can now continue.
+ * If any of the above failed, remember to unreference the device that
+ * was returned by usbi_alloc_device().
+ *
+ * At this stage we have a populated libusb_device structure (either one
+ * that was found earlier, or one that we have just allocated and
+ * populated). This can now be added to the discovered devices list
+ * using discovered_devs_append(). Note that discovered_devs_append()
+ * may reallocate the list, returning a new location for it, and also
+ * note that reallocation can fail. Your backend should handle these
+ * error conditions appropriately.
+ *
+ * This function should not generate any bus I/O and should not block.
+ * If I/O is required (e.g. reading the active configuration value), it is
+ * OK to ignore these suggestions :)
+ *
+ * This function is executed when the user wishes to retrieve a list
+ * of USB devices connected to the system.
+ *
+ * Return 0 on success, or a LIBUSB_ERROR code on failure.
+ */
int (*get_device_list)(struct discovered_devs **discdevs);
+ /* Open a device for I/O and other USB operations. The device handle
+ * is preallocated for you, you can retrieve the device in question
+ * through handle->dev.
+ *
+ * Your backend should allocate any internal resources required for I/O
+ * and other operations so that those operations can happen (hopefully)
+ * without hiccup. This is also a good place to inform libusb that it
+ * should monitor certain file descriptors related to this device -
+ * see the usbi_add_pollfd() function.
+ *
+ * This function should not generate any bus I/O and should not block.
+ *
+ * This function is called when the user attempts to obtain a device
+ * handle for a device.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
+ * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
+ * discovery
+ * - another LIBUSB_ERROR code on other failure
+ *
+ * Do not worry about freeing the handle on failed open, the upper layers
+ * do this for you.
+ */
int (*open)(struct libusb_device_handle *handle);
+
+ /* Close a device such that the handle cannot be used again. Your backend
+ * should destroy any resources that were allocated in the open path.
+ * This may also be a good place to call usbi_remove_pollfd() to inform
+ * libusb of any file descriptors associated with this device that should
+ * no longer be monitored.
+ *
+ * This function is called when the user closes a device handle.
+ */
void (*close)(struct libusb_device_handle *handle);
+ /* Retrieve the device descriptor from a device.
+ *
+ * The descriptor should be retrieved from memory, NOT via bus I/O to the
+ * device. This means that you may have to cache it in a private structure
+ * during get_device_list enumeration. Alternatively, you may be able
+ * to retrieve it from a kernel interface (some Linux setups can do this)
+ * still without generating bus I/O.
+ *
+ * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into
+ * buffer, which is guaranteed to be big enough.
+ *
+ * This function is called when sanity-checking a device before adding
+ * it to the list of discovered devices, and also when the user requests
+ * to read the device descriptor.
+ *
+ * Return 0 on success or a LIBUSB_ERROR code on failure.
+ */
int (*get_device_descriptor)(struct libusb_device *device,
unsigned char *buffer);
+
+ /* Get the ACTIVE configuration descriptor for a device.
+ *
+ * The descriptor should be retrieved from memory, NOT via bus I/O to the
+ * device. This means that you may have to cache it in a private structure
+ * during get_device_list enumeration. You may also have to keep track
+ * of which configuration is active when the user changes it.
+ *
+ * This function is expected to write len bytes of data into buffer, which
+ * is guaranteed to be big enough. If you can only do a partial write,
+ * return an error code.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
+ * - another LIBUSB_ERROR code on other failure
+ */
int (*get_active_config_descriptor)(struct libusb_device *device,
unsigned char *buffer, size_t len);
+
+ /* Get a specific configuration descriptor for a device.
+ *
+ * The descriptor should be retrieved from memory, NOT via bus I/O to the
+ * device. This means that you may have to cache it in a private structure
+ * during get_device_list enumeration.
+ *
+ * The requested descriptor is expressed as a zero-based index (i.e. 0
+ * indicates that we are requesting the first descriptor). The index does
+ * not (necessarily) equal the bConfigurationValue of the configuration
+ * being requested.
+ *
+ * This function is expected to write len bytes of data into buffer, which
+ * is guaranteed to be big enough. If you can only do a partial write,
+ * return an error code.
+ *
+ * Return 0 on success or a LIBUSB_ERROR code on failure.
+ */
int (*get_config_descriptor)(struct libusb_device *device,
uint8_t config_index, unsigned char *buffer, size_t len);
+ /* Set the active configuration for a device.
+ *
+ * A configuration value of -1 should put the device in unconfigured state.
+ *
+ * This function can block.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
+ * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
+ * configuration cannot be changed)
+ * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
+ * was opened
+ * - another LIBUSB_ERROR code on other failure.
+ */
int (*set_configuration)(struct libusb_device_handle *handle, int config);
+ /* Claim an interface. When claimed, the application can then perform
+ * I/O to an interface's endpoints.
+ *
+ * This function should not generate any bus I/O and should not block.
+ * Interface claiming is a logical operation that simply ensures that
+ * no other drivers/applications are using the interface, and after
+ * claiming, no other drivers/applicatiosn can use the interface because
+ * we now "own" it.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
+ * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
+ * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
+ * was opened
+ * - another LIBUSB_ERROR code on other failure
+ */
int (*claim_interface)(struct libusb_device_handle *handle, int iface);
+
+ /* Release a previously claimed interface.
+ *
+ * This function should also generate a SET_INTERFACE control request,
+ * resetting the alternate setting of that interface to 0. It's OK for
+ * this function to block as a result.
+ *
+ * You will only ever be asked to release an interface which was
+ * successfully claimed earlier.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
+ * was opened
+ * - another LIBUSB_ERROR code on other failure
+ */
int (*release_interface)(struct libusb_device_handle *handle, int iface);
+ /* Set the alternate setting for an interface.
+ *
+ * You will only ever be asked to set the alternate setting for an
+ * interface which was successfully claimed earlier.
+ *
+ * It's OK for this function to block.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
+ * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
+ * was opened
+ * - another LIBUSB_ERROR code on other failure
+ */
int (*set_interface_altsetting)(struct libusb_device_handle *handle,
int iface, int altsetting);
+
+ /* Clear a halt/stall condition on an endpoint.
+ *
+ * It's OK for this function to block.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
+ * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
+ * was opened
+ * - another LIBUSB_ERROR code on other failure
+ */
int (*clear_halt)(struct libusb_device_handle *handle,
unsigned char endpoint);
+
+ /* Perform a USB port reset to reinitialize a device.
+ *
+ * If possible, the handle should still be usable after the reset
+ * completes, assuming that the device descriptors did not change during
+ * reset and all previous interface state can be restored.
+ *
+ * If something changes, or you cannot easily locate/verify the resetted
+ * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
+ * to close the old handle and re-enumerate the device.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
+ * has been disconnected since it was opened
+ * - another LIBUSB_ERROR code on other failure
+ */
int (*reset_device)(struct libusb_device_handle *handle);
- /* optional */
+ /* Determine if a kernel driver is active on an interface. Optional.
+ *
+ * The presence of a kernel driver on an interface indicates that any
+ * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
+ *
+ * Return:
+ * - 0 if no driver is active
+ * - 1 if a driver is active
+ * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
+ * was opened
+ * - another LIBUSB_ERROR code on other failure
+ */
int (*kernel_driver_active)(struct libusb_device_handle *handle,
int interface);
+
+ /* Detach a kernel driver from an interface. Optional.
+ *
+ * After detaching a kernel driver, the interface should be available
+ * for claim.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
+ * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
+ * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
+ * was opened
+ * - another LIBUSB_ERROR code on other failure
+ */
int (*detach_kernel_driver)(struct libusb_device_handle *handle,
int interface);
+ /* Destroy a device. Optional.
+ *
+ * This function is called when the last reference to a device is
+ * destroyed. It should free any resources allocated in the get_device_list
+ * path.
+ */
void (*destroy_device)(struct libusb_device *dev);
+ /* Submit a transfer. Your implementation should take the transfer,
+ * morph it into whatever form your platform requires, and submit it
+ * asynchronously.
+ *
+ * This function must not block.
+ *
+ * Return:
+ * - 0 on success
+ * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * - another LIBUSB_ERROR code on other failure
+ */
int (*submit_transfer)(struct usbi_transfer *itransfer);
+
+ /* Cancel a previously submitted transfer.
+ *
+ * This function must not block. The transfer cancellation must complete
+ * later, resulting in a call to usbi_handle_transfer_cancellation()
+ * from the context of handle_events.
+ */
int (*cancel_transfer)(struct usbi_transfer *itransfer);
+
+ /* Clear a transfer as if it has completed or cancelled, but do not
+ * report any completion/cancellation to the library. You should free
+ * all private data from the transfer as if you were just about to report
+ * completion or cancellation.
+ *
+ * This function might seem a bit out of place. It is used when libusb
+ * detects a disconnected device - it calls this function for all pending
+ * transfers before reporting completion (with the disconnect code) to
+ * the user. Maybe we can improve upon this internal interface in future.
+ */
void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
+ /* Handle any pending events. This involves monitoring any active
+ * transfers and processing their completion or cancellation.
+ *
+ * The function is passed an array of pollfd structures (size nfds)
+ * as a result of the poll() system call. The num_ready parameter
+ * indicates the number of file descriptors that have reported events
+ * (i.e. the poll() return value). This should be enough information
+ * for you to determine which actions need to be taken on the currently
+ * active transfers.
+ *
+ * For any cancelled transfers, call usbi_handle_transfer_cancellation().
+ * For completed transfers, call usbi_handle_transfer_completion().
+ * For control/bulk/interrupt transfers, populate the "transferred"
+ * element of the appropriate usbi_transfer structure before calling the
+ * above functions. For isochronous transfers, populate the status and
+ * transferred fields of the iso packet descriptors of the transfer.
+ *
+ * This function should also be able to detect disconnection of the
+ * device, reporting that situation with usbi_handle_disconnect().
+ *
+ * Return 0 on success, or a LIBUSB_ERROR code on failure.
+ */
int (*handle_events)(struct pollfd *fds, nfds_t nfds, int num_ready);
- /* number of bytes to reserve for libusb_device.os_priv */
+ /* Number of bytes to reserve for per-device private backend data.
+ * This private data area is accessible through the "os_priv" field of
+ * struct libusb_device. */
size_t device_priv_size;
- /* number of bytes to reserve for libusb_device_handle.os_priv */
+ /* Number of bytes to reserve for per-handle private backend data.
+ * This private data area is accessible through the "os_priv" field of
+ * struct libusb_device. */
size_t device_handle_priv_size;
- /* number of bytes to reserve for usbi_transfer.os_priv */
+ /* Number of bytes to reserve for per-transfer private backend data.
+ * This private data area is accessible by calling
+ * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance.
+ */
size_t transfer_priv_size;
- /* number of additional bytes for os_priv for each iso packet */
+ /* Mumber of additional bytes for os_priv for each iso packet.
+ * Can your backend use this? */
/* FIXME: linux can't use this any more. if other OS's cannot either,
* then remove this */
size_t add_iso_packet_size;