I've gotten a few requests for more information, so
here's an update in three parts:

 * A URL, to use for further information:

     http://kernel.bkbits.net/~david-b/

 * BK repository, currently 2.5.62 plus gadget support:

     bk://kernel.bkbits.net/david-b/linux/gadget-2.5

   This has the API, and the "Gadget Zero" implementation
   that I posted last week.  Feel free to send me patches.
   (The code there is slightly updated from what I've
   posted to this list already.)

 * Appended here, the part that makes it all runnable:
   a USB simulator that currently handles bulk and
   control traffic:  "dummy_hcd.c".  It should help to
   clear up some questions that may come up if you're
   just reading the API spec and/or gadget zero code.

Pretty much anyone that can configure a kernel to run
USB can configure it to use that simulator.  One way
to use it:

  # modprobe usbcore
  # modprobe dummy_hcd
  # mount -t usbfs usb /proc/bus/usb
  # modprobe g_zero
  # lsusb
  ... shows root hub and gadget zero high speed configs
  # cat /proc/bus/usb/devices
  ... does the same, but omits some string descriptors
  #

If you've configured the "usbtest" driver, it'll hotplug
and bind to that device, and works in the testing harness:

  # testusb -a
  ... runs all the standard regression tests
  #

Or it "should" work with usb-skeleton, but I've not
made time to try.

Interesting things you could do with the code that's
there already (possibly with the aid of UML) include:

 * Read the code to understand more of how USB gadgets
   work inside, or how the API components interact.

 * Bugfix other parts of the USB stack.  I tried changing
   to the loopback config the other day (not yet usable)
   and then got an oops out of usbcore when reading the
   /proc/bus/usb/devices file. (Maybe Oliver's patch can
   help fix those problems...)

 * Provide new gadget drivers.  Many of them need nothing
   beyond control and bulk: networking, storage, HID,
   and more.  They can be tested so long as there's a
   host-side Linux driver for such gadgets, which will
   reduce the debug time that needs "real hardware".

 * Improve the simulator.  It doesn't know about data
   toggle yet, its emulation of bandwidth constraints
   is messy (may not even work if HZ < 1000), there's
   no real support for periodic transactions (though
   interrupts at period 1 msec may act ok), and it
   only supports a single device.

 * Add drivers for new USB peripheral device controllers.
   One for the PXA-250 would be particularly good to have;
   a lot of PDAs will be using that one, and it's got
   enough endpoints to be interesting.

This framework is still in early stages -- it can/should
evolve -- but it's now in an interesting and usable state.
And you don't need

Appended is the "dummy_hcd.c" code.  Notice how it's
set up to emulate one of three kinds of hardware:  the
NetChip 2280 high speed controller (PCI based), the
PXA-250, and the SA-1100 (also used with PDAs, but
extremely limited).  When Gadget Zero uses it, Kconfig
tells it to make like a net2280 ... but it's also worked
with Kconfig tweaked to use the pxa250 or sa1100 modes.

- Dave




/*
 * dummy_hcd.c -- Dummy/Loopback USB host and device emulator driver.
 *
 * Copyright (C) 2003 David Brownell
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


/*
 * This exposes a device side "USB gadget" API, driven by requests to a
 * Linux-USB host controller driver.  USB traffic is simulated; there's
 * no need for USB hardware.  Use this with two other drivers:
 *
 *  - Gadget driver, responding to requests (slave);
 *  - Host-side device driver, as already familiar in Linux.
 *
 * Having this all in one kernel can help some stages of development,
 * bypassing some hardware (and driver) issues.  UML could help too.
 */

#define DEBUG

#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/smp_lock.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/version.h>

#include <linux/usb.h>
#include <linux/usb_gadget.h>

#include <asm/byteorder.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/system.h>
#include <asm/unaligned.h>


#include "../core/hcd.h"


#define DRIVER_VERSION	"31 Jan 2003"
static const char	driver_name [] = "dummy_hcd";
static const char	driver_desc [] = "USB Host+Gadget Emulator";

MODULE_DESCRIPTION (driver_desc);
MODULE_AUTHOR ("David Brownell");
MODULE_LICENSE ("GPL");

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

/* gadget side driver data structres */
struct dummy_ep {
	struct list_head		queue;
	unsigned long			last_io;	/* jiffies timestamp */
	struct usb_gadget		*gadget;
	const struct usb_endpoint_descriptor *desc;
	struct usb_ep			ep;
	unsigned			halted : 1;
};

struct dummy_request {
	struct list_head		queue;		/* ep's requests */
	struct usb_request		req;
};

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

/*
 * Every device has ep0 for control requests, plus up to 30 more endpoints,
 * in one of two types:
 *
 *   - Configurable:  direction (in/out), type (bulk, iso, etc), and endpoint
 *     number can be changed.  Names like "ep-a" are used for this type.
 *
 *   - Fixed Function:  in other cases.  some characteristics may be mutable;
 *     that'd be hardware-specific.  Names like "ep12out-bulk" are used.
 *
 * Gadget drivers are responsible for not setting up conflicting endpoint
 * configurations, illegal or unsupported packet lengths, and so on.
 */

static const char ep0name [] = "ep0";

static const char *const ep_name [] = {
	ep0name,				/* everyone has ep0 */

	/* act like a net2280: high speed, six configurable endpoints */
	"ep-a", "ep-b", "ep-c", "ep-d", "ep-e", "ep-f",

	/* or like pxa250: fifteen fixed function endpoints */
	"ep1in-bulk", "ep2out-bulk", "ep3in-iso", "ep4out-iso", "ep5in-int",
	"ep6in-bulk", "ep7out-bulk", "ep8in-iso", "ep9out-iso", "ep10in-int",
	"ep11in-bulk", "ep12out-bulk", "ep13in-iso", "ep14out-iso",
		"ep15in-int",

	/* or like sa1100: two fixed function endpoints */
	"ep1out-bulk", "ep2in-bulk",
};
#define DUMMY_ENDPOINTS	(sizeof(ep_name)/sizeof(char *))

struct dummy {
	spinlock_t			lock;

	/*
	 * SLAVE/GADGET side support
	 */
	struct dummy_ep			ep [DUMMY_ENDPOINTS];
	int				address;
	struct usb_gadget		gadget;
	struct usb_gadget_driver	*driver;

	struct hcd_dev			*hdev;

	/*
	 * MASTER/HOST side support
	 */
	struct usb_hcd			hcd;
	struct sys_device		dev;
	struct timer_list		timer;
	u32				port_status;
};

static struct dummy	*the_controller;

static inline struct dummy *ep_to_dummy (struct dummy_ep *ep)
{
	return container_of (ep->gadget, struct dummy, gadget);
}

/*
 * This "hardware" may look a bit odd in diagnostics since it's got both
 * host and device sides; and it binds different drivers to each side.
 */
#define hardware	(&the_controller->dev.dev)

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

static struct device_driver dummy_driver = {
	.name		= (char *) driver_name,
	.bus		= &system_bus_type,
};

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

/* SLAVE/GADGET SIDE DRIVER
 *
 * This only tracks gadget state.  All the work is done when the host
 * side tries some (emulated) i/o operation.  Real device controller
 * drivers would do real i/o using dma, fifos, irqs, timers, etc.
 */

#define is_enabled() \
	(the_controller->port_status & USB_PORT_STAT_ENABLE)

static int
dummy_enable (struct usb_ep *_ep, const struct usb_endpoint_descriptor *desc)
{
	struct dummy		*dev;
	struct dummy_ep		*ep;
	unsigned		max;
	int			retval;

	ep = container_of (_ep, struct dummy_ep, ep);
	if (!_ep || !desc || ep->desc || _ep->name == ep0name
			|| desc->bDescriptorType != USB_DT_ENDPOINT)
	if (!the_controller->driver || !is_enabled ())
		return -ESHUTDOWN;
	max = desc->wMaxPacketSize & 0x3ff;

	/* drivers must not request bad settings, since lower levels
	 * (hardware or its drivers) may not check.  some endpoints
	 * can't do iso, many have maxpacket limitations, etc.
	 *
	 * since this "hardware" driver is here to help debugging, we
	 * have some extra sanity checks.  (there could be more though,
	 * especially for "ep9out" style fixed function ones.)
	 */
	dev = container_of (ep->gadget, struct dummy, gadget);
	retval = -EINVAL;
	switch (desc->bmAttributes & 0x03) {
	case USB_ENDPOINT_XFER_BULK:
		if (strstr (ep->ep.name, "-iso")
				|| strstr (ep->ep.name, "-int")) {
			goto done;
		}
		switch (dev->gadget.speed) {
		case USB_SPEED_HIGH:
			if (max == 512)
				break;
			/* conserve return statements */
		default:
			switch (max) {
			case 8: case 16: case 32: case 64:
				/* we'll fake any legal size */
				break;
			default:
		case USB_SPEED_LOW:
				goto done;
			}
		}
		break;
	case USB_ENDPOINT_XFER_INT:
		if (strstr (ep->ep.name, "-iso")) /* bulk is ok */
			goto done;
		/* real hardware might not handle all packet sizes */
		switch (dev->gadget.speed) {
		case USB_SPEED_HIGH:
			if (max <= 1024)
				break;
			/* save a return statement */
		case USB_SPEED_FULL:
			if (max <= 64)
				break;
			/* save a return statement */
		default:
			if (max <= 8)
				break;
			goto done;
		}
		break;
	case USB_ENDPOINT_XFER_ISOC:
		if (strstr (ep->ep.name, "-bulk")
				|| strstr (ep->ep.name, "-int"))
			goto done;
		/* real hardware might not handle all packet sizes */
		switch (dev->gadget.speed) {
		case USB_SPEED_HIGH:
			if (max <= 1024)
				break;
			/* save a return statement */
		case USB_SPEED_FULL:
			if (max <= 1023)
				break;
			/* save a return statement */
		default:
			goto done;
		}
		break;
	default:
		/* few chips support control except on ep0 */
		goto done;
	}

	_ep->maxpacket = max;
	ep->desc = desc;

	dev_dbg (hardware, "enabled %s (ep%d%s-%s) maxpacket %d\n",
		_ep->name,
		desc->bEndpointAddress & 0x0f,
		(desc->bEndpointAddress & USB_DIR_IN) ? "in" : "out",
		({ char *val;
		 switch (desc->bmAttributes & 0x03) {
		 case USB_ENDPOINT_XFER_BULK: val = "bulk"; break;
		 case USB_ENDPOINT_XFER_ISOC: val = "iso"; break;
		 case USB_ENDPOINT_XFER_INT: val = "intr"; break;
		 default: val = "ctrl"; break;
		 }; val; }),
		max);

	/* at this point real hardware should be NAKing transfers
	 * to that endpoint, until a buffer is queued to it.
	 */
	retval = 0;
done:
	return retval;
}

/* called with spinlock held */
static void nuke (struct dummy *dev, struct dummy_ep *ep)
{
	while (!list_empty (&ep->queue)) {
		struct dummy_request	*req;

		req = list_entry (ep->queue.next, struct dummy_request, queue);
		list_del_init (&req->queue);
		req->req.status = -ESHUTDOWN;

		spin_unlock (&dev->lock);
		req->req.complete (&ep->ep, &req->req);
		spin_lock (&dev->lock);
	}
}

static int dummy_disable (struct usb_ep *_ep)
{
	struct dummy_ep		*ep;
	struct dummy		*dev;
	unsigned long		flags;
	int			retval;

	ep = container_of (_ep, struct dummy_ep, ep);
	if (!_ep || !ep->desc || _ep->name == ep0name)
		return -EINVAL;
	dev = ep_to_dummy (ep);

	spin_lock_irqsave (&dev->lock, flags);
	ep->desc = 0;
	retval = 0;
	nuke (dev, ep);
	spin_unlock_irqrestore (&dev->lock, flags);

	dev_dbg (hardware, "disabled %s\n", _ep->name);
	return retval;
}

static struct usb_request *
dummy_alloc_request (struct usb_ep *_ep, int mem_flags)
{
	struct dummy_ep		*ep;
	struct dummy_request	*req;

	ep = container_of (_ep, struct dummy_ep, ep);
	if (!_ep || (!ep->desc && _ep->name != ep0name))
		return 0;
	if (!the_controller->driver)
		return 0;

	req = kmalloc (sizeof *req, mem_flags);
	if (!req)
		return 0;
	memset (req, 0, sizeof *req);
	INIT_LIST_HEAD (&req->queue);
	return &req->req;
}

static void
dummy_free_request (struct usb_ep *_ep, struct usb_request *_req)
{
	struct dummy_ep		*ep;
	struct dummy_request	*req;

	ep = container_of (_ep, struct dummy_ep, ep);
	if (!ep || !_req || (!ep->desc && _ep->name != ep0name))
		return;

	req = container_of (_req, struct dummy_request, req);
	WARN_ON (!list_empty (&req->queue));
	kfree (req);
}

static void *
dummy_alloc_buffer (
	struct usb_ep *_ep,
	unsigned bytes,
	dma_addr_t *dma,
	int mem_flags
) {
	char *retval;

	if (!the_controller->driver)
		return 0;
	retval = kmalloc (bytes, mem_flags);
	*dma = (dma_addr_t) retval;
	return retval;
}

static void
dummy_free_buffer (
	struct usb_ep *_ep,
	void *buf,
	dma_addr_t dma,
	unsigned bytes
) {
	if (bytes)
		kfree (buf);
}

static int
dummy_queue (struct usb_ep *_ep, struct usb_request *_req, int mem_flags)
{
	struct dummy_ep		*ep;
	struct dummy_request	*req;
	struct dummy		*dev;
	unsigned long		flags;

	req = container_of (_req, struct dummy_request, req);
	if (!_req || !list_empty (&req->queue) || !_req->complete)
		return -EINVAL;

	ep = container_of (_ep, struct dummy_ep, ep);
	if (!_ep || (!ep->desc && _ep->name != ep0name))
		return -EINVAL;

	if (!the_controller->driver || !is_enabled ())
		return -ESHUTDOWN;

	dev = container_of (ep->gadget, struct dummy, gadget);

#if 0
	dev_dbg (hardware, "ep %p queue req %p to %s, len %d buf %p\n",
			ep, _req, _ep->name, _req->length, _req->buf);
#endif

	_req->status = -EINPROGRESS;
	_req->actual = 0;
	spin_lock_irqsave (&dev->lock, flags);
	list_add_tail (&req->queue, &ep->queue);
	spin_unlock_irqrestore (&dev->lock, flags);

	/* real hardware would likely enable transfers here, in case
	 * it'd been left NAKing.
	 */
	return 0;
}

static int dummy_dequeue (struct usb_ep *_ep, struct usb_request *_req)
{
	struct dummy_ep		*ep;
	struct dummy		*dev;
	int			retval = -EINVAL;
	unsigned long		flags;
	struct dummy_request	*req = 0;

	if (!the_controller->driver)
		return -ESHUTDOWN;

	if (!_ep || !_req)
		return retval;
	ep = container_of (_ep, struct dummy_ep, ep);
	dev = container_of (ep->gadget, struct dummy, gadget);

	spin_lock_irqsave (&dev->lock, flags);
	list_for_each_entry (req, &ep->queue, queue) {
		if (&req->req == _req) {
			list_del_init (&req->queue);
			_req->status = -ECONNRESET;
			retval = 0;
			break;
		}
	}
	spin_unlock_irqrestore (&dev->lock, flags);

	if (retval == 0) {
		dev_dbg (hardware, "dequeued req %p from %s, len %d buf %p\n",
				req, _ep->name, _req->length, _req->buf);

		_req->complete (_ep, _req);
	}
	return retval;
}

static int
dummy_set_halt (struct usb_ep *_ep, int value)
{
	struct dummy_ep		*ep;

	if (!_ep)
		return -EINVAL;
	if (!the_controller->driver)
		return -ESHUTDOWN;
	ep = container_of (_ep, struct dummy_ep, ep);
	ep->halted = (value != 0);
	/* FIXME clear emulated data toggle too */
	return 0;
}

static const struct usb_ep_ops dummy_ep_ops = {
	.enable		= dummy_enable,
	.disable	= dummy_disable,

	.alloc_request	= dummy_alloc_request,
	.free_request	= dummy_free_request,

	.alloc_buffer	= dummy_alloc_buffer,
	.free_buffer	= dummy_free_buffer,
	/* map, unmap, ... eventually hook the "generic" dma calls */

	.queue		= dummy_queue,
	.dequeue	= dummy_dequeue,

	.set_halt	= dummy_set_halt,
};

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

/* there are both host and device side versions of this call ... */
static int dummy_g_get_frame (struct usb_gadget *_gadget)
{
	struct timeval	tv;

	do_gettimeofday (&tv);
	return tv.tv_usec / 1000;
}

static const struct usb_gadget_ops dummy_ops = {
	.get_frame	= dummy_g_get_frame,
};

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

/* "function" sysfs attribute */
static ssize_t
show_function (struct device *_dev, char *buf)
{
	struct dummy	*dev = the_controller;

	if (!dev->driver->function
			|| strlen (dev->driver->function) > PAGE_SIZE)
		return 0;
	return snprintf (buf, PAGE_SIZE, "%s\n", dev->driver->function);
}
DEVICE_ATTR (function, S_IRUGO, show_function, NULL);

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

/*
 * Driver registration/unregistration.
 *
 * This is basically hardware-specific; there's usually only one real USB
 * device (not host) controller since that's how USB devices are intended
 * to work.  So most implementations of these api calls will rely on the
 * fact that only one driver will ever bind to the hardware.  But curious
 * hardware can be built with discrete components, so the gadget API doesn't
 * require that assumption.
 *
 * For this emulator, it might be convenient to create a usb slave device
 * for each driver that registers:  just add to a big root hub.
 */

int
usb_gadget_register_driver (struct usb_gadget_driver *driver)
{
	struct dummy	*dev = the_controller;
	int		retval, i;

	if (!dev)
		return -EINVAL;
	if (dev->driver)
		return -EBUSY;
	if (!driver->bind || !driver->unbind || !driver->setup
			|| driver->speed == USB_SPEED_UNKNOWN)
		return -EINVAL;

	/*
	 * SLAVE side init ... the layer above hardware, which
	 * can't enumerate without help from the driver we're binding.
	 */
	strcpy (dev->gadget.dev.bus_id, "udc");
	strncpy (dev->gadget.dev.name, "usb device controller emulator",
			sizeof dev->gadget.dev.name);
	dev->gadget.dev.parent = &dev->dev.dev;

	INIT_LIST_HEAD (&dev->gadget.ep_list);
	for (i = 0; i < DUMMY_ENDPOINTS; i++) {
		struct dummy_ep	*ep = &dev->ep [i];

		if (!ep_name [i])
			break;
		ep->ep.name = ep_name [i];
		ep->ep.ops = &dummy_ep_ops;
		list_add_tail (&ep->ep.ep_list, &dev->gadget.ep_list);
		ep->halted = 0;
		ep->ep.maxpacket = ~0;
		ep->last_io = jiffies;
		ep->gadget = &dev->gadget;
		ep->desc = 0;
		INIT_LIST_HEAD (&ep->queue);
	}

	dev->gadget.ep0 = &dev->ep [0].ep;
	dev->ep [0].ep.maxpacket = 64;
	list_del_init (&dev->ep [0].ep.ep_list);

	dev->driver = driver;
	dev->gadget.dev.driver = &driver->driver;
	dev_dbg (hardware, "binding gadget driver '%s'\n", driver->driver.name);
	if ((retval = driver->bind (&dev->gadget)) != 0) {
		dev->driver = 0;
		return retval;
	}

#if 0
	// driver->driver.bus = &system_bus_type,
	driver_register (&driver->driver);
#endif

	device_register (&dev->gadget.dev);
	device_create_file (&dev->gadget.dev, &dev_attr_function);

	/* khubd will enumerate this in a while */
	dev->port_status = USB_PORT_STAT_CONNECTION
		| (1 << USB_PORT_FEAT_C_CONNECTION);
	return 0;
}
EXPORT_SYMBOL (usb_gadget_register_driver);

/* caller must hold lock */
static void
stop_activity (struct dummy *dev, struct usb_gadget_driver *driver)
{
	struct dummy_ep	*ep;

	/* prevent any more requests */
	dev->hdev = 0;
	dev->address = 0;
	dev->port_status = 0;

	/* this might not succeed ... */
	del_timer (&dev->timer);

	/* nuke any pending requests first, so driver i/o is quiesced */
	list_for_each_entry (ep, &dev->gadget.ep_list, ep.ep_list)
		nuke (dev, ep);

	/* driver now does any non-usb quiescing necessary */
	if (driver) {
		spin_unlock (&dev->lock);
		driver->disconnect (&dev->gadget);
		spin_lock (&dev->lock);
	}
}

int
usb_gadget_unregister_driver (struct usb_gadget_driver *driver)
{
	struct dummy	*dev = the_controller;
	unsigned long	flags;

	if (!dev)
		return -ENODEV;
	if (!driver || driver != dev->driver)
		return -EINVAL;

	dev_dbg (hardware, "unregister gadget driver '%s'\n",
			driver->driver.name);

	spin_lock_irqsave (&dev->lock, flags);
	stop_activity (dev, driver);
	spin_unlock_irqrestore (&dev->lock, flags);

	driver->unbind (&dev->gadget);
	dev->driver = 0;

	device_remove_file (&dev->gadget.dev, &dev_attr_function);
	device_unregister (&dev->gadget.dev);

#if 0
// FIXME this hangs
dev_warn (hardware, "about to hang? ...\n");
	driver_unregister (&driver->driver);
dev_dbg (hardware, "gadget driver gone...\n");
#endif

	del_timer_sync (&dev->timer);

	/* host side hub driver notices this later */
	dev->port_status = (1 << USB_PORT_FEAT_C_CONNECTION);
	return 0;
}
EXPORT_SYMBOL (usb_gadget_unregister_driver);

#undef is_enabled

int net2280_set_fifo_mode (struct usb_gadget *gadget, int mode)
{
	return -ENOSYS;
}
EXPORT_SYMBOL (net2280_set_fifo_mode);

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

/* MASTER/HOST SIDE DRIVER
 *
 * this uses the hcd framework to hook up to host side drivers.
 * its root hub will only have one device, otherwise it acts like
 * a normal host controller.
 *
 * when urbs are queued, they're just stuck on a list that we
 * scan in a timer callback.  that callback connects writes from
 * the host with reads from the device, and so on, based on the
 * usb 2.0 rules.
 */

static int dummy_urb_enqueue (
	struct usb_hcd	*hcd,
	struct urb	*urb,
	int		mem_flags
) {
	struct dummy	*dev;
	unsigned long	flags;

	/* patch to usb_sg_init() is in 2.5.60 */
	BUG_ON (!urb->transfer_buffer && urb->transfer_buffer_length);

	dev = container_of (hcd, struct dummy, hcd);
	spin_lock_irqsave (&dev->lock, flags);

	if (!dev->hdev)
		dev->hdev = urb->dev->hcpriv;
	urb->hcpriv = dev;

	/* kick the scheduler, it'll do the rest */
	if (!timer_pending (&dev->timer))
		mod_timer (&dev->timer, jiffies + 1);

	spin_unlock_irqrestore (&dev->lock, flags);
	return 0;
}

static int dummy_urb_dequeue (struct usb_hcd *hcd, struct urb *urb)
{
	/* giveback happens automatically in timer callback */
	return 0;
}

static void maybe_set_status (struct urb *urb, int status)
{
	spin_lock (&urb->lock);
	if (urb->status == -EINPROGRESS)
		urb->status = status;
	spin_unlock (&urb->lock);
}

/* transfer up to a frame's worth; caller must own lock */
static int
transfer (struct dummy *dev, struct urb *urb, struct dummy_ep *ep, int limit)
{
	struct dummy_request	*req;

top:
	/* if there's no request queued, the device is NAKing; return */
	list_for_each_entry (req, &ep->queue, queue) {
		unsigned	host_len, dev_len, len;
		int		is_short, to_host;
		int		rescan = 0;

		/* 1..N packets of ep->ep.maxpacket each ... the last one
		 * may be short (including zero length).
		 *
		 * writer can send a zlp explicitly (length 0) or implicitly
		 * (length mod maxpacket zero, and 'zero' flag); they always
		 * terminate reads.
		 */
		host_len = urb->transfer_buffer_length - urb->actual_length;
		dev_len = req->req.length - req->req.actual;
		len = min (host_len, dev_len);

		/* FIXME update emulated data toggle too */

		to_host = usb_pipein (urb->pipe);
		if (unlikely (len == 0))
			is_short = 1;
		else {
			char		*ubuf, *rbuf;

			/* not enough bandwidth left? */
			if (limit < ep->ep.maxpacket && limit < len)
				break;
			len = min (len, (unsigned) limit);
			if (len == 0)
				break;

			/* use an extra pass for the final short packet */
			if (len > ep->ep.maxpacket) {
				rescan = 1;
				len -= (len % ep->ep.maxpacket);
			}
			is_short = (len % ep->ep.maxpacket) != 0;

			/* else transfer packet(s) */
			ubuf = urb->transfer_buffer + urb->actual_length;
			rbuf = req->req.buf + req->req.actual;
			if (to_host)
				memcpy (ubuf, rbuf, len);
			else
				memcpy (rbuf, ubuf, len);
			ep->last_io = jiffies;

			limit -= len;
			urb->actual_length += len;
			req->req.actual += len;
		}

		/* short packets terminate, maybe with overflow/underflow.
		 * it's only really an error to write too much.
		 *
		 * partially filling a buffer optionally blocks queue advances
		 * (so completion handlers can clean up the queue) but we don't
		 * need to emulate such data-in-flight.  so we only show part
		 * of the URB_SHORT_NOT_OK effect: completion status.
		 */
		if (is_short) {
			if (host_len == dev_len) {
				req->req.status = 0;
				maybe_set_status (urb, 0);
			} else if (to_host) {
				if (dev_len > host_len) {
					req->req.status = -EOVERFLOW;
					maybe_set_status (urb, -EOVERFLOW);
				} else {
					req->req.status = 0;
					maybe_set_status (urb,
						(urb->transfer_flags
							& URB_SHORT_NOT_OK)
						? -EREMOTEIO : 0);
				}
			} else if (!to_host) {
				if (host_len > dev_len) {
					req->req.status = -EOVERFLOW;
					maybe_set_status (urb, -EOVERFLOW);
				} else {
					req->req.status = 0;
					maybe_set_status (urb, 0);
				}
			}

		/* many requests terminate without a short packet */
		} else {
			if (req->req.length == req->req.actual
					&& !req->req.zero)
				req->req.status = 0;
			if (urb->transfer_buffer_length == urb->actual_length
					&& !(urb->transfer_flags
						& URB_ZERO_PACKET))
				maybe_set_status (urb, 0);
		}

		/* device side completion --> continuable */
		if (req->req.status != -EINPROGRESS) {
			list_del_init (&req->queue);

			spin_unlock (&dev->lock);
			req->req.complete (&ep->ep, &req->req);
			spin_lock (&dev->lock);

			/* requests might have been unlinked... */
			rescan = 1;
		}

		/* host side completion --> terminate */
		if (urb->status != -EINPROGRESS)
			break;

		/* rescan to continue with any other queued i/o */
		if (rescan)
			goto top;
	}
	return limit;
}

static int periodic_bytes (struct dummy *dev, struct dummy_ep *ep)
{
	int	limit = ep->ep.maxpacket;

	if (dev->gadget.speed == USB_SPEED_HIGH) {
		int	tmp;

		/* high bandwidth mode */
		tmp = ep->desc->wMaxPacketSize;
		tmp = le16_to_cpu (tmp);
		tmp = (tmp >> 11) & 0x03;
		tmp *= 8 /* applies to entire frame */;
		limit += limit * tmp;
	}
	return limit;
}

#define Dev_Request	(USB_TYPE_STANDARD | USB_RECIP_DEVICE)
#define Dev_InRequest	(Dev_Request | USB_DIR_IN)
#define Intf_Request	(USB_TYPE_STANDARD | USB_RECIP_INTERFACE)
#define Intf_InRequest	(Intf_Request | USB_DIR_IN)
#define Ep_Request	(USB_TYPE_STANDARD | USB_RECIP_ENDPOINT)
#define Ep_InRequest	(Ep_Request | USB_DIR_IN)

/* drive both sides of the transfers; looks like irq handlers to
 * both drivers except the callbacks aren't in_irq().
 */
static void dummy_timer (unsigned long _dev)
{
	struct dummy		*dev = (struct dummy *) _dev;
	struct hcd_dev		*hdev = dev->hdev;
	struct list_head	*entry, *tmp;
	unsigned long		flags;
	int			limit, total;

	if (!hdev) {
		dev_err (hardware, "timer fired with device gone?\n");
		return;
	}

	/* simplistic model for one frame's bandwidth */
	switch (dev->gadget.speed) {
	case USB_SPEED_LOW:
		total = 8/*bytes*/ * 12/*packets*/;
		break;
	case USB_SPEED_FULL:
		total = 64/*bytes*/ * 19/*packets*/;
		break;
	case USB_SPEED_HIGH:
		total = 512/*bytes*/ * 13/*packets*/ * 8/*uframes*/;
		break;
	default:
		dev_err (hardware, "bogus device speed\n");
		return;
	}

	/* FIXME if HZ != 1000 this will probably misbehave ... */

	/* look at each urb queued by the host side driver */
	spin_lock_irqsave (&dev->lock, flags);
restart:
	list_for_each_safe (entry, tmp, &hdev->urb_list) {
		struct urb		*urb;
		struct dummy_request	*req;
		u8			address;
		struct dummy_ep		*ep = 0;
		int			type;

		urb = list_entry (entry, struct urb, urb_list);
		if (urb->status != -EINPROGRESS) {
			/* likely it was just unlinked */
			goto return_urb;
		}
		type = usb_pipetype (urb->pipe);

		/* used up this frame's non-periodic bandwidth?
		 * FIXME there's infinite bandwidth for control and
		 * periodic transfers ... unrealistic.
		 */
		if (total <= 0 && type == PIPE_BULK)
			continue;

		/* find the gadget's ep for this request (if configured) */
		address = usb_pipeendpoint (urb->pipe);
		if (address == 0)
			ep = &dev->ep [0];
		else {
			int	i;

			if (usb_pipein (urb->pipe))
				address |= USB_DIR_IN;
			for (i = 1; i < DUMMY_ENDPOINTS; i++) {
				ep = &dev->ep [i];
				if (!ep->desc)
					continue;
				if (ep->desc->bEndpointAddress == address)
					break;
			}
			if (i == DUMMY_ENDPOINTS) {
				/* set_configuration() disagreement */
				dev_err (hardware,
					"no ep configured for urb %p\n",
					urb);
				maybe_set_status (urb, -ETIMEDOUT);
				goto return_urb;
			}
			if (ep->halted) {
				/* NOTE: must not be iso! */
				dev_dbg (hardware, "ep %s halted, urb %p\n",
						ep->ep.name, urb);
				maybe_set_status (urb, -EPIPE);
				goto return_urb;
			}
			/* FIXME make sure both ends agree on maxpacket */
		}

		/* handle control requests */
		if (ep == &dev->ep [0]) {
			struct usb_ctrlrequest		setup;
			int				value = 1;

			setup = *(struct usb_ctrlrequest*) urb->setup_packet;
			le16_to_cpus (&setup.wIndex);
			le16_to_cpus (&setup.wValue);
			le16_to_cpus (&setup.wLength);
			if (setup.wLength != urb->transfer_buffer_length) {
				maybe_set_status (urb, -EOVERFLOW);
				goto return_urb;
			}

			/* paranoia, in case of stale queued data */
			list_for_each_entry (req, &ep->queue, queue) {
				list_del_init (&req->queue);
				req->req.status = -EOVERFLOW;
				dev_dbg (hardware, "stale req = %p\n", req);

				spin_unlock (&dev->lock);
				req->req.complete (&ep->ep, &req->req);
				spin_lock (&dev->lock);
				goto restart;
			}

			/* gadget driver never sees set_address or operations
			 * on standard feature flags.  some hardware doesn't
			 * even expose them.
			 */
			ep->last_io = jiffies;
			switch (setup.bRequest) {
			case USB_REQ_SET_ADDRESS:
				if (setup.bRequestType != Dev_Request)
					break;
				if (dev->address != 0) {
					maybe_set_status (urb, -ETIMEDOUT);
					urb->actual_length = 0;
					goto return_urb;
				}
				dev->address = setup.wValue;
				maybe_set_status (urb, 0);
				dev_dbg (hardware, "set_address = %d\n",
						setup.wValue);
				value = 0;
				break;
			case USB_REQ_SET_FEATURE:
				if (setup.bRequestType == Dev_Request) {
					// remote wakeup, and (hs) test mode
					value = -EOPNOTSUPP;
				} else if (setup.bRequestType == Ep_Request) {
					// FIXME endpoint halt
				}
				break;
			case USB_REQ_CLEAR_FEATURE:
				if (setup.bRequestType == Dev_Request) {
					// remote wakeup
					value = 0;
					maybe_set_status (urb, 0);
				} else if (setup.bRequestType == Ep_Request) {
					// FIXME endpoint halt
				}
				break;
			case USB_REQ_GET_STATUS:
				if (setup.bRequestType == Dev_InRequest
						|| setup.bRequestType
							== Intf_InRequest
						|| setup.bRequestType
							== Ep_InRequest
						) {
					char *buf;

					// device: remote wakeup, selfpowered
					// interface: nothing
					// device: halt
					buf = (char *)urb->transfer_buffer;
					if (urb->transfer_buffer_length > 0) {
						buf [0] = 0;
						// FIXME report ep halt...
					}
					if (urb->transfer_buffer_length > 1)
						buf [1] = 0;
					urb->actual_length = min (2,
						urb->transfer_buffer_length);
					value = 0;
					maybe_set_status (urb, 0);
				}
				break;
			}

			/* gadget driver handles all other requests.  block
			 * until setup() returns; no reentrancy issues etc.
			 */
			if (value > 0) {
				spin_unlock (&dev->lock);
				value = dev->driver->setup (&dev->gadget,
						&setup);
				spin_lock (&dev->lock);

				if (value < 0) {
					/* error, see below */
				} else if (setup.wLength != 0
						&& list_empty (&ep->queue)) {
					dev_dbg (hardware, "%s setup didn't\n",
						dev->driver->driver.name);
					maybe_set_status (urb, -EPROTO);
					urb->actual_length = 0;
				} else {
					/* no delays (max 64KB data stage) */
					transfer (dev, urb, ep, 64*1024);
					maybe_set_status (urb, 0);
				}
			}

			if (value < 0) {
				if (value != -EOPNOTSUPP)
					dev_dbg (hardware,
						"setup --> %d\n",
						value);
				maybe_set_status (urb, -EPIPE);
				urb->actual_length = 0;
			}

			goto return_urb;
		}

		/* non-control requests */
		limit = total;
		switch (usb_pipetype (urb->pipe)) {
		case PIPE_ISOCHRONOUS:
			/* FIXME is it urb->interval since the last xfer?
			 * use urb->iso_frame_desc[i].
			 * complete whether or not ep has requests queued.
			 * report random errors, to debug drivers.
			 */
			limit = max (limit, periodic_bytes (dev, ep));
			maybe_set_status (urb, -ENOSYS);
			break;

		case PIPE_INTERRUPT:
			/* FIXME is it urb->interval since the last xfer?
			 * this almost certainly polls too fast.
			 */
			limit = max (limit, periodic_bytes (dev, ep));
			/* FALLTHROUGH */

		// case PIPE_BULK:
		default:
			ep->last_io = jiffies;
			total = transfer (dev, urb, ep, limit);
			break;
		}

		/* incomplete transfer? */
		if (urb->status == -EINPROGRESS)
			continue;

return_urb:
		urb->hcpriv = 0;

		spin_unlock (&dev->lock);
		usb_hcd_giveback_urb (&dev->hcd, urb, 0);
		spin_lock (&dev->lock);

		goto restart;
	}

	/* want a 1 msec delay here */
	if (!list_empty (&hdev->urb_list))
		mod_timer (&dev->timer, jiffies + 1);

	spin_unlock_irqrestore (&dev->lock, flags);
}

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

static void dummy_free_config (struct usb_hcd *hcd, struct usb_device *udev)
{
	struct dummy		*dev;

	dev = container_of (hcd, struct dummy, hcd);
	if (dev->address != 0 || dev->hdev != 0)
		dev_err (hardware, "bogus free_config, device still in use\n");
}

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

#define PORT_C_MASK \
	 ((1 << USB_PORT_FEAT_C_CONNECTION) \
	| (1 << USB_PORT_FEAT_C_ENABLE) \
	| (1 << USB_PORT_FEAT_C_SUSPEND) \
	| (1 << USB_PORT_FEAT_C_OVER_CURRENT) \
	| (1 << USB_PORT_FEAT_C_RESET))

static int dummy_hub_status (struct usb_hcd *hcd, char *buf)
{
	struct dummy		*dev;
	unsigned long		flags;
	int			retval;

	dev = container_of (hcd, struct dummy, hcd);

	spin_lock_irqsave (&dev->lock, flags);
	if (!(dev->port_status & PORT_C_MASK))
		retval = 0;
	else {
		*buf = (1 << 1);
		dev_dbg (hardware, "port status 0x%08x has changes\n",
			dev->port_status);
		retval = 1;
	}
	spin_unlock_irqrestore (&dev->lock, flags);
	return retval;
}

static inline void
hub_descriptor (struct usb_hub_descriptor *desc)
{
	memset (desc, 0, sizeof *desc);
	desc->bDescriptorType = 0x29;
	desc->bDescLength = 9;
	desc->wHubCharacteristics = cpu_to_le16 (0x0001);
	desc->bNbrPorts = 1;
	desc->bitmap [0] = 0xff;
	desc->bitmap [1] = 0xff;
}

static int dummy_hub_control (
	struct usb_hcd	*hcd,
	u16		typeReq,
	u16		wValue,
	u16		wIndex,
	char		*buf,
	u16		wLength
) {
	struct dummy	*dev;
	int		retval = 0;
	unsigned long	flags;

	dev = container_of (hcd, struct dummy, hcd);
	spin_lock_irqsave (&dev->lock, flags);
	switch (typeReq) {
	case ClearHubFeature:
		break;
	case ClearPortFeature:
		// FIXME won't some of these need special handling?
		dev->port_status &= ~(1 << wValue);
		break;
	case GetHubDescriptor:
		hub_descriptor ((struct usb_hub_descriptor *) buf);
		break;
	case GetHubStatus:
		*(u32 *) buf = cpu_to_le32 (0);
		break;
	case GetPortStatus:
		if (wIndex != 1)
			retval = -EPIPE;
		*(u32 *) buf = cpu_to_le32 (dev->port_status);
		break;
	case SetHubFeature:
		retval = -EPIPE;
		break;
	case SetPortFeature:
		if (wValue == USB_PORT_FEAT_RESET) {
			/* if it's already running, disconnect first */
			if (dev->port_status & USB_PORT_STAT_ENABLE) {
				dev->port_status &= ~USB_PORT_STAT_ENABLE;
				dev_dbg (hardware, "disconnect gadget\n");

				stop_activity (dev, dev->driver);

				/* FIXME test that code path! */
			}

			dev->port_status |=
				  (1 << USB_PORT_FEAT_C_RESET)
				| USB_PORT_STAT_ENABLE;

			/* give it the best speed we agree on */
			dev->gadget.speed = dev->driver->speed;
			dev->gadget.ep0->maxpacket = 64;
			switch (dev->gadget.speed) {
			case USB_SPEED_HIGH:
				dev->port_status |= USB_PORT_STAT_HIGH_SPEED;
				break;
			case USB_SPEED_LOW:
				dev->gadget.ep0->maxpacket = 8;
				dev->port_status |= USB_PORT_STAT_LOW_SPEED;
				break;
			default:
				dev->gadget.speed = USB_SPEED_FULL;
				break;
			}
		} else
			dev->port_status |= (1 << wValue);
		break;

	default:
		dev_dbg (hardware,
			"hub control req%04x v%04x i%04x l%d\n",
			typeReq, wValue, wIndex, wLength);

		/* "protocol stall" on error */
		retval = -EPIPE;
	}
	spin_unlock_irqrestore (&dev->lock, flags);
	return retval;
}


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

static struct usb_hcd *dummy_alloc (void)
{
	struct dummy		*dev;

	dev = kmalloc (sizeof *dev, SLAB_KERNEL);
	if (dev == NULL)
		return 0;
	memset (dev, 0, sizeof *dev);
	return &dev->hcd;
}

static void dummy_free (struct usb_hcd *hcd)
{
	struct dummy		*dev;

	dev = container_of (hcd, struct dummy, hcd);
	WARN_ON (dev->driver != 0);
	kfree (dev);
}

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

static inline ssize_t
show_urb (char *buf, size_t size, struct urb *urb)
{
	int ep = usb_pipeendpoint (urb->pipe);

	return snprintf (buf, size,
		"urb/%p %s ep%d%s%s len %d/%d\n",
		urb,
		({ char *s;
		 switch (urb->dev->speed) {
		 case USB_SPEED_LOW:	s = "ls"; break;
		 case USB_SPEED_FULL:	s = "fs"; break;
		 case USB_SPEED_HIGH:	s = "hs"; break;
		 default:		s = "?"; break;
		 }; s; }),
		ep, ep ? (usb_pipein (urb->pipe) ? "in" : "out") : "",
		({ char *s; \
		 switch (usb_pipetype (urb->pipe)) { \
		 case PIPE_CONTROL:	s = ""; break; \
		 case PIPE_BULK:	s = "-bulk"; break; \
		 case PIPE_INTERRUPT:	s = "-int"; break; \
		 default: 		s = "-iso"; break; \
		}; s;}),
		urb->actual_length, urb->transfer_buffer_length);
}

static ssize_t
show_urbs (struct device *dev, char *buf)
{
	struct dummy		*dummy = dev->driver_data;
	struct urb		*urb;
	size_t			size = 0;
	unsigned long		flags;

	spin_lock_irqsave (&dummy->lock, flags);
	if (dummy->hdev) {
		list_for_each_entry (urb, &dummy->hdev->urb_list, urb_list) {
			size_t		temp;

			temp = show_urb (buf, PAGE_SIZE - size, urb);
			buf += temp;
			size += temp;
		}
	}
	spin_unlock_irqrestore (&dummy->lock, flags);

	return size;
}
static DEVICE_ATTR (urbs, S_IRUGO, show_urbs, NULL);


static const struct hc_driver dummy_hcd;

static int dummy_start (struct usb_hcd *hcd)
{
	struct dummy		*dev;
	struct usb_bus		*bus;
	struct usb_device	*root;
	int			retval;

	dev = container_of (hcd, struct dummy, hcd);

	/*
	 * MASTER side init ... we emulate a root hub that'll only ever
	 * talk to one device (the slave side).  Also appears in sysfs,
	 * just like more familiar pci-based HCDs.
	 */
	spin_lock_init (&dev->lock);

	dev->dev.name = "hc";
	strncpy (dev->dev.dev.name, "usb host controller emulator",
			sizeof dev->dev.dev.name);
	dev->dev.dev.driver = &dummy_driver;
	dev->dev.dev.driver_data = dev;
	retval = driver_register (&dummy_driver);
	if (retval < 0)
		return retval;
	retval = sys_device_register (&dev->dev);
	if (retval < 0) {
		driver_unregister (&dummy_driver);
		return retval;
	}
	dev_info (&dev->dev.dev, "%s, driver " DRIVER_VERSION "\n",
			driver_desc);

	hcd->self.controller = &dev->dev.dev;
	hcd->controller = hcd->self.controller;

	/* FIXME 'urbs' should be a per-device thing, maybe in usbcore */
	device_create_file (hcd->controller, &dev_attr_urbs);

	init_timer (&dev->timer);
	dev->timer.function = dummy_timer;
	dev->timer.data = (unsigned long) dev;

	/* root hub will appear as another device */
	dev->hcd.driver = (struct hc_driver *) &dummy_hcd;
	dev->hcd.description = dummy_hcd.description;
	dev->hcd.product_desc = dev->dev.dev.name;
	dev->hcd.controller = &dev->dev.dev;

	bus = hcd_to_bus (&dev->hcd);
	bus->bus_name = dev->dev.dev.bus_id;
	usb_bus_init (bus);
	bus->op = &usb_hcd_operations;
	bus->hcpriv = &dev->hcd;

	/* FIXME don't require the pci-based buffer/alloc impls;
	 * the "generic dma" implementation still requires them,
	 * it's not very generic yet.
	 */
	if (hcd_buffer_create (&dev->hcd) != 0) {
clean0:
		sys_device_unregister (&dev->dev);
		driver_unregister (&dummy_driver);
		return -ENOMEM;
	}

	INIT_LIST_HEAD (&hcd->dev_list);
	usb_register_bus (bus);

	bus->root_hub = root = usb_alloc_dev (0, bus);
	if (!root) {
clean1:
		usb_deregister_bus (bus);
		goto clean0;
	}

	/* root hub enters addressed state... */
	dev->hcd.state = USB_STATE_READY;
	root->speed = USB_SPEED_HIGH;
	usb_connect (root);

	/* ...then configured, so khubd sees us. */
	if (hcd_register_root (&dev->hcd) != 0) {
		bus->root_hub = 0;
		usb_put_dev (root);
		retval = -ENODEV;
		goto clean1;
	}

	return 0;
}

static void dummy_stop (struct usb_hcd *hcd)
{
	struct usb_device	*root;
	struct dummy		*dev;
	struct usb_bus		*bus;

	dev = container_of (hcd, struct dummy, hcd);
	usb_gadget_unregister_driver (dev->driver);

	bus = hcd_to_bus (&dev->hcd);
	root = bus->root_hub;
	hcd->state = USB_STATE_QUIESCING;
	dev_dbg (hardware, "remove root hub\n");
	usb_disconnect (&root);

	hcd_buffer_destroy (&dev->hcd);
	usb_deregister_bus (bus);

	dev_info (hardware, "stopped\n");

	device_remove_file (hcd->controller, &dev_attr_urbs);
	sys_device_unregister (&dev->dev);

	driver_unregister (&dummy_driver);
}

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

static int dummy_h_get_frame (struct usb_hcd *hcd)
{
	return dummy_g_get_frame (0);
}

static const struct hc_driver dummy_hcd = {
	.description =		(char *) driver_name,
	.flags =		HCD_USB2,

	.start =		dummy_start,
	.stop =			dummy_stop,

	.hcd_alloc = 		dummy_alloc,
	.hcd_free = 		dummy_free,

	.urb_enqueue = 		dummy_urb_enqueue,
	.urb_dequeue = 		dummy_urb_dequeue,
	.free_config =		dummy_free_config,

	.get_frame_number = 	dummy_h_get_frame,

	.hub_status_data = 	dummy_hub_status,
	.hub_control = 		dummy_hub_control,
};

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

static int __init init (void)
{
	struct usb_hcd		*hcd;
	int			value;

	if (usb_disabled ())
		return -ENODEV;
	if ((hcd = dummy_alloc ()) == 0)
		return -ENOMEM;

	the_controller = container_of (hcd, struct dummy, hcd);
	value = dummy_start (hcd);

	if (value != 0) {
		dummy_free (hcd);
		the_controller = 0;
	}
	return value;
}
module_init (init);

static void __exit cleanup (void)
{
	dummy_stop (&the_controller->hcd);
	dummy_free (&the_controller->hcd);
	the_controller = 0;
}
module_exit (cleanup);




-------------------------------------------------------
This SF.net email is sponsored by: SlickEdit Inc. Develop an edge.
The most comprehensive and flexible code editor you can use.
Code faster. C/C++, C#, Java, HTML, XML, many more. FREE 30-Day Trial.
www.slickedit.com/sourceforge
_______________________________________________
[EMAIL PROTECTED]
To unsubscribe, use the last form field at:
https://lists.sourceforge.net/lists/listinfo/linux-usb-devel

Reply via email to