Here's the updated <linux/usb_gadget.h> ... if you looked at the
previous version, it's the same basic structure, with cleanups:

 * handling of status and feature flags doesn't assume software
   can do more than set/clear halt (or self-powered) features.

 * per-frame irq capability removed from interface, so drivers
   won't be tempted to abuse it.

 * add some request flags, matching key host-side ones.

 * use driver model only on 2.5; 2.4 uses traditional solutions.

 * updates of in-line documentation

I'm thinking this should be a reasonable fit with a fair variety
of USB peripheral/device controller hardware.

Remember, the point of this particular API is to provide a (mostly)
hardware-neutral wrapper around hardware capabilities ... so that
the Linux community can start to develop "gadget" code implementing
class and vendor drivers.  Then such "gadget" code will run on new
hardware that happens to run Linux, with minimal updates.

- Dave




/*
 * <linux/usb_gadget.h>
 *
 * We call the USB code inside a Linux-based peripheral device a "gadget"
 * driver, except for the hardware-specific bus glue.  One USB host can
 * master many USB gadgets, but the gadgets are only slaved to one host.
 *
 *
 * (c) Copyright 2002 by David Brownell
 *
 * This software is licensed under the GNU GPL version 2.
 */

#ifndef __LINUX_USB_GADGET_H
#define __LINUX_USB_GADGET_H

#ifdef __KERNEL__

/*
 * Gadget drivers make endpoint I/O requests to hardware without needing
 * to know many details of the hardware, but driver setup/configuration
 * code needs to handle some differences.  Use the API like this:
 *
 *
 * (1) Register a driver for the particular device side bus interface
 * hardware, such as the sa1100 or pxa250 as found in Linux PDAs, net2280
 * on PCI (USB 2.0), and so on.  At this point the device is logically in the
 * USB ch9 initial state ("attached"), drawing no power and not usable.
 *
 * (2) Register a gadget driver that implements some higher level device
 * function.  That will then bind() to a usb_gadget.
 *
 * (3) The hardware driver can now start enumerating.  The steps it handles
 * are to accept USB power and set_address requests.  Other steps are
 * handled by the gadget driver.
 *
 *
 * (4) The gadget driver's setup() call returns usb descriptors, based both
 * on what the bus interface hardware provides and on the functionality being
 * implemented.  That can involve alternate settings or configurations,
 * unless the hardware prevents such operation.
 *
 * (5) The gadget driver handles the last step of enumeration, when the USB
 * host issues a the set_configuration call.  It enables all endpoints used
 * in that configuration, with all interfaces in their default settings.
 * That involves using a list of the hardware's endpoints, enabling each
 * endpoint according to its descriptor.
 *
 *
 * (6) Do real work and perform data transfers, possibly involving changes
 * to interface settings or switching to new configurations, until the
 * device is disconnect()ed from the host.  Then dequeue any pending
 * requests, and goto (3).
 *
 *
 * When a gadget driver unregisters itself, it will be disconect()ed from
 * the host (if needed) before it is told to unbind() from the device.
 */

/*-------------------------------------------------------------------------*/

struct usb_ep;

/*
 * FIXME it'd be good to evolve so that master and slave sides of usb
 * had the same way to package and submit requests, but that implies
 * something new or slimming 'urb' to be less host-centric.  good for
 * many reasons including supporting usb OTG (peer-to-peer usb, where
 * devices can switch roles in order to master another device).
 *
 * FOR NOW consider that implementations of usb_request and usb_endpoint
 * could wrap host-side data structures ... drivers on OTG hardware could
 * handle transfers using the same API for both master and slave modes,
 * except that control messaging would work differently.
 */


/**
 * struct usb_request - describes one i/o request
 *
 * these are allocated/freed through the endpoint they're used with.  the
 * endpoint's driver can add extra per-request data to the memory it returns,
 * which often avoids separate memory allocations (potential failures),
 * later when the request is queued.
 *
 * bulk endpoints can use any size buffers, and can also be used for interrupt.
 * interrupt-only endpoints can be much less functional.
 */
        // NOTE this is analagous to 'struct urb' on the host side,
        // except that it's thinner and promotes more pre-allocation.
        //
        // ISSUE should this be allocated through the device?

struct usb_request {
        /* inputs, read by the hardware driver.  provide both dma and buf,
         * if you have them, and always at least 'buf' unless you know
         * the underlying hardware only uses dma transfers.
         */
        dma_addr_t              dma;
        void                    *buf;
        unsigned                length;

        /* flags to match the host side (different symbols):
         *   - no_interrupt:  hint that no completion irq is needed;
         *     helpful with deep request queues;
         *   - zero:  when writing data, makes the last packet be "short"
         *     by adding a zero length packet as needed;
         *   - short_not_ok: when reading data, makes short packets be
         *     treated as errors (queue stops advancing till cleanup).
         */
        unsigned                no_interrupt : 1,
                                zero : 1,
                                short_not_ok : 1;

        void                    (*complete) (struct usb_ep *ep,
                                        struct usb_request *req);
        void                    *context;

        /* outputs, valid from complete() until resubmit or free */
        int                     status;
        unsigned                actual;
};

/*-------------------------------------------------------------------------*/

/* endpoint-specific parts of the api to the usb controller hardware.
 * unlike the urb model, (de)multiplexing layers are not required.
 * (so this api could slash overhead if used on the host side...)
 *
 * note that device side usb controllers commonly differ in how many
 * endpoints they support, as well as their capabilities.
 */
struct usb_ep_ops {
        int (*enable) (struct usb_ep *ep,
                const struct usb_endpoint_descriptor *desc);
        int (*disable) (struct usb_ep *ep);

        struct usb_request *(*alloc_request) (struct usb_ep *ep,
                int gfp_flags);
        void (*free_request) (struct usb_ep *ep, struct usb_request *req);

        void *(*alloc_buffer) (struct usb_ep *ep, unsigned bytes,
                dma_addr_t *dma, int gfp_flags);
        void (*free_buffer) (struct usb_ep *ep, void *buf, dma_addr_t dma,
                unsigned bytes);
        // NOTE:  on 2.5, drivers may also use dma_map() and
        // dma_sync_single() to manage dma overhead. 

        int (*queue) (struct usb_ep *ep, struct usb_request *req,
                int gfp_flags);
        int (*dequeue) (struct usb_ep *ep, struct usb_request *req);

        int (*set_halt) (struct usb_ep *ep, int value);
};

/**
 * struct usb_ep - device side representation of USB endpoint
 *
 * the bus controller driver lists all the general purpose endpoints in
 * gadget->ep_list.  the control endpoint (gadget->ep0) is not in that list,
 * and is accessed only in response to a driver setup() callback.
 */
struct usb_ep {
        /* managed by gadget driver */
        void                    *driver_data;

        /* readonly to gadget driver */
        const char              *name;
        const struct usb_ep_ops *ops;
        struct list_head        ep_list;
        unsigned                maxpacket : 16;
};

/*-------------------------------------------------------------------------*/

/**
 * usb_ep_enable - configure endpoint, making it usable
 * @ep: the endpoint being configured.  may not be the endpoint named "ep0".
 *      drivers discover endpoints through the ep_list of a usb_gadget.
 * @desc: descriptor for desired behavior.  caller guarantees this pointer
 *      remains valid until the endpoint is disabled; the data byte order
 *      is little-endian (usb-standard).
 *
 * when configurations are set, or when interface settings change, the driver
 * will enable or disable the relevant endpoints.  while it is enabled, an
 * endpoint may be used for i/o until the driver receives a disconnect() from
 * the host or until the endpoint is disabled.
 *
 * the ep0 implementation (which calls this routine) must ensure that the
 * hardware capabilities of each endpoint match the descriptor provided
 * for it.  for example, an endpoint named "ep2in-bulk" would be usable
 * for interrupt transfers as well as bulk, but it likely couldn't be used
 * for iso transfers or for endpoint 14.  some endpoints are fully
 * configurable, with more generic names like "ep-a".  (remember that for
 * USB, "in" means "towards the USB master".)
 *
 * returns zero, or a negative error code.
 */
static inline int
usb_ep_enable (struct usb_ep *ep, const struct usb_endpoint_descriptor *desc)
{
        return ep->ops->enable (ep, desc);
}

/**
 * usb_ep_disable - endpoint is no longer usable
 * @ep: the endpoint being unconfigured.  may not be the endpoint named "ep0".
 *
 * no other task may be using this endpoint when this is called,
 * all submitted requests must have been completed (or canceled), and
 * all allocated requests should have been freed.  after this call
 * returns, the only legal request to this endpoint is usb_ep_enable().
 *
 * returns zero, or a negative error code.
 */
static inline int
usb_ep_disable (struct usb_ep *ep)
{
        return ep->ops->disable (ep);
}

/**
 * usb_ep_alloc_request - allocate a request object to use with this endpoint
 * @ep: the endpoint to be used with with the request
 * @gfp_flags: GFP_* flags to use
 *
 * request objects must be allocated with this call, since they normally
 * require controller-specific (and perhaps endpoint-specific) setup.
 * requests may be submitted with usb_ep_queue(), and receive a single
 * completion callback.  free requests with usb_ep_free_request(), when
 * they are no longer needed.
 *
 * returns the request, or null if one could not be allocated.
 */
static inline struct usb_request *
usb_ep_alloc_request (struct usb_ep *ep, int gfp_flags)
{
        return ep->ops->alloc_request (ep, gfp_flags);
}

/**
 * usb_ep_free_request - frees a request object
 * @ep: the endpoint associated with the request
 * @req: the request being freed
 *
 * reverses the effect of usb_ep_alloc_request().
 * caller guarantees the request is not queued, and that it will
 * no longer be requeued (or otherwise used).
 */
static inline void
usb_ep_free_request (struct usb_ep *ep, struct usb_request *req)
{
        ep->ops->free_request (ep, req);
}

/**
 * usb_ep_alloc_buffer - allocate an I/O buffer
 * @ep: the endpoint associated with the buffer
 * @len: length of the desired buffer
 * @dma: pointer to the buffer's DMA address; must be valid
 * @gfp_flags: GFP_* flags to use
 *
 * returns a new buffer, or null if one could not be allocated.
 * the buffer is suitably aligned for dma, if that endpoint uses DMA,
 * and the caller won't have to worry about dma-inconsistency.
 * free it later with usb_ep_free_buffer().
 */
static inline void *
usb_ep_alloc_buffer (struct usb_ep *ep, unsigned len, dma_addr_t *dma,
        int gfp_flags)
{
        return ep->ops->alloc_buffer (ep, len, dma, gfp_flags);
}

/**
 * usb_ep_free_buffer - frees an i/o buffer
 * @ep: the endpoint associated with the buffer
 * @buf: CPU view address of the buffer
 * @dma: the buffer's DMA address
 * @len: length of the buffer
 *
 * reverses the effect of usb_ep_alloc_buffer().
 * caller guarantees the buffer will no longer be accessed
 */
static inline void
usb_ep_free_buffer (struct usb_ep *ep, void *buf, dma_addr_t dma, unsigned len)
{
        ep->ops->free_buffer (ep, buf, dma, len);
}

/**
 * usb_ep_queue - queues (submits) an I/O request to an endpoint.
 * @ep: the endpoint associated with the request
 * @req: the request being submitted
 * @gfp_flags: GFP_* flags to use in case the lower level driver couldn't
 *      pre-allocate all necessary memory with the request.
 *
 * this tells the device controller to perform the specified request through
 * that endpoint (reading or writing a buffer).  when the request completes,
 * including being canceled by usb_ep_dequeue(), the request's completion
 * routine is called to return the request to the driver.  any endpoint
 * (except usually the control endpoint) may have more than one transfer
 * request queued; they complete in sequence.
 *
 * bulk endpoints can queue any amount of data; the transfer is packetized
 * automatically.  the last packet may be short if the request doesn't fill it
 * out completely.  zero length packets should be avoided in portable
 * protocols since not all usb hardware can successfully handle zero length
 * packets.  (zlps may be explicitly issued, and may be implicitly issued if
 * the request 'zero' flag is set.)  bulk endpoints may also be used
 * for interrupt transfers; but the reverse is not true, and some endpoints
 * won't support every interrupt transfer.  (such as 768 byte packets.)
 *
 * interrupt-only endpoints are less functional than bulk endpoints, for
 * example by not supporting queueing or not handling buffers that are
 * larger than the endpoint's maxpacket size.  they may also treat data
 * toggle differently.
 *
 * control endpoints ... after getting a setup() callback, the driver queues
 * one response (optional if it would be zero length).  that enables the
 * status ack, after transfering data as specified in the response.  setup
 * functions may return negative error codes to generate protocol stalls.
 *
 * for periodic endpoints, like interrupt or isochronous ones, the usb host
 * arranges to poll once per interval, and the gadget driver usually will
 * have queued some data to transfer at that time.
 *
 * returns zero, or a negative error code.  endpoints that are not enabled,
 * or which are enabled but halted, report errors; errors will also be
 * reported when the usb peripheral is disconnected.
 */
static inline int
usb_ep_queue (struct usb_ep *ep, struct usb_request *req, int gfp_flags)
{
        return ep->ops->queue (ep, req, gfp_flags);
}

/**
 * usb_ep_dequeue - dequeues (cancels, unlinks) an I/O request from an endpoint
 * @ep: the endpoint associated with the request
 * @req: the request being canceled
 *
 * if the request is still active on the endpoint, it is dequeued and its
 * completion routine is called (with status -ECONNRESET); else a negative
 * error code is returned.
 *
 * note that some hardware can't clear out write fifos (to unlink the request
 * at the head of the queue) except as part of disconnecting from usb.  such
 * restrictions prevent drivers from supporting configuration changes,
 * even to configuration zero (a "chapter 9" requirement).
 */
static inline int usb_ep_dequeue (struct usb_ep *ep, struct usb_request *req)
{
        return ep->ops->dequeue (ep, req);
}

/**
 * usb_ep_set_halt - sets the endpoint halt feature.
 * @ep: the bulk or interrupt endpoint being stalled
 *
 * use this to stall an endpoint, perhaps as an error report.
 * the endpoint stays halted (will not stream any data) until the host
 * clears this feature; drivers may need to empty the endpoint's request
 * queue first, to make sure no inappropriate transfers happen.
 *
 * returns zero, or a negative error code.  on success, this call sets
 * underlying hardware state that blocks data transfers.
 */
static inline int
usb_ep_set_halt (struct usb_ep *ep)
{
        return ep->ops->set_halt (ep, 1);
}

/**
 * usb_ep_clear_halt - clears endpoint halt, and resets toggle
 * @ep: the bulk or interrupt endpoint being reset
 *
 * use this when responding to the standard usb "set interface" request,
 * for endpoints that aren't reconfigured.
 *
 * returns zero, or a negative error code.  on success, this call clears
 * the underlying hardware state reflecting endpoint halt and data toggle.
 */
static inline int
usb_ep_clear_halt (struct usb_ep *ep)
{
        return ep->ops->set_halt (ep, 0);
}


/*-------------------------------------------------------------------------*/

struct usb_gadget;

/* the rest of the api to the controller hardware: device operations,
 * which don't involve endpoints (or i/o).
 */
struct usb_gadget_ops {
        int     (*get_frame)(struct usb_gadget *);
        int     (*wakeup)(struct usb_gadget *);
        int     (*set_selfpowered) (struct usb_gadget *, int value);
};

#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,50)
#define HAVE_DRIVER_MODEL
#include <linux/device.h>
#endif

/**
 * struct usb_gadget - represents a usb slave device
 *
 * gadgets have a mostly-portable "gadget driver" implementing device
 * functions, handling all usb configurations and interfaces.  they
 * also have a hardware-specific driver (accessed through ops vectors),
 * which insulates the gadget driver from hardware details and packages
 * the hardware endpoints through generic i/o queues.
 */
struct usb_gadget {
        /* readonly to gadget driver */
        const struct usb_gadget_ops     *ops;
        struct usb_ep                   *ep0;
        struct list_head                ep_list;        /* of usb_ep */
        enum usb_device_speed           speed;

#ifdef  HAVE_DRIVER_MODEL
        /* with 2.5 "generic dma" api, use this to allocate dma-coherent
         * buffers or set up dma mappings.  or print diagnostics, etc.
         */
        struct device                   dev;
#else
        char                            *bus_id;
        void                            *driver_data;
#endif
};

#ifdef  HAVE_DRIVER_MODEL
static inline void set_gadget_data (struct usb_gadget *gadget, void *data)
        { dev_set_drvdata (&gadget->dev, data); }
static inline void *get_gadget_data (struct usb_gadget *gadget)
        { return dev_get_drvdata (&gadget->dev); }

#else
static inline void set_gadget_data (struct usb_gadget *gadget, void *data)
        { gadget->driver_data = data; }
static inline void *get_gadget_data (struct usb_gadget *gadget)
        { return gadget->driver_data; }

#endif

/* iterates the non-control endpoints; 'tmp' is a struct usb_ep pointer */
#define gadget_for_each_ep(tmp,gadget) \
        list_for_each_entry(tmp, &(gadget)->ep_list, ep_list)

/**
 * usb_gadget_frame_number - returns the current frame number
 *
 * returns the usb frame number, normally eleven bits from a SOF packet,
 * or negative errno if this device doesn't support this capability.
 */
static inline int usb_gadget_frame_number (struct usb_gadget *gadget)
{
        return gadget->ops->get_frame (gadget);
}

/**
 * usb_gadget_wakeup - tries to wake up the host connected to this gadget
 *
 * returns zero on success, else negative error code if the hardware
 * doesn't support such attempts, or its support has not been enabled
 * by the usb host.  drivers must return device descriptors that report
 * their ability to support this, or hosts won't enable it.
 */
static inline int usb_gadget_wakeup (struct usb_gadget *gadget)
{
        if (!gadget->ops->wakeup)
                return -EOPNOTSUPP;
        return gadget->ops->wakeup (gadget);
}

/**
 * usb_gadget_set_selfpowered - sets the device selfpowered feature.
 * @gadget: the device being declared as self-powered
 *
 * this affects the device status reported by the hardware driver
 * to reflect that it now has a local power supply.
 *
 * returns zero on success, else negative errno.
 */
static inline int
usb_gadget_set_selfpowered (struct usb_gadget *gadget)
{
        if (!gadget->ops->set_selfpowered)
                return -EOPNOTSUPP;
        return gadget->ops->set_selfpowered (gadget, 1);
}

/**
 * usb_gadget_clear_selfpowered - clear the device selfpowered feature.
 * @gadget: the device being declared as bus-powered
 *
 * this affects the device status reported by the hardware driver.
 * some hardware may not support bus-powered operation, in which
 * case this feature's value can never change.
 *
 * returns zero on success, else negative errno.
 */
static inline int
usb_gadget_clear_selfpowered (struct usb_gadget *gadget)
{
        if (!gadget->ops->set_selfpowered)
                return -EOPNOTSUPP;
        return gadget->ops->set_selfpowered (gadget, 0);
}


/*-------------------------------------------------------------------------*/

/**
 * struct usb_gadget_driver - driver for usb 'slave' devices
 *
 * devices are disabled till a gadget driver successfully bind()s, which
 * means the driver will handle setup() requests needed to enumerate (and
 * meet "chapter 9" requirements) then do some useful work.
 *
 * drivers use hardware-specific knowledge to configure the usb hardware.
 * endpoint addressing is only one of several hardware characteristics that
 * are in descriptors the ep0 implementation returns from setup() calls.
 *
 * except for ep0 implementation, most driver code shouldn't need change to
 * run on top of different usb controllers.  it'll use endpoints set up by
 * that ep0 implementation.
 */
struct usb_gadget_driver {
        char                    *function;              /* description */

        /* highest speed it handles ... for hw sanity check */
        enum usb_device_speed   speed;

        /* lets a driver bind to the usb slave hardware, or unbinds it
         * on driver rmmod, system shutdown, etc.  these calls are made
         * in a context that can sleep.
         *
         * endpoint zero is active when a driver is bound. then setup()
         * returns descriptors and otherwise cooperates with enumeration
         * and configuration management.
         */
        int                     (*bind) (struct usb_gadget *);
        void                    (*unbind) (struct usb_gadget *);
        
        /* set_address is always hidden from device drivers, as are
         * device and endpoint feature flags (get_status, set_feature,
         * and clear_feature) except that drivers may halt endpoints.
         *
         * get_descriptor must always be implemented, returning at least
         * device and configuration descriptors.  drivers must make sure
         * the endpoint descriptors match any hardware constraints. some
         * hardware also constrains other descriptors. (pxa250 allows
         * only configurations 1, 2, or 3).
         *
         * set_configuration must always be implemented, and is where
         * endpoints should be activated or (config 0) shut down.
         * likewise for set_interface, if altsettings are used
         *
         * the driver queues a response to ep0, or returns negative to stall.
         * note: the 16-bit members of the request are in cpu order.
         */
        int                     (*setup) (struct usb_gadget *,
                                        const struct usb_ctrlrequest *);

        /* called on bus or host disconnect, maybe in_interrupt().
         */
        void                    (*disconnect) (struct usb_gadget *);

        // FIXME support safe rmmod
#ifdef  HAVE_DRIVER_MODEL
        struct device_driver    driver;
#else
        char                    *name;
        void                    *driver_data;
#endif
};

#ifdef  HAVE_DRIVER_MODEL
static inline char *gadget_driver_name (struct usb_gadget_driver *driver)
        { return driver->driver.name; }

#else
static inline char *gadget_driver_name (struct usb_gadget_driver *driver)
        { return driver->name; }

#endif


/* driver modules register and unregister, as usual.
 * these calls must be made in a context that can sleep.
 *
 * these will usually be implemented directly by the hardware-dependent
 * usb bus interface driver, which will only support a single driver.
 */
int usb_gadget_register_driver (struct usb_gadget_driver *);
int usb_gadget_unregister_driver (struct usb_gadget_driver *);

#endif  /* __KERNEL__ */

#endif  /* __LINUX_USB_GADGET_H */

Reply via email to